package com.persagy.dmp.auth.handler;

import com.persagy.dmp.auth.service.AuthService;
import com.persagy.dmp.auth.service.AuthServiceFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.security.auth.message.AuthException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 上下文 拦截器
 * @author Charlie Yu
 * @date 2021-06-25
 */
public class AppContextHandler extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        AuthService authService = AuthServiceFactory.getAuthService();
        // 登录校验
        boolean isSuccess = authService.validateLogin(request, response);
        if(!isSuccess) {
            // 鉴权器处理
            authService.loginFailure(request, response);
            throw new AuthException("登录认证失败!");
        }
        // 登录成功处理
        authService.loginSuccess(request, response);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        AuthServiceFactory.getAuthService().release(request, response);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthServiceFactory.getAuthService().release(request, response);
    }
}
