package com.yunniu.farming.shiro;

import com.yunniu.farming.webadmin.model.Admin;
import com.yunniu.farming.webadmin.service.AdminService;
import com.yunniu.farming.webadmin.service.MenuService;
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.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;

public class UserRealm extends AuthorizingRealm {

    @Resource
    private MenuService menuService;

    @Resource
    private AdminService adminService;


    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//		Admin admin = (Admin) SecurityUtils.getSubject().getSession().getAttribute("currentUser");
//		int userId = admin.getId();

//		List<String> permsList = new ArrayList<>();
//		permsList = adminService.findPermission(userId);
//
//		// 用户权限列表
//		Set<String> permsSet = new HashSet<String>();
//		for (String perm : permsList) {
//			if (perm != null && !("".equals(perm))) {
//				permsSet.add(perm);
//			}
//		}
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//		info.setStringPermissions(permsSet);
        return info;
    }

    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 1. 把 AuthenticationToken 转换为 UsernamePasswordToken
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;

        // 2. 从 UsernamePasswordToken 中来获取 username
        String username = upToken.getUsername();
        // 判断用户名是否存在，若存在，返回user对象
        Admin admin = adminService.getAdminByAccount((username));
        if (admin != null && 2 == admin.getPermissions()) {
            admin.setAbolishState("1");
        }
        if (admin != null && "1".equals(admin.getAbolishState())) {
            admin = null;
        }
        // 盐值.
        ByteSource credentialsSalt = ByteSource.Util.bytes(admin.getAdminSalt());
        // 自动完成密码比对 - 密码的比对:
        // 通过 AuthenticatingRealm 的 credentialsMatcher 属性来进行的密码的比对!
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, admin.getAdminPassword(), credentialsSalt, getName());
        SecurityUtils.getSubject().getSession().setAttribute("currentUser", admin);
        SecurityUtils.getSubject().getSession().setTimeout(1800000);
        return info;
    }

}
