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

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 UuidAuthenticationProvider implements AuthenticationProvider {

    private UuidUserDetailsServiceImpl userDetailsService;


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

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

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