use of net.robinfriedli.aiode.concurrent.ThreadContext in project aiode by robinfriedli.
the class RequestInterceptorHandler method preHandle.
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
ThreadContext threadContext = ThreadContext.Current.get();
threadContext.install(new RequestContext(request));
try {
Cookie[] cookies = request.getCookies();
String sessionId = null;
if (cookies != null) {
sessionId = Arrays.stream(cookies).filter(c -> c.getName().equals("botify_session_id")).map(Cookie::getValue).findAny().orElse(null);
}
ClientSession clientSession = null;
ExecutionContext executionContext = null;
if (sessionId != null) {
UUID uuid = UUID.fromString(sessionId);
String remoteAddr = request.getRemoteAddr();
Optional<ClientSession> existingClientSession = hibernateComponent.invokeWithSession(session -> queryBuilderFactory.find(ClientSession.class).where((cb, root) -> cb.and(cb.equal(root.get("sessionId"), uuid), cb.equal(root.get("ipAddress"), remoteAddr))).build(session).uniqueResultOptional());
if (existingClientSession.isPresent()) {
clientSession = existingClientSession.get();
executionContext = setupExecutionContext(clientSession);
if (executionContext == null) {
response.sendError(403, "Could not connect to guild or user. Either the bot is having connection issues or the bot is longer part of the connected guild or the connected member is no longer part of this guild.");
threadContext.clear();
return false;
}
ExecutionContext.Current.set(executionContext);
}
}
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
AuthenticationRequired methodAnnotation = handlerMethod.getMethodAnnotation(AuthenticationRequired.class);
if (methodAnnotation != null) {
if (clientSession == null) {
response.sendError(403, "This endpoint requires the client to be connected to an active Session");
threadContext.clear();
return false;
}
String[] requiredPermissions = methodAnnotation.requiredPermissions();
if (requiredPermissions.length > 0) {
Member member = executionContext.getMember();
boolean unauthorized = Arrays.stream(requiredPermissions).noneMatch(perm -> securityManager.askPermission(perm, member));
if (unauthorized) {
response.sendError(403, String.format("Member '%s' does not have any of the required permissions: %s", member.getEffectiveName(), String.join(", ", requiredPermissions)));
threadContext.clear();
return false;
}
}
}
}
} catch (Exception e) {
response.sendError(500, "Internal server error");
threadContext.clear();
throw e;
}
return true;
}
Aggregations