package com.seer.teach.admin.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;

@Configuration
public class SaTokenConfigure {

    /**
     * 注册 [Sa-Token全局过滤器]，设置顺序在CORS过滤器之后
     */
    //@Bean
    @Order(Ordered.HIGHEST_PRECEDENCE + 1)
    public SaServletFilter getSaServletFilter() {
        return new SaServletFilter()
                .addInclude("/**")
                .addExclude("/favicon.ico", "/user/login", "/swagger-ui/**", "/v3/api-docs/**", "/swagger-resources/**")
                .setAuth(obj -> {
                    if ("OPTIONS".equals(SaHolder.getRequest().getMethod())) {
                        return;
                    }
                    SaRouter.match("/**", r -> {
                        // 排除多个不需要认证的接口
                        SaRouter.match("/user/login");
                        SaRouter.match("/user/register");
                        SaRouter.match("/swagger-ui/**");
                        SaRouter.match("/v3/api-docs/**");
                        SaRouter.match("/swagger-resources/**");
                        // 其他接口都需要登录
                        StpUtil.checkLogin();
                    });
                })
                .setError(e -> {
                    return SaResult.code(HttpStatus.UNAUTHORIZED.value());
                })
                .setBeforeAuth(r -> {
                    SaHolder.getResponse()
                            // 是否启用浏览器默认XSS防护： 0=禁用 | 1=启用 | 1; mode=block 启用, 并在检查到XSS攻击时，停止渲染页面
                            .setHeader("X-XSS-Protection", "1; mode=block")
                            // 禁用浏览器内容嗅探
                            .setHeader("X-Content-Type-Options", "nosniff");
                });
    }
}