package vip.xiaonuo.exam.context;


import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import vip.xiaonuo.auth.core.pojo.SaBaseLoginUser;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;

/**
 * @version 3.3.0
 * @description: The enum System code.
 * Copyright (C), 2020-2024, 武汉思维跳跃科技有限公司
 * @date 2021/5/25 10:45
 */
@Component
public class WebContext {
    private static final String USER_ATTRIBUTES = "USER_ATTRIBUTES";




    /**
     * Sets current user.
     *
     * @param user the user
     */
    public void setCurrentUser(SaBaseLoginUser user) {
        RequestContextHolder.currentRequestAttributes().setAttribute(USER_ATTRIBUTES, user, RequestAttributes.SCOPE_REQUEST);
    }

    /**
     * Gets current user.
     *
     * @return the current user
     */
    public SaBaseLoginUser getCurrentUser() {
        SaBaseLoginUser saBaseLoginUser = (SaBaseLoginUser) RequestContextHolder.currentRequestAttributes().getAttribute(USER_ATTRIBUTES, RequestAttributes.SCOPE_REQUEST);
        if (null != saBaseLoginUser) {
            return saBaseLoginUser;
        } else {
            saBaseLoginUser=StpLoginUserUtil.getLoginUser();
            if (null != saBaseLoginUser) {
                setCurrentUser(saBaseLoginUser);
            }
            return saBaseLoginUser;
        }
    }
}
