package com.izouma.awesomeadmin.shiro;

import com.izouma.awesomeadmin.model.SysRole;
import com.izouma.awesomeadmin.model.UserInfo;
import com.izouma.awesomeadmin.service.SysRoleService;
import com.izouma.awesomeadmin.service.UserInfoService;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class Bos_realm extends AuthorizingRealm {
    private static Logger logger = Logger.getLogger(Bos_realm.class);

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private SysRoleService sysRoleService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        try {
            UserInfo userInfo = (UserInfo) principalCollection.getPrimaryPrincipal();
            //获取角色数据权限授权
            SysRole sysRole = sysRoleService.getSysRoleById(userInfo.getRoleId());
            String[] permission = sysRole.getPermission().split(",");
            for (String perm : permission) {
                info.addStringPermission(perm);
            }
        } catch (Exception e) {
            logger.error("doGetAuthorizationInfo", e);
        }
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取令牌(里面存放new UsernamePasswordToken放入的账号和密码)
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;

        UserInfo userInfo = userInfoService.login(userToken.getUsername(), new String(userToken.getPassword()));

        if (userInfo != null) {
            //参数1.用户认证的对象(subject.getPrincipal();返回的对象),
            //参数2.从数据库根据用户名查询到的用户的密码
            //参数3.把当前自定义的realm对象传给SimpleAuthenticationInfo,在配置文件需要注入
            AuthenticationInfo Info = new SimpleAuthenticationInfo(userInfo, new String(userToken.getPassword()), this.getName());
            return Info;
        } else {
            return null;
        }
    }
}
