package com.example.demo.config;

import com.example.demo.entity.Permission;
import com.example.demo.entity.Role;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
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.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class EnceladusShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    //进行权限校验时调用
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection){
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
        String userName=(String) principalCollection.getPrimaryPrincipal();
        User user=userService.findAllUserInfoByUsername(userName);
        List<String> stringRoleList=new ArrayList<>();
        List<String> stringPermissionList=new ArrayList<>();
        List<Role> roleList=user.getRoleList();

        for(Role role:roleList){
            stringRoleList.add(role.getName());
            List<Permission> permissionList=role.getPermissionList();
            for(Permission p:permissionList){
                if (null != p) {
                    stringPermissionList.add(p.getName());
                }
            }
        }
        simpleAuthorizationInfo.addRoles(stringRoleList);
        simpleAuthorizationInfo.addStringPermissions(stringPermissionList);
        SecurityUtils.getSubject().getSession().setAttribute("roleList", stringRoleList);
        return simpleAuthorizationInfo;
    }

    //登录校验调用
    @Override
    protected SimpleAuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username=(String) token.getPrincipal();
        System.out.println("principal:"+username);
        User user=userService.findAllUserInfoByUsername(username);
        System.out.println("principal password:"+user.getPassWord());

        String passWord=user.getPassWord();
        if(null==passWord|| "".equals(passWord)){
            return null;
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUserName(), user.getPassWord(),
                ByteSource.Util.bytes(user.getSalt()), getName());
        return authenticationInfo;
    }
}
