/**
 * <p>Copyright:Copyright(c) 2016</p>
 * <p>Company:上海中信信息发展股份有限公司</p>
 * <p>类更新历史信息</p>
 * @author 张二伟
 * @date 2016-09-19 14:58
 * @todo
 */

package com.cesgroup.cesmonitor.web;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.shiro.SecurityUtils;
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.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
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.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.cesgroup.cesmonitor.common.Rsa;
import com.cesgroup.cesmonitor.service.IdentityService;
import com.cesgroup.cesmonitor.service.LoginUser;

/**
 * 权限数据源服务
 *
 * @author 张二伟
 *
 */
public class ShiroRealm extends AuthorizingRealm {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    protected IdentityService identityService;

    public static String data = "passKey";

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(final PrincipalCollection principals) {
        if (!SecurityUtils.getSubject().isAuthenticated()) {
            return null;
        }
        String username = (String) super.getAvailablePrincipal(principals);
        LoginUser user = identityService.getLoginUser(username);
        if (user == null) {
            return null;
        }
        SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
        if (user.isAdmin()) {
            simpleAuthorInfo.addRole("admin");
            // 添加权限
            simpleAuthorInfo.addStringPermission("admin:manage");
            logger.info("已为用户[{}]赋予了[admin]角色", username);

        } else {
            simpleAuthorInfo.addRole("project");
            logger.info("已为用户[{}]赋予了[project]角色", username);
        }
        return simpleAuthorInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken authcToken)
        throws AuthenticationException {
        try {
            UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
            String username = token.getUsername();
            String password = new String(token.getPassword());

            String privateKey = identityService.getKey();

            //解密
            String date = Rsa.decrypt(privateKey);
            int i = 0;
            if ("0".equals(date)) {
                i = 2;
            } else {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                Date endDate = sdf.parse(date);

                Date day = new Date();

                i = endDate.compareTo(day);

            }

            //System.out.println("是否过期" + i);
            if (i > 0) {
                logger.info("ok");
            } else {
                throw new UnknownAccountException("产品已过试用期");
            }

            LoginUser user = identityService.login(username, password);
            logger.info("用户{}已登录", username);

            SimpleAuthenticationInfo authcInfo = new SimpleAuthenticationInfo(username, password, this.getName());
            return authcInfo;
        } catch (Throwable e) {
            logger.error("登录失败", e);
            if (e.getMessage() == null) {
                throw new UnknownAccountException("用户名或密码不正确", e);
            } else {
                throw new UnknownAccountException(e.getMessage(), e);
            }

        }
    }

    /**
     * 将一些数据放到ShiroSession中,以便于其它地方使用
     *
     * @see 比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到
     */
    private void setSession(final Object key, final Object value) {
        Subject currentUser = SecurityUtils.getSubject();
        if (null != currentUser) {
            Session session = currentUser.getSession();
            logger.info("Session默认超时时间为[" + session.getTimeout() + "]毫秒");
            //if (null != session) {
            session.setAttribute(key, value);
            //}
        }
    }

}
