package com.eactive.httpmockserver.common.interceptor;


import com.eactive.httpmockserver.common.exception.UserNotLoginException;
import com.eactive.httpmockserver.common.util.SecurityUtil;
import com.eactive.httpmockserver.user.entity.AnonymousUser;
import com.eactive.httpmockserver.user.entity.User;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 인증여부 체크 인터셉터
 *
 * @author
 * @version 1.0
 */


public class AuthenticInterceptor implements AsyncHandlerInterceptor {

    /**
     * 관리자 접근 권한 패턴 목록
     */
    private List<String> adminAuthPatternList;

    private static AntPathMatcher pathMatcher = new AntPathMatcher();

    public List<String> getAdminAuthPatternList() {
        return adminAuthPatternList;
    }

    public void setAdminAuthPatternList(List<String> adminAuthPatternList) {
        this.adminAuthPatternList = adminAuthPatternList;
    }

    /**
     * 인증된 사용자 여부로 인증 여부를 체크한다.
     * 관리자 권한에 따라 접근 페이지 권한을 체크한다.
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //인증된사용자 여부
        User currentUser = SecurityUtil.getCurrentUser();

        if (currentUser == null || currentUser instanceof AnonymousUser) {
            throw new UserNotLoginException();
        }

        boolean found = findPattern(request.getRequestURI());

        if (found) {
            if (currentUser.getUserSecurity() != null && "ROLE_ADMIN".equals(currentUser.getUserSecurity())) {
                return true;
            } else {
                throw new UserNotLoginException();
            }
        }
        return true;

    }

    boolean findPattern(String path) {
        for (String pattern : adminAuthPatternList) {
            if (pathMatcher.match(pattern, path)) {
                return true;
            }
        }
        return false;
    }

}
