package com.apobates.forum.thrones.admin.controller.helper;

import com.apobates.forum.member.entity.MemberRoleEnum;
import com.apobates.forum.member.storage.OnlineMemberStorage;
import com.apobates.forum.member.storage.core.MemberSessionBean;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 设置模板中访问会员信息的标识
 * 
 * @author xiaofanku
 * @since 20200604
 */
public class AdminIdentityInterceptor extends HandlerInterceptorAdapter{
    @Autowired
    private OnlineMemberStorage onlineMemberStorage;
    @Value("${site.online.member.symbol}")
    private String MSB_KEY;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        // Cookie
        MemberSessionBean mbean = onlineMemberStorage.getInstance(request, "AdminIdentityInterceptor").orElse(null);
        if (null != mbean && mbean.isOnline() && MemberRoleEnum.ADMIN == mbean.getRole()) {
            if (null == request.getAttribute(MSB_KEY)) {
                request.setAttribute(MSB_KEY, mbean);
            }
            return true;
        }
        response.sendRedirect(request.getContextPath() + "/");
        return false;
    }
}