package com.iamberry.wechat.realm;

import com.iamberry.sys.Admin;
import com.iamberry.wechat.face.sys.SysService;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class IamberryRealm extends AuthorizingRealm {

    private static final Logger LOGGER = LoggerFactory.getLogger(IamberryRealm.class);

    @Autowired
    private SysService sysService;

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.info(token.getPrincipal() + " - 申请认证...");
        }
        UsernamePasswordToken passwordToken = (UsernamePasswordToken) token;
        // 查找用户信息
        Admin temp = new Admin();
        temp.setAdminAccount(passwordToken.getUsername());
        Admin admin = sysService.get(temp);
        if (admin == null) {
            throw new UnknownAccountException("NOT_ADMIN");
        }
        if (admin.getAdminStatus() == 2) {
            throw new LockedAccountException("ADMIN_LOCKED");
        }
        // 返回信息
        return new SimpleAuthenticationInfo(admin, admin.getAdminPassword().toUpperCase(), getName());
    }

    /**
     * 授权（权限认证 ）
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.info(principals.toString() + " - 申请授权...");
        }
        // 获取登录时输入的用户名
        Admin admin = (Admin) principals.getPrimaryPrincipal();
        // 根据id，查询用户的权限
        List<String> permissions = sysService.listSymbolByRule(admin.getRuleId());
        // 封装权限
        Set<String> perms = new HashSet<>(permissions);
        //权限信息对象info,用来存放查出的用户的所有的角色（role）及权限（permission）
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(perms);
        return info;
    }
}
