All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.haoxuer.discover.user.shiro.realm.UserAuthorization Maven / Gradle / Ivy

There is a newer version: 3.3.18-20230117
Show newest version
package com.haoxuer.discover.user.shiro.realm;

import com.haoxuer.discover.user.shiro.utils.UserUtil;
import com.haoxuer.discover.user.data.entity.UserInfo;
import com.haoxuer.discover.user.data.entity.UserRole;
import com.haoxuer.discover.user.data.service.UserInfoService;

import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UserAuthorization {

    Logger logger = LoggerFactory.getLogger("ada");


    private UserInfoService userInfoService;

    public UserAuthorization(UserInfoService userInfoService) {
        this.userInfoService = userInfoService;
    }

    /**
     * 授权
     *
     * @param principals
     * @return
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Object o = principals.getPrimaryPrincipal();
        if (o instanceof ShiroUser) {

        } else {
            return new SimpleAuthorizationInfo();
        }

        ShiroUser shiroUser = (ShiroUser) o;
        UserInfo user = userInfoService.findById(shiroUser.getId());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        if (user != null) {
            logger.info("doGetAuthorizationInfo:" + shiroUser.getName());
            // 把principals放session中
            UserUtil.getSession().setAttribute(String.valueOf(user.getId()), SecurityUtils.getSubject().getPrincipals());
            UserUtil.setCurrentUser(user);

            Set authorities = new HashSet();
            /**
             * 赋予角色
             */
            for (UserRole userRole : user.getRoles()) {
                info.addRole(userRole.getName());
                logger.info("role:" + userRole.getName());
            }
            if (user != null) {
                authorities.addAll(userInfoService.findAuthorities(user.getId()));
            }
            // //设置登录次数、时间
            info.addStringPermissions(authorities);
            userInfoService.updateUserLogin(user);
        }

        return info;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy