package com.dcit.authority.shiro.realm;

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.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.dcit.authority.shiro.domain.AuthUserInfo;
import com.dcit.authority.shiro.provider.ShiroAuthProvider;
import com.dcit.authority.shiro.token.PasswordToken;
import com.dcit.common.utils.StrEncryptUtil;


/**
* <p>Title: PasswordRealm</p>
* <p>Description: 登录认证realm</p>
* <p>Company: SJZ DC-IT co. LTD</p> 
* @author ZZZ
* @date 2018年9月6日 下午5:36:00
*/
public class PasswordRealm extends AuthorizingRealm {

	private ShiroAuthProvider shiroAuthProvider;

	/**
     * description 此Realm只支持PasswordToken
     *
     * @return java.lang.Class<?>
     */
    @Override
    public Class<?> getAuthenticationTokenClass() {
        return PasswordToken.class;
    }


    /**
     * description 这里只需要认证登录，成功之后派发 json web token 授权在那里进行
     *
     * @param principalCollection 1
     * @return org.apache.shiro.authz.AuthorizationInfo
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        if (!(authenticationToken instanceof PasswordToken)) {
            return null;
        }

        if(null==authenticationToken.getPrincipal()||null==authenticationToken.getCredentials()){
            throw new UnknownAccountException();
        }
        String account = (String)authenticationToken.getPrincipal();
        AuthUserInfo authUserInfo = shiroAuthProvider.loadAuthUserInfoByAccount(account);
        if (null != authUserInfo) {
            // 用盐对密码进行MD5加密
            ((PasswordToken) authenticationToken).setPassword(StrEncryptUtil.md5(((PasswordToken) authenticationToken).getPassword()+authUserInfo.getSalt()));
            return new SimpleAuthenticationInfo(account,authUserInfo.getPassword(),getName());
        } else {
            return new SimpleAuthenticationInfo(account,"",getName());
        }

    }

    public void setShiroAuthProvider(ShiroAuthProvider shiroAuthProvider) {
        this.shiroAuthProvider = shiroAuthProvider;
    }

}
