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.commons.lang.StringUtils;
import org.apache.log4j.Logger;
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;

import java.util.Arrays;
import java.util.List;

public abstract class BaseRealm extends AuthorizingRealm {
    protected static Logger logger = Logger.getLogger(PhoneCodeRealm.class);

    @Autowired
    protected UserInfoService userInfoService;

    @Autowired
    protected SysRoleService sysRoleService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        try {
            UserInfo userInfo = (UserInfo) principalCollection.getPrimaryPrincipal();
            //获取角色数据权限授权
            List<SysRole> sysRoles = sysRoleService.getUserRoles(userInfo.getId());
            for (SysRole sysRole : sysRoles) {
                info.addRole(sysRole.getEnname());
                if (StringUtils.isNotEmpty(sysRole.getPermission())) {
                    info.addStringPermissions(Arrays.asList(sysRole.getPermission().split(",")));
                }
            }
        } catch (Exception e) {
            logger.error("doGetAuthorizationInfo", e);
        }
        return info;
    }
}
