package com.aida.seller.common.context; import com.aida.seller.common.exception.UnauthorizedException; import com.aida.seller.model.vo.AuthPrincipalVo; public class UserContext { private static final ThreadLocal userHolder = new ThreadLocal<>(); private static final ThreadLocal optionalAuth = ThreadLocal.withInitial(() -> false); public static void setUserHolder(AuthPrincipalVo authPrincipalVo) { userHolder.set(authPrincipalVo); } public static void setOptionalAuth(boolean value) { optionalAuth.set(value); } public static AuthPrincipalVo getUserHolder() { AuthPrincipalVo holder = userHolder.get(); if (holder == null) { if (optionalAuth.get()) { return null; } throw new UnauthorizedException("Gateway token verification failed"); } if (!"AIDA".equals(holder.getSource())) { throw new UnauthorizedException("Gateway token verification failed"); } return holder; } public static void delete() { userHolder.remove(); optionalAuth.remove(); } public static Long getUserId() { return getUserHolder() == null ? null : getUserHolder().getId(); } //买家端请求需要调用此方法获取买家id public static Long getBuyerId() { AuthPrincipalVo holder = userHolder.get(); if (holder == null) { if (optionalAuth.get()) { return null; } throw new UnauthorizedException("Gateway token verification failed"); } if (!"BUYER".equals(holder.getSource())) { throw new UnauthorizedException("Gateway token verification failed"); } return holder.getId(); } public static Long getBuyerIdSafely() { AuthPrincipalVo holder = userHolder.get(); if (holder == null) { return null; } if (!"BUYER".equals(holder.getSource())) { return null; } return holder.getId(); } }