package com.jd.lightapplication.security;

import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

@Data
@AllArgsConstructor
public class MobileAuthenticationProvider implements AuthenticationProvider {

    private  UserDetailServiceImpl userDetailService;

    //身份认证的逻辑
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        MobileAuthenticationToken authenticationToken = (MobileAuthenticationToken)authentication;
        //根据手机号（Principal）去查用户信息
        String phone = authentication.getPrincipal().toString();
        UserDetails userDetails = userDetailService.loadUserByPhone(phone);
        if (userDetails == null){
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }
        //将认证信息传入进去。
        MobileAuthenticationToken authenticationResult = new MobileAuthenticationToken(userDetails,userDetails.getAuthorities());
        //将请求的信息传递Token中。
        authenticationResult.setDetails(authenticationToken.getDetails());
        return authenticationResult;
    }
    //用于选去AuthenticationProvider的主要方法。
    @Override
    public boolean supports(Class<?> authentication) {
        return MobileAuthenticationToken.class.isAssignableFrom(authentication);
    }
}

