package com.hz.pm.api.user.security.auth.mh;

import lombok.Setter;
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;

/**
 * <p>
 * AgentAuthProvider
 * </p>
 *
 * @author WendyYang
 * @since 20:41 2023/12/15
 */
@Setter
public class MhAuthProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        MhAuthToken authenticationToken = (MhAuthToken) authentication;
        String principal = (String) authenticationToken.getPrincipal();

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

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

}
