package com.ningdatech.kqapi.security.password;

import com.ningdatech.kqapi.user.helper.LoginHelper;
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>
 * UsernamePasswordAuthProvider
 * </p>
 *
 * @author LiuXinXin
 * @since 2020/8/3 8:55 下午
 **/
@Setter
public class PasswordAuthProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    private LoginHelper loginHelper;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        UsernamePasswordAuthToken authToken = (UsernamePasswordAuthToken) authentication;

        UserDetails user = userDetailsService.loadUserByUsername((String) authToken.getPrincipal());
        loginHelper.checkPassword(user, authToken);
        // 校验用户是否有当前端的登陆权限
        // 将用户定义的user放入token中，这样可以在session中查询到所有自定义的用户信息
        return new UsernamePasswordAuthToken(user, user.getPassword(), user.getAuthorities());
    }

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

}
