package com.community.huiju.security;

import com.community.commom.constant.Constant;
import com.community.huiju.exception.WisdomSecurityException;
import com.community.huiju.service.IRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;

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

/**
 * 授权过程
 *
 * @author weiximei
 */
@Slf4j
public class RestPreAuthenticateProvider implements AuthenticationProvider {

   private HttpServletRequest request;

   private IRoleService iRoleService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        log.info("provider session: {}", request.getSession().getId());
        TokenAuthrentication tokenAuthrentication = (TokenAuthrentication) authentication.getPrincipal();
        if (null != tokenAuthrentication) {
            Collection<GrantedAuthority> grantedAuthorityList = tokenAuthrentication.getAuthorities();
            if (null != grantedAuthorityList && grantedAuthorityList.size() > 0) {
                boolean isNone= grantedAuthorityList.stream().anyMatch(e->e.getAuthority().equals(Constant.ROLE_NONE));
                if (isNone) {
                    tokenAuthrentication.setAuthenticated(false);
                    return tokenAuthrentication;
                }
                boolean hasPermission = iRoleService.hasPermission(request);
                tokenAuthrentication.setAuthenticated(hasPermission);
                return tokenAuthrentication;
            }

        }


        throw new WisdomSecurityException("没有授权角色!");
    }

    /**
     * 是否授权过程
     *
     * @param authentication
     * @return
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return PreAuthenticatedAuthenticationToken.class.isAssignableFrom(authentication)
                || TokenAuthrentication.class.isAssignableFrom(authentication);
    }

    public RestPreAuthenticateProvider(HttpServletRequest request, IRoleService iRoleService) {
        this.request = request;
        this.iRoleService = iRoleService;
    }
}
