Files
aida-seller/src/main/java/com/aida/seller/common/context/UserContext.java

67 lines
2.0 KiB
Java
Raw Normal View History

2026-04-21 10:25:39 +08:00
package com.aida.seller.common.context;
import com.aida.seller.common.exception.UnauthorizedException;
2026-04-21 10:25:39 +08:00
import com.aida.seller.model.vo.AuthPrincipalVo;
public class UserContext {
private static final ThreadLocal<AuthPrincipalVo> userHolder = new ThreadLocal<>();
private static final ThreadLocal<Boolean> optionalAuth = ThreadLocal.withInitial(() -> false);
public static void setUserHolder(AuthPrincipalVo authPrincipalVo) {
userHolder.set(authPrincipalVo);
}
public static void setOptionalAuth(boolean value) {
optionalAuth.set(value);
}
2026-04-21 10:25:39 +08:00
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;
2026-04-21 10:25:39 +08:00
}
public static void delete() {
userHolder.remove();
optionalAuth.remove();
2026-04-21 10:25:39 +08:00
}
public static Long getUserId() {
return getUserHolder() == null ? null : getUserHolder().getId();
2026-04-21 10:25:39 +08:00
}
//买家端请求需要调用此方法获取买家id
public static Long getBuyerId() {
2026-04-21 10:25:39 +08:00
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();
2026-04-21 10:25:39 +08:00
}
public static Long getBuyerIdSafely() {
AuthPrincipalVo holder = userHolder.get();
if (holder == null) {
return null;
}
if (!"BUYER".equals(holder.getSource())) {
return null;
}
return holder.getId();
}
2026-04-21 10:25:39 +08:00
}