package com.saye.hospitalgd.config;

import com.saye.hospitalgd.commons.date.DateDUtil;
import com.saye.hospitalgd.commons.string.StringDUtil;
import com.saye.hospitalgd.model.Users;
import com.saye.hospitalgd.service.system.UsersService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class MyShiroRealm extends AuthorizingRealm {

	@Autowired
	private UsersService usersService;

    /*主要是用来进行身份认证的，也就是说验证用户输入的账号和密码是否正确。*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        //获取用户的输入的账号.
        UsernamePasswordToken up = (UsernamePasswordToken)token;
        String username = String.valueOf(up.getUsername());
        String password = String.valueOf(up.getPassword());
        List<Users> list = usersService.searchByName(username);       
        if(list.isEmpty()){
            return null;
        }
        Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();
		
        Users user = list.get(0);
        //判断账户是否锁定
        String lockTime = user.getLockTime();
        String currentTime = DateDUtil.getTheCurrentTime();
        if(lockTime.compareTo(currentTime) == 1) {
        	throw new ExcessiveAttemptsException();
        }
        //连续输入错误超过6次，锁定10分钟
        String truePassword = user.getPassword();
        String encryptPassword = new Md5Hash(password,"hospitalgd",2).toString();
        if(!truePassword.equals(encryptPassword)) {
        	String num = StringDUtil.changeNullToEmpty(session.getAttribute(username));
			int failNum = Integer.valueOf(num.equals("")?"0":num);
			session.setAttribute(username, ++failNum);	
			if(failNum>6) { 
				lockTime = DateDUtil.getPlusMinutes("yyyy-MM-dd HH:mm:ss", currentTime, 10);
				this.usersService.modifyLockTime(username, lockTime);
				throw new ExcessiveAttemptsException();
			}
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
        		user, 
        		truePassword, 
                ByteSource.Util.bytes("hospitalgd"),
                getName()  //realm name
        );
        return authenticationInfo;
    }
	public static void main(String[] args) {
		String result = new Md5Hash("1234Saye","hospitalgd",2).toString();
		System.out.println(result);
		System.out.println(result.length());
	}
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// 配置权限
		return null;
	}

}