package cn.ftebox.realm;

import cn.ftebox.entity.Blogger;
import cn.ftebox.service.BloggerService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

public class MyRealm extends AuthorizingRealm {
    @Resource
    private BloggerService bloggerService;

    /**
     * 获得授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 登录验证
     * token：令牌，基于用户名密码的令牌

     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 从令牌中取出用户名
        String userName = (String) token.getPrincipal();
        //让Shiro去验证账号密码
        Blogger blogger = bloggerService.getByUserName(userName);
        if (blogger!=null){
            SecurityUtils.getSubject().getSession().setAttribute("currentUser",blogger);
            return new SimpleAuthenticationInfo(blogger.getUserName(),blogger.getPassword(),getName());
        }
        return null;
    }
}
