package ru.ulstu.user.component;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import ru.ulstu.configuration.Constants;
import ru.ulstu.user.service.UserSessionService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Component
public class UserSessionLoginHandler extends SavedRequestAwareAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    private final Logger log = LoggerFactory.getLogger(UserSessionLoginHandler.class);
    private final UserSessionService userSessionService;

    public UserSessionLoginHandler(UserSessionService userSessionService) {
        super();
        this.userSessionService = userSessionService;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        super.onAuthenticationSuccess(request, response, authentication);
        final String login = authentication.getName();
        final String ipAddress = IpAddressResolver.getRemoteAddr(request);
        final String host = request.getRemoteHost();
        log.debug("Authentication Success for {}@{} ({})", login, ipAddress, host);
        HttpSession session = request.getSession(false);
        if (session != null) {
            final String sessionId = session.getId();
            userSessionService.createUserSession(sessionId, login, ipAddress, host);
            session.setAttribute(Constants.SESSION_ID_ATTR, sessionId);
            session.setMaxInactiveInterval(Constants.SESSION_TIMEOUT_SECONDS);
        }
    }
}
