package cn.hanghui.outapi.platform.common.handler;

import cn.hanghui.outapi.platform.common.entity.rest.RespCodeEnum;
import cn.hanghui.outapi.platform.common.exception.CommonException;
import cn.hanghui.outapi.platform.common.service.LoginService;
import cn.hutool.extra.spring.SpringUtil;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

@Component
@AllArgsConstructor(onConstructor_ = @Autowired)
public class LoginAuthorizedHandler implements AuthenticationProvider {

    private final LoginService loginService;

    /**
     * 登录校验
     *
     * @param authentication Authentication
     * @return Authentication
     * @throws AuthenticationException AuthenticationException
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String accountName = authentication.getName();
        String password = authentication.getCredentials().toString();
        // 获取封装用户信息的对象
        UserDetails userDetails = loginService.loadUserByUsername(accountName);
        // 进行密码的比对
        // 校验通过
        BCryptPasswordEncoder bCryptPasswordEncoder = SpringUtil.getBean(BCryptPasswordEncoder.class);
        if (bCryptPasswordEncoder.matches(password, userDetails.getPassword())) {
            return new UsernamePasswordAuthenticationToken(userDetails, password);
        }
        throw new CommonException(RespCodeEnum.ACCOUNT_OR_PASSWORD_ERROR);
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
