Files
qchat/src/main/java/de/w665/testing/config/UsernamePrincipalHandshakeHandler.java
Maximilian Walz adb8ef9c83 Init
2025-09-16 23:05:31 +02:00

35 lines
1.3 KiB
Java

package de.w665.testing.config;
import de.w665.testing.service.TokenService;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;
import java.security.Principal;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
public class UsernamePrincipalHandshakeHandler extends DefaultHandshakeHandler {
private final TokenService tokenService;
public UsernamePrincipalHandshakeHandler(TokenService tokenService) {
this.tokenService = tokenService;
}
@Override
protected Principal determineUser(ServerHttpRequest request,
WebSocketHandler wsHandler,
Map<String, Object> attributes) {
Object tokenObj = attributes.get("token");
String token = tokenObj != null ? tokenObj.toString() : null;
if (token == null) {
// Anonymous session (reject by generating random, effectively not mapped to any user)
return () -> "anon-" + UUID.randomUUID();
}
Optional<String> user = tokenService.resolveUsername(token);
return user.<Principal>map(name -> () -> name)
.orElseGet(() -> (()-> "anon-" + UUID.randomUUID()));
}
}