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

com.github.dennisit.vplus.data.security.AuthorityRealm Maven / Gradle / Ivy

/*--------------------------------------------------------------------------
 *  Copyright (c) 2010-2020, Elon.su All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the elon developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: Elon.su, you can also mail [email protected]
 *--------------------------------------------------------------------------
*/
package com.github.dennisit.vplus.data.security;

import com.github.dennisit.vplus.data.enums.common.EnableEnum;
import com.github.dennisit.vplus.data.utils.DigestUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Elon.su
 */
public class AuthorityRealm extends AuthorizingRealm {


    private static final Logger LOG = LoggerFactory.getLogger(AuthorityRealm.class);

    /**
     * 用户登录授权接口
     */
    private AuthorityIFace authorityIface;

    /**
     * 是否只允许后台用户登录
     */
    private boolean onlyAdmin = false;


    public AuthorityRealm(AuthorityIFace authorityIface){
        this.authorityIface = authorityIface;
    }

    public AuthorityRealm(CacheManager cacheManager, CredentialsMatcher matcher) {
        super(cacheManager, matcher);
    }

    public AuthorityRealm(CacheManager cacheManager, CredentialsMatcher matcher, AuthorityIFace authorityIface) {
       this(cacheManager, matcher, authorityIface, false);
    }

    public AuthorityRealm(CacheManager cacheManager, CredentialsMatcher matcher, AuthorityIFace authorityIface, boolean onlyAdmin) {
        super(cacheManager, matcher);
        this.authorityIface = authorityIface;
        this.onlyAdmin = onlyAdmin;
    }

    public AuthorityRealm(CacheManager cacheManager) {
        super(cacheManager);
    }

    /**
     * 角色权限
     * 没有使用缓存的时候,不断刷新页面的话,这个代码会不断执行, 当其实没有必要每次都重新设置权限信息,所以我们需要放到缓存中进行管理;
     * 当放到缓存中时,这样的话,doGetAuthorizationInfo就只会执行一次了, 缓存过期之后会再次执行。
     * @param principals 授权会话
     * @return 授权信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Authority authority = (Authority) principals.getPrimaryPrincipal();
        LOG.info("当前登录用户:{}", authority.getShowName());
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addStringPermissions(authorityIface.selectPermissions(authority.getUserId()));
        authorizationInfo.addRoles(authorityIface.selectRoles(authority.getUserId()));
        return authorizationInfo;
    }

    /**
     *  
     *   public boolean signIn(SignInParam param) throws Exception {
     *       if(StringUtils.isBlank(param.getUsername()) || StringUtils.isBlank(param.getPassword())){
     *           throw new ApiException("用户或密码不能为空");
     *       }
     *
     *       Subject subject = SecurityUtils.getSubject();
     *
     *       UsernamePasswordToken token = new UsernamePasswordToken(param.getUsername(), param.getPassword());
     *      try {
     *           token.setRememberMe(param.isRememberMe());
     *           subject.login(token);
     *           return true;
     *       } catch (IncorrectCredentialsException | UnknownAccountException  e) {
     *           token.clear();
     *           throw new ApiException("账号或密码不正确!", e);
     *       } catch (LockedAccountException lae) {
     *           token.clear();
     *           throw new ApiException("用户已经被锁定不能登录,请与管理员联系");
     *       } catch (AuthenticationException e) {
     *           token.clear();
     *           throw new ApiException("用户或密码不正确", e);
     *       } catch (Throwable e) {
     *           token.clear();
     *          throw new ApiException("网络错误,请稍后重试!", e);
     *       }
     *   }
     *  
     *
     * 认证信息.(身份验证) : Authentication 是用来验证用户身份
     * @return 验证后授权信息
     * @throws AuthenticationException 授权异常
     */

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
            throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());
        Authority authority = authorityIface.selectByUserName(username);
        if(null == authority){
            throw new UnknownAccountException("账号不存在");
        }
        LOG.debug("加密:" + DigestUtils.md5Hex(password, authority.getSalt()) + ",比较:" + authority.getPassword());
        if(!authority.getPassword().equals(DigestUtils.md5Hex(password, authority.getSalt()))) {
            throw new IncorrectCredentialsException("密码不正确");
        }
        // 仅让管理员登录, 角色信息中没有配置角色标识普通站内用户
        if(onlyAdmin && !CollectionUtils.isEmpty(authorityIface.selectRoles(authority.getUserId()))){
            throw new AuthenticationException("非系统管理账号");
        }
        if(EnableEnum.DISABLE.getValue() == authority.getEnabled()){
            throw new LockedAccountException("账号锁定");
        }
        return new SimpleAuthenticationInfo(authority, password, getName());
    }

    public void setOnlyAdmin(boolean onlyAdmin) {
        this.onlyAdmin = onlyAdmin;
    }

    public void setAuthorityIFace(AuthorityIFace authorityIface){
        this.authorityIface = authorityIface;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy