package com.iformall.shiro;

import com.iformall.common.ErrorCode;
import com.iformall.domain.po.MallUserInfo;
import com.iformall.enums.EnumMallUserStatus;
import com.iformall.service.MallUserInfoService;
import org.apache.shiro.SecurityUtils;
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.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.Set;

/**
 * Created by yangqj on 2017/4/21.
 */
public class MyShiroRealm extends AuthorizingRealm {

    @Resource
    private MallUserInfoService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        MallUserInfo user= (MallUserInfo) SecurityUtils.getSubject().getPrincipal();
        Set<String> permissionSet = userService.getUserPermissions(user);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permissionSet);
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户的输入的账号.
        String username = (String)token.getPrincipal();
        MallUserInfo user = userService.getByUsername(username);
        if(user == null) {
            throw new UnknownAccountException(ErrorCode.USER_IS_EMPTY.getMessage());
        }
        if(user.getTenantId().equals("1")) {
            // 只支持租户为1的用户
            throw new UnknownAccountException("租户不支持");
        }
        if(user.getStatus()==null ||
                !EnumMallUserStatus.VALID.getCode().equals(user.getStatus())) {//用户被禁用
            throw new DisabledAccountException(ErrorCode.USER_IS_LOCKED.getMessage());
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user, //用户
                user.getPassword(), //密码
                ByteSource.Util.bytes(username),
                getName()  //realm name
        );
        // 当验证都通过后，把用户信息放在session里
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute(UserSession.userInfo, user);
        session.setAttribute(UserSession.userId, user.getId());
        session.setAttribute(UserSession.tenantId, user.getTenantId());
        return authenticationInfo;
    }


    /**
     * 指定principalCollection 清除
     */
  /*  public void clearCachedAuthorizationInfo(PrincipalCollection principalCollection) {

        SimplePrincipalCollection principals = new SimplePrincipalCollection(
                principalCollection, getName());
        super.clearCachedAuthorizationInfo(principals);
    }
*/
}
