/**
 * Copyright (c) 2020 fumeiai All rights reserved.
 *
 *
 *
 * 版权所有，侵权必究！
 */

package com.lz.modules.sys.oauth2;

import com.lz.modules.app.entity.StaffEntity;
import com.lz.modules.app.service.StaffService;
import com.lz.modules.sys.entity.SysUserEntity;
import com.lz.modules.sys.entity.SysUserEntityDto;
import com.lz.modules.sys.entity.SysUserTokenEntity;
import com.lz.modules.sys.service.ShiroService;
import lombok.extern.slf4j.Slf4j;
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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 认证
 *
 * @author Mark sunlightcs@gmail.com
 */
@Component
@Slf4j
public class OAuth2Realm extends AuthorizingRealm {
    @Autowired
    private ShiroService shiroService;

    @Autowired
    private StaffService staffService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SysUserEntity user = (SysUserEntity)principals.getPrimaryPrincipal();
        //用户权限列表
        Set<String> permsSet = shiroService.getUserPermissions(user);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;
    }

    /**
     * 认证(登录时调用)
     *
     *
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String accessToken = (String) token.getPrincipal();
        //根据accessToken，查询用户信息
        SysUserTokenEntity tokenEntity = shiroService.queryByToken(accessToken);
        //token失效
        if(tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()){
            throw new IncorrectCredentialsException("token失效，请重新登录");
        }

        //查询用户信息
        SysUserEntity user = null;
        StaffEntity staffEntity = staffService.selectStaffById(tokenEntity.getUserId());
        if(tokenEntity.getType() == 0){         //如果是系统用户
            log.info("token判定为系统用户");
            user = shiroService.queryUser(tokenEntity.getUserId());
            if(staffEntity != null){
                log.info("查询到系统用户信息");
                user.setAvatar(staffEntity.getAvatar());
            }

        }else{
            user = new SysUserEntity();
            user.setMobile(staffEntity.getMobile());
            user.setAvatar(staffEntity.getAvatar());
            user.setUserId(staffEntity.getId());
            user.setEmail(staffEntity.getEmail());
            user.setStatus(1);
            user.setType(1);
            user.setUsername(staffEntity.getMobile());
            user.setRealName(staffEntity.getName());
            user.setUserNo(staffEntity.getMobile());
        }
        //账号锁定
        if(user.getStatus() == 0){
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, accessToken, getName());
        return info;
    }

}
