package com.simuwang.shiro.core;

import com.simuwang.base.common.exception.APIException;
import com.simuwang.shiro.core.bridge.AuthBridgeService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
public class ShiroDbRealmImpl extends ShiroDbRealm {
    private final AuthBridgeService authBridgeService;
    private final CredentialsMatcher credentialsMatcher;

    public ShiroDbRealmImpl(AuthBridgeService authBridgeService, CredentialsMatcher credentialsMatcher) {
        this.authBridgeService = authBridgeService;
        this.credentialsMatcher = credentialsMatcher;
    }

    @Override
    public AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
        return this.authBridgeService.getAuthorizationInfo(shiroUser);
    }

    @Override
    public AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        // 查询用户
        ShiroUser shiroUser = this.authBridgeService.findUserByUsername(username);
        if (shiroUser == null) {
            throw new UnknownAccountException("账号不存在");
        }
        if (!Objects.equals(1, shiroUser.getStatus())) {
            throw new APIException("账号已禁用");
        }
        shiroUser.setPermissionCodes(this.authBridgeService.findPermissions(shiroUser.getUserId()));
        return new SimpleAuthenticationInfo(shiroUser, shiroUser.getPassword(), getName());
    }

    @Override
    public void initCredentialsMatcher() {
        this.setCredentialsMatcher(this.credentialsMatcher);
    }
}
