package com.atlassian.stash.internal.auth.trusted;

import com.atlassian.event.api.EventPublisher;
import com.atlassian.bitbucket.event.auth.AuthenticationFailureEvent;
import com.atlassian.bitbucket.event.auth.AuthenticationSuccessEvent;
import com.atlassian.bitbucket.user.UserService;
import com.atlassian.security.auth.trustedapps.filter.AuthenticationListener;
import com.atlassian.security.auth.trustedapps.filter.Authenticator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TrustedApplicationsAuthListener implements AuthenticationListener {

    static final String AUTHENTICATION_METHOD = "trusted-apps";

    private final EventPublisher eventPublisher;
    private final UserService userService;

    @Autowired
    public TrustedApplicationsAuthListener(EventPublisher eventPublisher, UserService userService) {
        this.eventPublisher = eventPublisher;
        this.userService = userService;
    }

    @Override
    public void authenticationSuccess(Authenticator.Result result, HttpServletRequest request, HttpServletResponse response) {
        userService.preauthenticate(result.getUser().getName());

        eventPublisher.publish(new AuthenticationSuccessEvent(this, result.getUser().getName(), AUTHENTICATION_METHOD));
    }

    @Override
    public void authenticationFailure(Authenticator.Result result, HttpServletRequest request, HttpServletResponse response) {
        eventPublisher.publish(new AuthenticationFailureEvent(this, null, AUTHENTICATION_METHOD, null));
    }

    @Override
    public void authenticationError(Authenticator.Result result, HttpServletRequest request, HttpServletResponse response) {
    }

    @Override
    public void authenticationNotAttempted(HttpServletRequest request, HttpServletResponse response) {
    }
}
