2026-04-21 10:25:39 +08:00
|
|
|
package com.aida.seller.common.context;
|
|
|
|
|
|
2026-05-13 09:40:32 +08:00
|
|
|
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<>();
|
2026-05-13 09:40:32 +08:00
|
|
|
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() {
|
2026-05-13 09:40:32 +08:00
|
|
|
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();
|
2026-05-13 09:40:32 +08:00
|
|
|
optionalAuth.remove();
|
2026-04-21 10:25:39 +08:00
|
|
|
}
|
|
|
|
|
|
2026-05-13 09:40:32 +08:00
|
|
|
public static Long getUserId() {
|
|
|
|
|
return getUserHolder() == null ? null : getUserHolder().getId();
|
2026-04-21 10:25:39 +08:00
|
|
|
}
|
|
|
|
|
|
2026-05-13 09:40:32 +08:00
|
|
|
//买家端请求需要调用此方法获取买家id
|
|
|
|
|
public static Long getBuyerId() {
|
2026-04-21 10:25:39 +08:00
|
|
|
AuthPrincipalVo holder = userHolder.get();
|
2026-05-13 09:40:32 +08:00
|
|
|
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
|
|
|
}
|
2026-06-01 15:53:02 +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
|
|
|
}
|