package com.qxgmat.util.shiro;

import com.nuliji.tools.shiro.inter.RealmAuthenticationToken;
import com.qxgmat.data.dao.entity.User;
import com.qxgmat.service.UsersService;
import org.apache.commons.lang.time.FastDateFormat;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Objects;

/**
 * Created by GaoJie on 2017/11/3.
 */
public class TokenRealm extends AuthorizingRealm {
    private static final FastDateFormat dateFormat = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");
    private static final Logger logger = LoggerFactory.getLogger(TokenRealm.class);

    @Autowired
    private UsersService usersService;

    public TokenRealm() {
        super();
        setAuthenticationTokenClass(AuthenticationToken.class);
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String className = TokenRealm.class.getName();
        boolean selected = false;
        for(String realmNames: principalCollection.getRealmNames()){
            if(realmNames.contains(className)) selected = true;
        }
        if(!selected) return null;
        ArrayList<String> roleAuthorization = new ArrayList<String>();
        SimpleAuthorizationInfo sa = new SimpleAuthorizationInfo();
        roleAuthorization.add("user");
        sa.addRoles(roleAuthorization);
        return sa;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        AuthenticationToken token = (AuthenticationToken) authenticationToken;
        String username = (String)token.getCredentials();
        logger.info("Login token: "+username);

        User user = usersService.getUserByToken(username);
        if (user == null || user.getId() <= 0) {
            throw new UnknownAccountException("用户不存在！");
        }
        return new SimpleAuthenticationInfo(user, username, getName());
    }
    protected void assertCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) throws AuthenticationException {
    }
}
