package net.siufung.bzgzpt.web.security;

import java.util.Collection;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpSession;

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.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.jbinfo.platform.core.framework.Global;
import cn.jbinfo.platform.core.framework.security.Encodes;
import cn.jbinfo.platform.core.framework.security.MyShiro;
import cn.jbinfo.platform.core.framework.security.Principal;
import cn.jbinfo.platform.core.framework.security.UsernamePasswordToken;
import cn.jbinfo.platform.core.framework.servlet.Servlets;
import cn.jbinfo.platform.core.framework.servlet.ValidateCode;
import cn.jbinfo.platform.core.utils.StringUtils;
import net.siufung.bzgzpt.persistence.uap.domain.Log;
import net.siufung.bzgzpt.persistence.uap.domain.Menu;
import net.siufung.bzgzpt.persistence.uap.domain.Role;
import net.siufung.bzgzpt.persistence.uap.domain.User;

/**
 * 系统安全认证实现类
 * @author siufung.chen
 * @version 2015-7-5
 */
@Component("systemAuthorizingRealm")
public class SystemAuthorizingRealm extends AuthorizingRealm {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private SystemManager systemManager;
	
	/**
	 * 认证回调函数, 登录时调用
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		int activeSessionSize =  systemManager.getActiveSessions(false).size();
		if (logger.isDebugEnabled()){
			logger.debug("login submit, active session size: {}, username: {}", activeSessionSize, token.getUsername());
		}	
		/*校验登录验证码*/
		HttpSession session=Servlets.getRequest().getSession();
		String code = (String)session.getAttribute(ValidateCode.VALIDATE_CODE);
		if (token.getCaptcha() == null || !token.getCaptcha().toUpperCase().equals(code)){
			throw new AuthenticationException("msg:验证码错误, 请重试.");
		}
		/*校验用户名密码*/
		User user = systemManager.getUserByLoginName(token.getUsername());
		if (user != null) {
			if (Global.NO.equals(user.getLoginFlag())){
				throw new AuthenticationException("msg:该帐号已禁止登录.");
			}
			byte[] salt = Encodes.decodeHex(user.getPassword().substring(0,16));
			return new SimpleAuthenticationInfo(new Principal(user.getId(),user.getLoginName(),user.getName(),token.isMobileLogin()), 
					user.getPassword().substring(16), ByteSource.Util.bytes(salt), getName());
		} else {
			return null;
		}
	}

	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		Principal principal = (Principal) getAvailablePrincipal(principals);
		/*获取当前已登录的用户*/
		if (!Global.TRUE.equals(Global.getConfig("user.multiAccountLogin"))){
			Collection<Session> sessions = systemManager.getActiveSessions(true, principal, MyShiro.getSession());
			if (sessions.size() > 0){
				// 如果是登录进来的，则踢出已在线用户
				if (MyShiro.getSubject().isAuthenticated()){
					for (Session session : sessions){
						systemManager.delete(session);
					}
				}
				/*记住我进来的，并且当前用户已登录，则退出当前用户提示信息。*/
				else{
					MyShiro.getSubject().logout();
					throw new AuthenticationException("msg:账号已在其它地方登录，请重新登录。");
				}
			}
		}
		User user = systemManager.getUserByLoginName(principal.getLoginName());
		if (user != null) {
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			List<Menu> list = systemManager.findAllList();
			for (Menu menu : list){
				if (StringUtils.isNotBlank(menu.getPermission())){
					for (String permission : StringUtils.split(menu.getPermission(),",")){
						info.addStringPermission(permission);
					}
				}
			}
			info.addStringPermission("admin");
			for (Role role : user.getRoleList()){
				info.addRole(role.getEnname());
			}
			systemManager.updateUserLoginInfo(user);
			Log log=new Log();
			log.setTitle(user.getLoginName()+"登录系统");
			//logService.insert(log);
			return info;
		} else {
			return null;
		}
	}
	
	@Override
	protected void checkPermission(Permission permission, AuthorizationInfo info) {
		authorizationValidate(permission);
		super.checkPermission(permission, info);
	}
	
	@Override
	protected boolean[] isPermitted(List<Permission> permissions, AuthorizationInfo info) {
		if (permissions != null && !permissions.isEmpty()) {
            for (Permission permission : permissions) {
        		authorizationValidate(permission);
            }
        }
		return super.isPermitted(permissions, info);
	}
	
	@Override
	public boolean isPermitted(PrincipalCollection principals, Permission permission) {
		authorizationValidate(permission);
		return super.isPermitted(principals, permission);
	}
	
	@Override
	protected boolean isPermittedAll(Collection<Permission> permissions, AuthorizationInfo info) {
		if (permissions != null && !permissions.isEmpty()) {
            for (Permission permission : permissions) {
            	authorizationValidate(permission);
            }
        }
		return super.isPermittedAll(permissions, info);
	}
	
	private void authorizationValidate(Permission permission){
		// 模块授权预留接口
	}
	

	@PostConstruct
	public void initCredentialsMatcher() {
		HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(MyShiro.HASH_ALGORITHM);
		matcher.setHashIterations(MyShiro.HASH_INTERATIONS);
		setCredentialsMatcher(matcher);
	}
	
	
	
}
