package com.iformall.shiro;

import javax.annotation.Resource;

import com.iformall.common.ErrorCode;
import com.iformall.enums.EnumMallUserStatus;
import com.iformall.exception.MallinkException;
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 com.iformall.domain.po.MallUserInfo;
import com.iformall.service.MallPermissionService;

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

    @Resource
    private MallUserInfoService userService;

    @Resource
    private MallPermissionService resourcesService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        MallUserInfo user= (MallUserInfo) SecurityUtils.getSubject().getPrincipal();//User{id=1, username='admin', password='3ef7164d1f6167cb9f2658c07d3c2f0a', enable=1}
//        Map<String,Object> map = new HashMap<String,Object>();
//        map.put("userid",user.getId());
//        List<SysPermission> resourcesList = resourcesService.list(map);
//         权限信息对象info,用来存放查出的用户的所有的角色（role）及权限（permission）
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        for(SysPermission resources: resourcesList){
//            info.addStringPermission(resources.getUrl());
//        }
        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.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);
    }
*/
}
