package com.example.myshiro.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.myshiro.domain.Users;
import com.example.myshiro.mapper.UsersMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

//自定义用户的realm
@Component
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UsersMapper usersMapper;
//    自定义授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
    //    自定义认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 1.获取用户输入的用户名
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();

        // 2.根据用户名查询用户
        QueryWrapper<Users> wrapper = new QueryWrapper<Users>().eq("username", username);
        Users users = usersMapper.selectOne(wrapper);

        // 3.将查询到的用户封装为认证信息
        if (users == null) {
            throw new UnknownAccountException("(用户名)账户不存在");
        }
        /**
         * 参数1：用户
         * 参数2：密码
         * 参数3：Realm名
         */
        //        return new SimpleAuthenticationInfo(users, users.getPassword(), "myRealm");

        /**
         * 参数1：用户
         * 参数2：密码
         * 参数3：盐
         * 参数4：Realm名
         */
        return new SimpleAuthenticationInfo(users, users.getPassword(), ByteSource.Util.bytes(users.getSalt()),"myRealm");

    }
}

