com.sirdc.modules.security.SystemAuthorizingRealm.java Source code

Java tutorial

Introduction

Here is the source code for com.sirdc.modules.security.SystemAuthorizingRealm.java

Source

/**
 * Copyright &copy; 2012-2013 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.sirdc.modules.security;

import java.util.List;

import javax.annotation.PostConstruct;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sirdc.modules.core.servlet.ValidateCodeServlet;
import com.sirdc.modules.entity.sys.SysLogin;
import com.sirdc.modules.entity.sys.SysUser;
import com.sirdc.modules.service.sys.SysLoginLogService;
import com.sirdc.modules.service.sys.SysLoginService;
import com.sirdc.modules.service.sys.SysRolePermissionService;
import com.sirdc.modules.service.sys.SysUserService;
import com.sirdc.modules.shiro.exception.CaptchaException;
import com.sirdc.modules.shiro.matcher.RetryLimitHashedCredentialsMatcher;
import com.sirdc.modules.sys.security.Principal;
import com.sirdc.modules.sys.util.SysGlobals;
import com.sirdc.modules.util.SysUserUtils;
import com.sirdc.modules.utils.CollectionsUtils;
import com.sirdc.modules.utils.StringUtils;

/**
 * ?
 * 
 * @author ThinkGem
 * @version 2013-5-29
 */
@Service
public class SystemAuthorizingRealm extends AuthorizingRealm {

    @Autowired
    private SysLoginService sysLoginService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private RetryLimitHashedCredentialsMatcher retryMather;
    @Autowired
    private SysRolePermissionService sysRolePermissionService;
    @Autowired
    private SysLoginLogService sysLoginLogService;

    /**
     * ?, 
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
            throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;

        validCode(token);//???
        SysLogin loginUser = sysLoginService.getUserByLoginName(token.getUsername());

        if (loginUser == null) {
            throw new UnknownAccountException();//??
        }

        if (loginUser.getState().equals(SysGlobals.AccountStates.DISABLE)) {
            throw new LockedAccountException();//???
        }

        SysUser userInfo = sysUserService.getById(loginUser.getSysId());

        //??
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                new SysPrincipal(loginUser, userInfo, token.isApi()), //???
                loginUser.getPassword(), //?
                ByteSource.Util.bytes(loginUser.getSaltKey()), //()
                getName());
        return authenticationInfo;
    }

    /**
     * ?, ???
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //??
        SysPrincipal principal = SysUserUtils.getSysPrincipal();
        String roleId = principal.getRoleId();
        String deptId = principal.getDeptId();
        sysLoginLogService.updateLoginLog(principal);//

        //???
        List<String> permissions = sysRolePermissionService.queryPermissionByRoleIdDeptId(roleId, deptId);
        SysLogin user = sysLoginService.getUserByLoginName(principal.getUserId());
        if (user != null && CollectionsUtils.isNotEmpty(permissions)) {
            SimpleAuthorizationInfo info = constructInfo(permissions);//???
            info.addRole(roleId.toString());//
            return info;
        }
        return null;
    }

    /**
     * ???
     * @author: weihuang.peng
     * @param authcToken
     */
    public void validCode(UsernamePasswordToken token) {
        // ??
        Session session = SecurityUtils.getSubject().getSession();
        String code = (String) session.getAttribute(ValidateCodeServlet.VALIDATE_CODE);
        if (token.isApi()) {
            return;
        }
        if (token.getCaptcha() == null || !token.getCaptcha().toUpperCase().equals(code)) {
            throw new CaptchaException("??");
        }
    }

    /**
     * ??
     * @author: weihuang.peng
     * @param permissions
     * @return
     */
    public SimpleAuthorizationInfo constructInfo(List<String> permissions) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        for (String permission : permissions) {
            if (StringUtils.isNotBlank(permission)) {
                info.addStringPermission(permission);//?????
            }
        }
        //?
        return info;
    }

    /**
     * session?
     * @author: weihuang.peng
     */
    public void invalidate() {
        SysPrincipal principal = SysUserUtils.getSysPrincipal();
        sysLoginLogService.updateLogoutLog(principal);
    }

    /**
     * ?Hash
     */
    @PostConstruct
    public void initCredentialsMatcher() {
        setCredentialsMatcher(retryMather);
    }

    /**
     * ?????
     */
    public void clearCachedAuthorizationInfo(String principal) {
        SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
        clearCachedAuthorizationInfo(principals);
    }

    /**
     * ?????
     */
    public void clearCachedAuthorizationInfo(Principal principal) {
        SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
        clearCachedAuthorizationInfo(principals);
    }

    /**
     * ??
     */
    public void clearAllCachedAuthorizationInfo() {
        Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
        if (cache != null) {
            for (Object key : cache.keys()) {
                cache.remove(key);
            }
        }
    }
}