package cn.com.liandisys.ycjt.ggcx.common.security.shiro;

import java.io.Serializable;
import java.util.List;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
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 cn.com.liandisys.ycjt.ggcx.admin.model.Role;
import cn.com.liandisys.ycjt.ggcx.admin.model.User;
import cn.com.liandisys.ycjt.ggcx.admin.service.UserService;
import cn.com.liandisys.ycjt.ggcx.common.constant.CommonConstant;
import cn.com.liandisys.ycjt.ggcx.common.security.shiro.session.SessionDAO;
import cn.com.liandisys.ycjt.ggcx.common.util.UserUtils;

/**
 * 系统安全认证实现类
 * @author jiangchao
 */
public class ShiroDbRealm extends AuthorizingRealm {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private SessionDAO sessionDAO;
	@Autowired
	private UserService userService;
	
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		
		int activeSessionSize = sessionDAO.getActiveSessions(false).size();
		if (logger.isDebugEnabled()){
			logger.debug("login submit, active session size: {}, username: {}", activeSessionSize, token.getUsername());
		}
		// 校验用户名密码
		User user = userService.findByLoginName(token.getUsername());
		if (user != null) {
			// 系统管理员有最高权限
			if(user.isAdmin()){
				return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
			}else{
				// CMS后台管理员有进入系统的权限
				boolean isCmsAdmin = false;
				List<Role> roles = user.getRoles();
				for(Role role : roles){
					if(CommonConstant.CMS_ADMIN_CODE.equals(role.getCode())){
						isCmsAdmin = true;
						break;
					}
				}
				if(isCmsAdmin){
					return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
				}else{
					return null;
				}
			}
		} else {
			return null;
		}
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO 网站CMS权限单一，暂不设置权限，后期后台功能扩展后可在用户管理系统中配置并在此处进行赋权查询
		return null;
	}
	
	/**
	 * 授权用户信息
	 */
	public static class Principal implements Serializable {

		private static final long serialVersionUID = 1L;
		private String id; // 编号
		private String loginName; // 登录名
		private String name; // 姓名
		public Principal(User user) {
			this.id = user.getId();
			this.loginName = user.getLoginName();
			this.name = user.getName();
		}

		public String getId() {
			return id;
		}

		public String getLoginName() {
			return loginName;
		}

		public String getName() {
			return name;
		}

		/**
		 * 获取SESSIONID
		 */
		public String getSessionid() {
			try{
				return (String) UserUtils.getSession().getId();
			}catch (Exception e) {
				return "";
			}
		}
		
		@Override
		public String toString() {
			return id;
		}

	}

}
