package com.cpop.core.utils;

import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @author: DB
 * @date: 2022-09-25 17:01
 * @Description:
 */
@NoArgsConstructor
public class PasswordEncoder extends BCryptPasswordEncoder {

    @Autowired
    private RsaUtils rsaUtils;

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        // 接收到的前端的密码
        String pwd = rawPassword.toString();
        //针对+变空格进行处理
        pwd = pwd.replace(" ", "+");
        // 进行rsa解密
        try {
            pwd = rsaUtils.decrypt(pwd);
        } catch (Exception e) {
            throw new BadCredentialsException(e.getMessage());
        }
        if (encodedPassword != null && !encodedPassword.isEmpty()) {
            return BCrypt.checkpw(pwd, encodedPassword);
        } else {
            return false;
        }
    }
}
