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

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 2020/7/15 10:39
 */
public class ImeiAuthenticationProvider implements AuthenticationProvider {

    private ImeiUserDetailsServiceImpl userDetailsService;


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

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

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

}
