package com.iformall.utils;

import com.iformall.common.ErrorCode;
import com.iformall.domain.po.MallUserInfo;
import com.iformall.exception.MallinkException;
import com.iformall.shiro.UserSession;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

/**
 * Shiro工具类
 *
 * @author stormeye.wu
 * @email wugq@mippoint.com
 * @date 2016年11月12日 上午9:49:19
 */
public class ShiroUtils {

    public static Session getSession() {
        return SecurityUtils.getSubject().getSession();
    }

    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    public static MallUserInfo getUserInfo() {
        return (MallUserInfo) SecurityUtils.getSubject().getSession().getAttribute(UserSession.userInfo);
    }

    public static Long getUserId() {
        return getUserInfo().getId();
    }

    public static void setSessionAttribute(Object key, Object value) {
        getSession().setAttribute(key, value);
    }

    public static Object getSessionAttribute(Object key) {
        return getSession().getAttribute(key);
    }

    public static boolean isLogin() {
        return SecurityUtils.getSubject().getPrincipal() != null;
    }

    public static void logout() {
        SecurityUtils.getSubject().logout();
    }

    public static String getKaptcha(String key) {
        Object kaptcha = getSessionAttribute(key);
        if (kaptcha == null) {
            throw new MallinkException(ErrorCode.KAPCHA_NOT_VALID);
        }
        getSession().removeAttribute(key);
        return kaptcha.toString();
    }

}
