package com.jiayue.ssi.config;

import cn.hutool.crypto.SmUtil;
import com.jiayue.ssi.constant.SecretKeyConstants;
import com.jiayue.ssi.entity.SysUser;
import com.jiayue.ssi.util.SM2CryptUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;

/**
 * security密码对比
 *
 * @author xsl
 * @since 2023/03/13
 */
@Slf4j
public class MyAuthenticationProvider extends DaoAuthenticationProvider {

    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        if (authentication.getCredentials() == null) {
            this.logger.debug("Authentication failed: no credentials provided");
            throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
        } else {
            String presentedPassword = authentication.getCredentials().toString();

            String decryptPassword = null;
            //解密登陆密码
            try {
                decryptPassword = SmUtil.sm3(presentedPassword).toUpperCase();

//            if (!this.passwordEncoder.matches(decryptPassword, userDetails.getPassword())) {
//                this.logger.debug("Authentication failed: password does not match stored value");
//                throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
//            }
                // 先检测存储密码的完整性
                SysUser user = (SysUser) userDetails;

                if ("1".equals(user.getPassword())){
                    throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
                }

                String dbpwd = "";
                try {
                    dbpwd = SM2CryptUtils.decrypt(user.getPassword(), SecretKeyConstants.SERVER_PRIVATE_KEY);
                }
                catch (Exception e1){
                    this.logger.error("账号："+user.getUsername()+"，密码完整性校验失败！");
                    throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
                }
                if (!dbpwd.equals(user.getCheckPassword())){
                    this.logger.error("账号："+user.getUsername()+"，密码完整性校验失败！");
                    throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
                }

                if (!decryptPassword.equals(dbpwd)) {
                    this.logger.debug("Authentication failed: password does not match stored value");
                    throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
                }
            } catch (Exception e) {
//                log.error("用户密码解密错误，无法登录！");
                throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
            }
        }
    }
}
