package com.ningdatech.pmapi.user.security.auth.agent;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * @Author LiuXinXin
 * @Date 2020/8/3 8:55 下午
 * @Version 1.0
 **/
public class AgentAuthProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        if (!(authentication instanceof AgentAuthToken)) {
            throw new RuntimeException("CustomAuthProvider 只支持 CustomAuthToken");
        }
        AgentAuthToken authenticationToken = (AgentAuthToken) authentication;
        String principal = (String) authenticationToken.getPrincipal();

        UserDetails user = userDetailsService.loadUserByUsername(principal);
        // 将用户定义的user放入token中，这样可以在session中查询到所有自定义的用户信息
        return new AgentAuthToken(user, user.getPassword(), user.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return AgentAuthToken.class.isAssignableFrom(authentication);
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

}
