package com.skr.mdm.authentication.user.oaid;

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;

/**
 * @author nfq
 * @date 2021/1/29 15:14
 */
public class OaidAuthenticationProvider implements AuthenticationProvider {

    private OaidUserDetailsServiceImpl userDetailsService;


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        OaidAuthenticationToken authenticationToken = (OaidAuthenticationToken) authentication;
        String principal = (String) authenticationToken.getPrincipal();
        String companyId = (String) authenticationToken.getCompanyId();
        userDetailsService.setCompanyId(Integer.valueOf(companyId));
        // 校验oaid
        UserDetails userDetails = userDetailsService.loadUserByUsername(principal);
        if (userDetails == null) {
            throw new OaidAuthenticationException(
                    "UserDetailsService returned null, which is an interface contract violation");
        }
        OaidAuthenticationToken authenticationResult  = new OaidAuthenticationToken(userDetails.getAuthorities(), userDetails, companyId);
        authenticationResult.setDetails(authentication.getDetails());
        return authenticationResult;
    }

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

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