package com.emr.shiro;

import com.emr.controller.UserToken;
import com.emr.entity.Power_User;
import org.apache.commons.lang3.StringUtils;
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.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @author HJL
 * @create 2019/4/29
 */
public class MyRealm extends AuthorizingRealm {
      //获取权限列表
    /*@Autowired
    private PermissionService permissionService;
    //获取用户
    @Autowired
    private UserService userService;
    ////获取用户角色
    @Autowired
    private RoleService roleService;*/

    /**
     * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
        //获取登录时输入的用户名
        if (user != null) {
            Set<String> menus = user.getMenus();
            // 用户权限列表
            Set<String> permsSet = new HashSet<String>();
            if(null != menus && !menus.isEmpty()){
                for(String menu : menus){
                    if(StringUtils.isNoneBlank(menu)){
                        permsSet.add(menu);
                    }
                }
            }
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            info.setStringPermissions(permsSet);
            return info;
        }else{
            return null;
        }
    }

    /**
     * 认证回调函数,登录时调用.
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        //通过表单接收的用户名
        /*if (username != null && !"".equals(username)) {
            return new SimpleAuthenticationInfo(username, "123456", getName());
        }*/
        //Power_User user = token.getUser();
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, "123456", getName());
        return info;
    }
}
 

