package com.simuwang.base.components;

import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.simuwang.base.config.DaqProperties;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;

public class ShiroRsaCredentialsMatcher extends SimpleCredentialsMatcher {
    private final DaqProperties properties;

    public ShiroRsaCredentialsMatcher(DaqProperties properties) {
        this.properties = properties;
    }

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        Object credentials = token.getCredentials();
        String tokenHashedPassword;
        if (credentials instanceof char[] temp) {
            tokenHashedPassword = new String(temp);
        } else {
            tokenHashedPassword = credentials.toString();
        }
        // 前端传递密码解密
        String encryptedPassword = this.encryptPassword(tokenHashedPassword);
        // 数据库密码解密
        String storedEncryptedPassword = this.encryptPassword(info.getCredentials().toString());
        return encryptedPassword.equals(storedEncryptedPassword);
    }

    private String encryptPassword(String password) {
        try {
            DaqProperties.SecurityRsa securityRsa = this.properties.getSecurityRsa();
            return new RSA(securityRsa.getPrivateKey(), null).decryptStr(password, KeyType.PrivateKey);
        } catch (Exception e) {
            throw new IncorrectCredentialsException();
        }
    }
}
