Init
This commit is contained in:
40
build.gradle
Normal file
40
build.gradle
Normal file
@@ -0,0 +1,40 @@
|
||||
plugins {
|
||||
id 'java'
|
||||
id 'org.springframework.boot' version '3.5.3'
|
||||
id 'io.spring.dependency-management' version '1.1.7'
|
||||
}
|
||||
|
||||
group = 'de.w665'
|
||||
version = '0.0.1-SNAPSHOT'
|
||||
|
||||
java {
|
||||
toolchain {
|
||||
languageVersion = JavaLanguageVersion.of(21)
|
||||
}
|
||||
}
|
||||
|
||||
configurations {
|
||||
compileOnly {
|
||||
extendsFrom annotationProcessor
|
||||
}
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation 'org.springframework.boot:spring-boot-starter-actuator'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-web'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-websocket'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
|
||||
implementation 'com.h2database:h2'
|
||||
compileOnly 'org.projectlombok:lombok'
|
||||
annotationProcessor 'org.projectlombok:lombok'
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
|
||||
}
|
||||
|
||||
tasks.named('test') {
|
||||
useJUnitPlatform()
|
||||
}
|
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
7
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
7
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.2-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
251
gradlew
vendored
Executable file
251
gradlew
vendored
Executable file
@@ -0,0 +1,251 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH="\\\"\\\""
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
94
gradlew.bat
vendored
Normal file
94
gradlew.bat
vendored
Normal file
@@ -0,0 +1,94 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
@rem SPDX-License-Identifier: Apache-2.0
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
1
settings.gradle
Normal file
1
settings.gradle
Normal file
@@ -0,0 +1 @@
|
||||
rootProject.name = 'testing'
|
13
src/main/java/de/w665/testing/TestingApplication.java
Normal file
13
src/main/java/de/w665/testing/TestingApplication.java
Normal file
@@ -0,0 +1,13 @@
|
||||
package de.w665.testing;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class TestingApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(TestingApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,37 @@
|
||||
package de.w665.testing.config;
|
||||
|
||||
import org.springframework.http.server.ServerHttpRequest;
|
||||
import org.springframework.http.server.ServerHttpResponse;
|
||||
import org.springframework.web.socket.WebSocketHandler;
|
||||
import org.springframework.web.socket.server.HandshakeInterceptor;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class UsernameHandshakeInterceptor implements HandshakeInterceptor {
|
||||
@Override
|
||||
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) {
|
||||
URI uri = request.getURI();
|
||||
String query = uri.getQuery();
|
||||
if (query != null) {
|
||||
for (String pair : query.split("&")) {
|
||||
String[] kv = pair.split("=", 2);
|
||||
if (kv.length == 2 && kv[0].equals("token")) {
|
||||
attributes.put("token", kv[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Also check headers (not used by SockJS handshake, but harmless)
|
||||
List<String> header = request.getHeaders().get("X-Auth-Token");
|
||||
if (header != null && !header.isEmpty()) {
|
||||
attributes.put("token", header.getFirst());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
|
||||
// no-op
|
||||
}
|
||||
}
|
@@ -0,0 +1,34 @@
|
||||
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()));
|
||||
}
|
||||
}
|
34
src/main/java/de/w665/testing/config/WebSocketConfig.java
Normal file
34
src/main/java/de/w665/testing/config/WebSocketConfig.java
Normal file
@@ -0,0 +1,34 @@
|
||||
package de.w665.testing.config;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
|
||||
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
|
||||
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
|
||||
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
|
||||
import de.w665.testing.service.TokenService;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSocketMessageBroker
|
||||
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
|
||||
private final TokenService tokenService;
|
||||
|
||||
public WebSocketConfig(TokenService tokenService) {
|
||||
this.tokenService = tokenService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configureMessageBroker(MessageBrokerRegistry config) {
|
||||
config.enableSimpleBroker("/topic", "/queue");
|
||||
config.setApplicationDestinationPrefixes("/app");
|
||||
config.setUserDestinationPrefix("/user");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerStompEndpoints(StompEndpointRegistry registry) {
|
||||
registry.addEndpoint("/ws")
|
||||
.setAllowedOriginPatterns("*")
|
||||
.addInterceptors(new UsernameHandshakeInterceptor())
|
||||
.setHandshakeHandler(new UsernamePrincipalHandshakeHandler(tokenService))
|
||||
.withSockJS();
|
||||
}
|
||||
}
|
40
src/main/java/de/w665/testing/controller/AuthController.java
Normal file
40
src/main/java/de/w665/testing/controller/AuthController.java
Normal file
@@ -0,0 +1,40 @@
|
||||
package de.w665.testing.controller;
|
||||
|
||||
import de.w665.testing.dto.SignupRequest;
|
||||
import de.w665.testing.dto.SignupResponse;
|
||||
import de.w665.testing.service.PresenceService;
|
||||
import de.w665.testing.service.TokenService;
|
||||
import de.w665.testing.service.UserService;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api")
|
||||
public class AuthController {
|
||||
private final UserService userService;
|
||||
private final PresenceService presenceService;
|
||||
private final TokenService tokenService;
|
||||
|
||||
public AuthController(UserService userService, PresenceService presenceService, TokenService tokenService) {
|
||||
this.userService = userService;
|
||||
this.presenceService = presenceService;
|
||||
this.tokenService = tokenService;
|
||||
}
|
||||
|
||||
@PostMapping("/signup")
|
||||
public ResponseEntity<?> signup(@RequestBody SignupRequest request) {
|
||||
try {
|
||||
String token = userService.signup(request.getUsername());
|
||||
return ResponseEntity.ok(new SignupResponse(request.getUsername().trim().toLowerCase(), token));
|
||||
} catch (IllegalArgumentException ex) {
|
||||
return ResponseEntity.status(409).body(ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/online")
|
||||
public Set<String> online() {
|
||||
return presenceService.getOnlineUsers();
|
||||
}
|
||||
}
|
@@ -0,0 +1,29 @@
|
||||
package de.w665.testing.controller;
|
||||
|
||||
import de.w665.testing.dto.ChatMessage;
|
||||
import de.w665.testing.dto.SendMessageCommand;
|
||||
import org.springframework.messaging.handler.annotation.MessageMapping;
|
||||
import org.springframework.messaging.handler.annotation.Payload;
|
||||
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||
import org.springframework.stereotype.Controller;
|
||||
|
||||
import java.security.Principal;
|
||||
|
||||
@Controller
|
||||
public class WebSocketChatController {
|
||||
private final SimpMessagingTemplate messagingTemplate;
|
||||
|
||||
public WebSocketChatController(SimpMessagingTemplate messagingTemplate) {
|
||||
this.messagingTemplate = messagingTemplate;
|
||||
}
|
||||
|
||||
@MessageMapping("/chat/send")
|
||||
public void send(@Payload SendMessageCommand cmd, Principal principal) {
|
||||
if (principal == null || cmd.getRoomId() == null || cmd.getRoomId().isBlank() || cmd.getContent() == null || cmd.getContent().isBlank()) {
|
||||
return;
|
||||
}
|
||||
String sender = principal.getName();
|
||||
ChatMessage msg = ChatMessage.of(cmd.getRoomId(), sender, cmd.getContent());
|
||||
messagingTemplate.convertAndSend("/topic/room." + cmd.getRoomId(), msg);
|
||||
}
|
||||
}
|
@@ -0,0 +1,45 @@
|
||||
package de.w665.testing.controller;
|
||||
|
||||
import de.w665.testing.dto.AcceptInviteCommand;
|
||||
import de.w665.testing.dto.DeclineInviteCommand;
|
||||
import de.w665.testing.dto.InviteCommand;
|
||||
import de.w665.testing.service.InviteService;
|
||||
import org.springframework.messaging.handler.annotation.MessageMapping;
|
||||
import org.springframework.messaging.handler.annotation.Payload;
|
||||
import org.springframework.stereotype.Controller;
|
||||
|
||||
import java.security.Principal;
|
||||
|
||||
@Controller
|
||||
public class WebSocketInviteController {
|
||||
private final InviteService inviteService;
|
||||
|
||||
public WebSocketInviteController(InviteService inviteService) {
|
||||
this.inviteService = inviteService;
|
||||
}
|
||||
|
||||
@MessageMapping("/invite/send")
|
||||
public void sendInvite(@Payload InviteCommand cmd, Principal principal) {
|
||||
if (principal == null) return;
|
||||
String from = principal.getName();
|
||||
if (cmd.getTo() == null || cmd.getTo().isBlank()) return;
|
||||
if (from.equalsIgnoreCase(cmd.getTo())) return;
|
||||
inviteService.sendInvite(from, cmd.getTo().trim().toLowerCase());
|
||||
}
|
||||
|
||||
@MessageMapping("/invite/accept")
|
||||
public void acceptInvite(@Payload AcceptInviteCommand cmd, Principal principal) {
|
||||
if (principal == null) return;
|
||||
String recipient = principal.getName();
|
||||
if (cmd.getInviter() == null || cmd.getInviter().isBlank()) return;
|
||||
inviteService.acceptInvite(recipient, cmd.getInviter().trim().toLowerCase());
|
||||
}
|
||||
|
||||
@MessageMapping("/invite/decline")
|
||||
public void declineInvite(@Payload DeclineInviteCommand cmd, Principal principal) {
|
||||
if (principal == null) return;
|
||||
String recipient = principal.getName();
|
||||
if (cmd.getInviter() == null || cmd.getInviter().isBlank()) return;
|
||||
inviteService.declineInvite(recipient, cmd.getInviter().trim().toLowerCase());
|
||||
}
|
||||
}
|
13
src/main/java/de/w665/testing/dto/AcceptInviteCommand.java
Normal file
13
src/main/java/de/w665/testing/dto/AcceptInviteCommand.java
Normal file
@@ -0,0 +1,13 @@
|
||||
package de.w665.testing.dto;
|
||||
|
||||
public class AcceptInviteCommand {
|
||||
private String inviter;
|
||||
|
||||
public String getInviter() {
|
||||
return inviter;
|
||||
}
|
||||
|
||||
public void setInviter(String inviter) {
|
||||
this.inviter = inviter;
|
||||
}
|
||||
}
|
55
src/main/java/de/w665/testing/dto/ChatMessage.java
Normal file
55
src/main/java/de/w665/testing/dto/ChatMessage.java
Normal file
@@ -0,0 +1,55 @@
|
||||
package de.w665.testing.dto;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public class ChatMessage {
|
||||
private String roomId;
|
||||
private String sender;
|
||||
private String content;
|
||||
private long timestamp;
|
||||
|
||||
public ChatMessage() {}
|
||||
|
||||
public ChatMessage(String roomId, String sender, String content, long timestamp) {
|
||||
this.roomId = roomId;
|
||||
this.sender = sender;
|
||||
this.content = content;
|
||||
this.timestamp = timestamp;
|
||||
}
|
||||
|
||||
public static ChatMessage of(String roomId, String sender, String content) {
|
||||
return new ChatMessage(roomId, sender, content, Instant.now().toEpochMilli());
|
||||
}
|
||||
|
||||
public String getRoomId() {
|
||||
return roomId;
|
||||
}
|
||||
|
||||
public void setRoomId(String roomId) {
|
||||
this.roomId = roomId;
|
||||
}
|
||||
|
||||
public String getSender() {
|
||||
return sender;
|
||||
}
|
||||
|
||||
public void setSender(String sender) {
|
||||
this.sender = sender;
|
||||
}
|
||||
|
||||
public String getContent() {
|
||||
return content;
|
||||
}
|
||||
|
||||
public void setContent(String content) {
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
public long getTimestamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
public void setTimestamp(long timestamp) {
|
||||
this.timestamp = timestamp;
|
||||
}
|
||||
}
|
13
src/main/java/de/w665/testing/dto/DeclineInviteCommand.java
Normal file
13
src/main/java/de/w665/testing/dto/DeclineInviteCommand.java
Normal file
@@ -0,0 +1,13 @@
|
||||
package de.w665.testing.dto;
|
||||
|
||||
public class DeclineInviteCommand {
|
||||
private String inviter;
|
||||
|
||||
public String getInviter() {
|
||||
return inviter;
|
||||
}
|
||||
|
||||
public void setInviter(String inviter) {
|
||||
this.inviter = inviter;
|
||||
}
|
||||
}
|
13
src/main/java/de/w665/testing/dto/InviteCommand.java
Normal file
13
src/main/java/de/w665/testing/dto/InviteCommand.java
Normal file
@@ -0,0 +1,13 @@
|
||||
package de.w665.testing.dto;
|
||||
|
||||
public class InviteCommand {
|
||||
private String to;
|
||||
|
||||
public String getTo() {
|
||||
return to;
|
||||
}
|
||||
|
||||
public void setTo(String to) {
|
||||
this.to = to;
|
||||
}
|
||||
}
|
63
src/main/java/de/w665/testing/dto/InviteEvent.java
Normal file
63
src/main/java/de/w665/testing/dto/InviteEvent.java
Normal file
@@ -0,0 +1,63 @@
|
||||
package de.w665.testing.dto;
|
||||
|
||||
public class InviteEvent {
|
||||
public enum Type { INVITE, ACCEPT, DECLINE }
|
||||
|
||||
private Type type;
|
||||
private String from;
|
||||
private String to;
|
||||
private String roomId; // present when type == ACCEPT
|
||||
|
||||
public InviteEvent() {}
|
||||
|
||||
public InviteEvent(Type type, String from, String to, String roomId) {
|
||||
this.type = type;
|
||||
this.from = from;
|
||||
this.to = to;
|
||||
this.roomId = roomId;
|
||||
}
|
||||
|
||||
public static InviteEvent invite(String from, String to) {
|
||||
return new InviteEvent(Type.INVITE, from, to, null);
|
||||
}
|
||||
|
||||
public static InviteEvent accept(String from, String to, String roomId) {
|
||||
return new InviteEvent(Type.ACCEPT, from, to, roomId);
|
||||
}
|
||||
|
||||
public static InviteEvent decline(String from, String to) {
|
||||
return new InviteEvent(Type.DECLINE, from, to, null);
|
||||
}
|
||||
|
||||
public Type getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(Type type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public String getFrom() {
|
||||
return from;
|
||||
}
|
||||
|
||||
public void setFrom(String from) {
|
||||
this.from = from;
|
||||
}
|
||||
|
||||
public String getTo() {
|
||||
return to;
|
||||
}
|
||||
|
||||
public void setTo(String to) {
|
||||
this.to = to;
|
||||
}
|
||||
|
||||
public String getRoomId() {
|
||||
return roomId;
|
||||
}
|
||||
|
||||
public void setRoomId(String roomId) {
|
||||
this.roomId = roomId;
|
||||
}
|
||||
}
|
22
src/main/java/de/w665/testing/dto/SendMessageCommand.java
Normal file
22
src/main/java/de/w665/testing/dto/SendMessageCommand.java
Normal file
@@ -0,0 +1,22 @@
|
||||
package de.w665.testing.dto;
|
||||
|
||||
public class SendMessageCommand {
|
||||
private String roomId;
|
||||
private String content;
|
||||
|
||||
public String getRoomId() {
|
||||
return roomId;
|
||||
}
|
||||
|
||||
public void setRoomId(String roomId) {
|
||||
this.roomId = roomId;
|
||||
}
|
||||
|
||||
public String getContent() {
|
||||
return content;
|
||||
}
|
||||
|
||||
public void setContent(String content) {
|
||||
this.content = content;
|
||||
}
|
||||
}
|
13
src/main/java/de/w665/testing/dto/SignupRequest.java
Normal file
13
src/main/java/de/w665/testing/dto/SignupRequest.java
Normal file
@@ -0,0 +1,13 @@
|
||||
package de.w665.testing.dto;
|
||||
|
||||
public class SignupRequest {
|
||||
private String username;
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
}
|
29
src/main/java/de/w665/testing/dto/SignupResponse.java
Normal file
29
src/main/java/de/w665/testing/dto/SignupResponse.java
Normal file
@@ -0,0 +1,29 @@
|
||||
package de.w665.testing.dto;
|
||||
|
||||
public class SignupResponse {
|
||||
private String username;
|
||||
private String token;
|
||||
|
||||
public SignupResponse() {}
|
||||
|
||||
public SignupResponse(String username, String token) {
|
||||
this.username = username;
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getToken() {
|
||||
return token;
|
||||
}
|
||||
|
||||
public void setToken(String token) {
|
||||
this.token = token;
|
||||
}
|
||||
}
|
28
src/main/java/de/w665/testing/service/ChatRoomService.java
Normal file
28
src/main/java/de/w665/testing/service/ChatRoomService.java
Normal file
@@ -0,0 +1,28 @@
|
||||
package de.w665.testing.service;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Service
|
||||
public class ChatRoomService {
|
||||
// key: canonicalPair(userA,userB) -> roomId
|
||||
private final Map<String, String> pairToRoom = new ConcurrentHashMap<>();
|
||||
|
||||
public String getOrCreateRoom(String userA, String userB) {
|
||||
String key = canonicalPair(userA, userB);
|
||||
return pairToRoom.computeIfAbsent(key, k -> "room-" + Math.abs(k.hashCode()));
|
||||
}
|
||||
|
||||
public Optional<String> getRoomIfExists(String userA, String userB) {
|
||||
return Optional.ofNullable(pairToRoom.get(canonicalPair(userA, userB)));
|
||||
}
|
||||
|
||||
private String canonicalPair(String a, String b) {
|
||||
String u1 = a.toLowerCase();
|
||||
String u2 = b.toLowerCase();
|
||||
return (u1.compareTo(u2) <= 0) ? (u1 + "|" + u2) : (u2 + "|" + u1);
|
||||
}
|
||||
}
|
48
src/main/java/de/w665/testing/service/InviteService.java
Normal file
48
src/main/java/de/w665/testing/service/InviteService.java
Normal file
@@ -0,0 +1,48 @@
|
||||
package de.w665.testing.service;
|
||||
|
||||
import de.w665.testing.dto.InviteEvent;
|
||||
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Service
|
||||
public class InviteService {
|
||||
private final SimpMessagingTemplate messagingTemplate;
|
||||
private final ChatRoomService chatRoomService;
|
||||
|
||||
// recipient -> set of inviters
|
||||
private final Map<String, Set<String>> pending = new ConcurrentHashMap<>();
|
||||
|
||||
public InviteService(SimpMessagingTemplate messagingTemplate, ChatRoomService chatRoomService) {
|
||||
this.messagingTemplate = messagingTemplate;
|
||||
this.chatRoomService = chatRoomService;
|
||||
}
|
||||
|
||||
public void sendInvite(String from, String to) {
|
||||
pending.computeIfAbsent(to, k -> ConcurrentHashMap.newKeySet()).add(from);
|
||||
InviteEvent event = InviteEvent.invite(from, to);
|
||||
messagingTemplate.convertAndSendToUser(to, "/queue/invites", event);
|
||||
}
|
||||
|
||||
public void acceptInvite(String recipient, String inviter) {
|
||||
Set<String> inviters = pending.getOrDefault(recipient, ConcurrentHashMap.newKeySet());
|
||||
if (inviters.remove(inviter)) {
|
||||
String room = chatRoomService.getOrCreateRoom(inviter, recipient);
|
||||
InviteEvent acceptForInviter = InviteEvent.accept(recipient, inviter, room);
|
||||
InviteEvent acceptForRecipient = InviteEvent.accept(inviter, recipient, room);
|
||||
messagingTemplate.convertAndSendToUser(inviter, "/queue/invites", acceptForInviter);
|
||||
messagingTemplate.convertAndSendToUser(recipient, "/queue/invites", acceptForRecipient);
|
||||
}
|
||||
}
|
||||
|
||||
public void declineInvite(String recipient, String inviter) {
|
||||
Set<String> inviters = pending.getOrDefault(recipient, ConcurrentHashMap.newKeySet());
|
||||
if (inviters.remove(inviter)) {
|
||||
InviteEvent declineForInviter = InviteEvent.decline(recipient, inviter);
|
||||
messagingTemplate.convertAndSendToUser(inviter, "/queue/invites", declineForInviter);
|
||||
}
|
||||
}
|
||||
}
|
54
src/main/java/de/w665/testing/service/PresenceService.java
Normal file
54
src/main/java/de/w665/testing/service/PresenceService.java
Normal file
@@ -0,0 +1,54 @@
|
||||
package de.w665.testing.service;
|
||||
|
||||
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
public class PresenceService {
|
||||
private final SimpMessagingTemplate messagingTemplate;
|
||||
|
||||
// sessionId -> username
|
||||
private final Map<String, String> sessionToUser = new ConcurrentHashMap<>();
|
||||
// username -> session count
|
||||
private final Map<String, Integer> userSessionCounts = new ConcurrentHashMap<>();
|
||||
|
||||
public PresenceService(SimpMessagingTemplate messagingTemplate) {
|
||||
this.messagingTemplate = messagingTemplate;
|
||||
}
|
||||
|
||||
public void userConnected(String sessionId, String username) {
|
||||
sessionToUser.put(sessionId, username);
|
||||
userSessionCounts.merge(username, 1, Integer::sum);
|
||||
broadcastOnlineUsers();
|
||||
}
|
||||
|
||||
public void userDisconnected(String sessionId) {
|
||||
String username = sessionToUser.remove(sessionId);
|
||||
if (username != null) {
|
||||
userSessionCounts.computeIfPresent(username, (u, count) -> {
|
||||
int next = count - 1;
|
||||
return next <= 0 ? null : next;
|
||||
});
|
||||
broadcastOnlineUsers();
|
||||
}
|
||||
}
|
||||
|
||||
public Set<String> getOnlineUsers() {
|
||||
return Collections.unmodifiableSet(
|
||||
userSessionCounts.entrySet().stream()
|
||||
.filter(e -> e.getValue() != null && e.getValue() > 0)
|
||||
.map(Map.Entry::getKey)
|
||||
.collect(Collectors.toSet())
|
||||
);
|
||||
}
|
||||
|
||||
public void broadcastOnlineUsers() {
|
||||
messagingTemplate.convertAndSend("/topic/online-users", getOnlineUsers());
|
||||
}
|
||||
}
|
35
src/main/java/de/w665/testing/service/TokenService.java
Normal file
35
src/main/java/de/w665/testing/service/TokenService.java
Normal file
@@ -0,0 +1,35 @@
|
||||
package de.w665.testing.service;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Service
|
||||
public class TokenService {
|
||||
private final Map<String, String> tokenToUser = new ConcurrentHashMap<>();
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
|
||||
public String createTokenForUsername(String username) {
|
||||
String token = generateToken();
|
||||
tokenToUser.put(token, username);
|
||||
return token;
|
||||
}
|
||||
|
||||
public Optional<String> resolveUsername(String token) {
|
||||
return Optional.ofNullable(tokenToUser.get(token));
|
||||
}
|
||||
|
||||
public void invalidate(String token) {
|
||||
tokenToUser.remove(token);
|
||||
}
|
||||
|
||||
private String generateToken() {
|
||||
byte[] bytes = new byte[32];
|
||||
random.nextBytes(bytes);
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||
}
|
||||
}
|
41
src/main/java/de/w665/testing/service/UserService.java
Normal file
41
src/main/java/de/w665/testing/service/UserService.java
Normal file
@@ -0,0 +1,41 @@
|
||||
package de.w665.testing.service;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Service
|
||||
public class UserService {
|
||||
private final TokenService tokenService;
|
||||
private final Map<String, String> usernameToToken = new ConcurrentHashMap<>();
|
||||
|
||||
public UserService(TokenService tokenService) {
|
||||
this.tokenService = tokenService;
|
||||
}
|
||||
|
||||
public synchronized String signup(String username) {
|
||||
String normalized = normalize(username);
|
||||
if (usernameToToken.containsKey(normalized)) {
|
||||
throw new IllegalArgumentException("Username already taken");
|
||||
}
|
||||
String token = tokenService.createTokenForUsername(normalized);
|
||||
usernameToToken.put(normalized, token);
|
||||
return token;
|
||||
}
|
||||
|
||||
public Optional<String> getTokenFor(String username) {
|
||||
return Optional.ofNullable(usernameToToken.get(normalize(username)));
|
||||
}
|
||||
|
||||
public Set<String> getAllRegisteredUsers() {
|
||||
return Collections.unmodifiableSet(usernameToToken.keySet());
|
||||
}
|
||||
|
||||
private String normalize(String username) {
|
||||
return username.trim().toLowerCase();
|
||||
}
|
||||
}
|
@@ -0,0 +1,54 @@
|
||||
package de.w665.testing.ws;
|
||||
|
||||
import de.w665.testing.service.PresenceService;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.socket.messaging.SessionConnectEvent;
|
||||
import org.springframework.web.socket.messaging.SessionConnectedEvent;
|
||||
import org.springframework.web.socket.messaging.SessionDisconnectEvent;
|
||||
|
||||
import java.security.Principal;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Component
|
||||
public class WebSocketPresenceEventListener {
|
||||
private final PresenceService presenceService;
|
||||
private final Set<String> connectedSessions = ConcurrentHashMap.newKeySet();
|
||||
|
||||
public WebSocketPresenceEventListener(PresenceService presenceService) {
|
||||
this.presenceService = presenceService;
|
||||
}
|
||||
|
||||
@EventListener
|
||||
public void handleWebSocketConnectListener(SessionConnectEvent event) {
|
||||
StompHeaderAccessor sha = StompHeaderAccessor.wrap(event.getMessage());
|
||||
Principal p = sha.getUser();
|
||||
String sessionId = sha.getSessionId();
|
||||
if (p != null && sessionId != null && connectedSessions.add(sessionId)) {
|
||||
presenceService.userConnected(sessionId, p.getName());
|
||||
}
|
||||
}
|
||||
|
||||
@EventListener
|
||||
public void handleWebSocketConnectedListener(SessionConnectedEvent event) {
|
||||
StompHeaderAccessor sha = StompHeaderAccessor.wrap(event.getMessage());
|
||||
Principal p = sha.getUser();
|
||||
String sessionId = sha.getSessionId();
|
||||
if (p != null && sessionId != null && connectedSessions.add(sessionId)) {
|
||||
presenceService.userConnected(sessionId, p.getName());
|
||||
}
|
||||
}
|
||||
|
||||
@EventListener
|
||||
public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
|
||||
String sessionId = event.getSessionId();
|
||||
if (sessionId != null && connectedSessions.remove(sessionId)) {
|
||||
presenceService.userDisconnected(sessionId);
|
||||
} else {
|
||||
// Even if we didn't mark it as connected (edge cases), attempt to notify presence
|
||||
presenceService.userDisconnected(sessionId);
|
||||
}
|
||||
}
|
||||
}
|
17
src/main/resources/application.properties
Normal file
17
src/main/resources/application.properties
Normal file
@@ -0,0 +1,17 @@
|
||||
spring.application.name=testing
|
||||
|
||||
# H2 Database configuration
|
||||
spring.datasource.url=jdbc:h2:mem:testdb
|
||||
spring.datasource.driverClassName=org.h2.Driver
|
||||
spring.datasource.username=sa
|
||||
spring.datasource.password=password
|
||||
spring.h2.console.enabled=true
|
||||
spring.h2.console.path=/h2-console
|
||||
|
||||
# JPA configuration
|
||||
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
|
||||
spring.jpa.hibernate.ddl-auto=create-drop
|
||||
spring.jpa.show-sql=true
|
||||
|
||||
# Server configuration
|
||||
server.port=8080
|
286
src/main/resources/static/index.html
Normal file
286
src/main/resources/static/index.html
Normal file
@@ -0,0 +1,286 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Simple Chat</title>
|
||||
<style>
|
||||
body { font-family: system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif; margin: 0; background: #0f172a; color: #e2e8f0; }
|
||||
header { padding: 16px; background: #111827; display: flex; justify-content: space-between; align-items: center; }
|
||||
header h1 { margin: 0; font-size: 18px; }
|
||||
.container { display: grid; grid-template-columns: 300px 1fr; gap: 16px; padding: 16px; height: calc(100vh - 64px); box-sizing: border-box; }
|
||||
.panel { background: #1f2937; border-radius: 8px; padding: 12px; overflow: hidden; display: flex; flex-direction: column; }
|
||||
.panel h2 { margin: 0 0 8px 0; font-size: 14px; color: #93c5fd; }
|
||||
.row { display: flex; gap: 8px; align-items: center; }
|
||||
input, button, select { padding: 8px 10px; border-radius: 6px; border: 1px solid #374151; background: #0b1220; color: #e5e7eb; }
|
||||
button { cursor: pointer; background: #2563eb; border: none; }
|
||||
button.secondary { background: #374151; }
|
||||
button:disabled { background: #1f2937; cursor: not-allowed; }
|
||||
ul { list-style: none; padding: 0; margin: 0; overflow: auto; }
|
||||
li { padding: 8px; border-bottom: 1px solid #374151; display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
||||
.badge { background: #10b981; color: #052e1a; border-radius: 999px; padding: 2px 8px; font-size: 12px; }
|
||||
.chat { display: grid; grid-template-rows: 1fr auto; gap: 8px; height: 100%; }
|
||||
.messages { background: #0b1220; border-radius: 8px; padding: 8px; overflow: auto; border: 1px solid #1f2937; }
|
||||
.msg { margin: 6px 0; }
|
||||
.msg .sender { font-weight: 600; color: #60a5fa; margin-right: 6px; }
|
||||
.system { color: #9ca3af; font-style: italic; }
|
||||
.rooms { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 8px; }
|
||||
.pill { padding: 6px 10px; border-radius: 999px; background: #0b1220; border: 1px solid #374151; cursor: pointer; }
|
||||
.pill.active { background: #1d4ed8; border-color: #1d4ed8; }
|
||||
.invite { display: flex; gap: 6px; align-items: center; }
|
||||
.footer { color: #9ca3af; font-size: 12px; }
|
||||
</style>
|
||||
<script src="https://cdn.jsdelivr.net/npm/sockjs-client@1.6.1/dist/sockjs.min.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/stompjs@2.3.3/lib/stomp.min.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<h1>Simple Chat</h1>
|
||||
<div id="me" class="footer"></div>
|
||||
</header>
|
||||
<div class="container">
|
||||
<div class="panel">
|
||||
<h2>Sign up</h2>
|
||||
<div class="row" style="margin-bottom:8px;">
|
||||
<input id="username" placeholder="username (a-z, 0-9)" />
|
||||
<button id="signupBtn">Sign up</button>
|
||||
</div>
|
||||
<div class="footer">After signup, a WebSocket connection is created. Your online status will be visible to others.</div>
|
||||
|
||||
<h2 style="margin-top:16px;">Online users</h2>
|
||||
<ul id="users"></ul>
|
||||
</div>
|
||||
<div class="panel">
|
||||
<h2>Chat</h2>
|
||||
<div class="rooms" id="rooms"></div>
|
||||
<div class="chat">
|
||||
<div class="messages" id="messages"></div>
|
||||
<div class="row">
|
||||
<input id="messageInput" placeholder="Type a message..." style="flex:1" />
|
||||
<button id="sendBtn" disabled>Send</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
(function(){
|
||||
const state = {
|
||||
username: localStorage.getItem('username') || '',
|
||||
token: localStorage.getItem('token') || '',
|
||||
client: null,
|
||||
connected: false,
|
||||
online: new Set(),
|
||||
rooms: {}, // roomId -> { participants: [a,b], messages: [] }
|
||||
activeRoom: null,
|
||||
subscribedRooms: new Set(),
|
||||
};
|
||||
|
||||
const els = {
|
||||
username: document.getElementById('username'),
|
||||
signupBtn: document.getElementById('signupBtn'),
|
||||
users: document.getElementById('users'),
|
||||
messages: document.getElementById('messages'),
|
||||
messageInput: document.getElementById('messageInput'),
|
||||
sendBtn: document.getElementById('sendBtn'),
|
||||
rooms: document.getElementById('rooms'),
|
||||
me: document.getElementById('me'),
|
||||
};
|
||||
|
||||
function setMe() {
|
||||
if (state.username) {
|
||||
els.me.textContent = `Signed in as ${state.username}`;
|
||||
} else {
|
||||
els.me.textContent = 'Not signed in';
|
||||
}
|
||||
}
|
||||
|
||||
function api(path, options={}){
|
||||
return fetch(path, {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
...options,
|
||||
}).then(r => {
|
||||
if (!r.ok) return r.text().then(t => Promise.reject(new Error(t||r.statusText)));
|
||||
const ct = r.headers.get('content-type')||'';
|
||||
if (ct.includes('application/json')) return r.json();
|
||||
return r.text();
|
||||
});
|
||||
}
|
||||
|
||||
function renderUsers(){
|
||||
els.users.innerHTML = '';
|
||||
const arr = Array.from(state.online).filter(u => u !== state.username).sort();
|
||||
if (!arr.length) {
|
||||
const li = document.createElement('li');
|
||||
li.innerHTML = '<span class="system">No other users online</span>';
|
||||
els.users.appendChild(li);
|
||||
return;
|
||||
}
|
||||
arr.forEach(u => {
|
||||
const li = document.createElement('li');
|
||||
const span = document.createElement('span');
|
||||
span.textContent = u;
|
||||
const btn = document.createElement('button');
|
||||
btn.textContent = 'Invite';
|
||||
btn.onclick = () => sendInvite(u);
|
||||
li.appendChild(span);
|
||||
li.appendChild(btn);
|
||||
els.users.appendChild(li);
|
||||
});
|
||||
}
|
||||
|
||||
function renderRooms(){
|
||||
els.rooms.innerHTML = '';
|
||||
Object.entries(state.rooms).forEach(([roomId, room]) => {
|
||||
const pill = document.createElement('div');
|
||||
pill.className = 'pill' + (state.activeRoom === roomId ? ' active' : '');
|
||||
const other = room.participants.find(p => p !== state.username) || 'room';
|
||||
pill.textContent = other;
|
||||
pill.onclick = () => setActiveRoom(roomId);
|
||||
els.rooms.appendChild(pill);
|
||||
});
|
||||
}
|
||||
|
||||
function renderMessages(){
|
||||
els.messages.innerHTML = '';
|
||||
const room = state.rooms[state.activeRoom];
|
||||
if (!room) {
|
||||
const d = document.createElement('div');
|
||||
d.className = 'system';
|
||||
d.textContent = 'No active room. Send or accept an invite to start chatting.';
|
||||
els.messages.appendChild(d);
|
||||
els.sendBtn.disabled = true;
|
||||
return;
|
||||
}
|
||||
els.sendBtn.disabled = false;
|
||||
room.messages.forEach(m => {
|
||||
const div = document.createElement('div');
|
||||
div.className = 'msg';
|
||||
const sender = document.createElement('span');
|
||||
sender.className = 'sender';
|
||||
sender.textContent = m.sender + ':';
|
||||
const content = document.createElement('span');
|
||||
content.textContent = ' ' + m.content;
|
||||
div.appendChild(sender);
|
||||
div.appendChild(content);
|
||||
els.messages.appendChild(div);
|
||||
});
|
||||
els.messages.scrollTop = els.messages.scrollHeight;
|
||||
}
|
||||
|
||||
function setActiveRoom(roomId){
|
||||
state.activeRoom = roomId;
|
||||
renderRooms();
|
||||
renderMessages();
|
||||
}
|
||||
|
||||
function upsertRoom(roomId, participants){
|
||||
if (!state.rooms[roomId]) {
|
||||
state.rooms[roomId] = { participants: participants || [], messages: [] };
|
||||
if (!state.activeRoom) setActiveRoom(roomId);
|
||||
}
|
||||
}
|
||||
|
||||
function connectWebSocket(){
|
||||
if (!state.token) return;
|
||||
const sock = new SockJS(`/ws?token=${encodeURIComponent(state.token)}`);
|
||||
const client = Stomp.over(sock);
|
||||
client.debug = () => {};
|
||||
client.connect({}, () => {
|
||||
state.client = client;
|
||||
state.connected = true;
|
||||
// Online users topic
|
||||
client.subscribe('/topic/online-users', msg => {
|
||||
try{ const set = new Set(JSON.parse(msg.body)); state.online = set; renderUsers(); } catch(e){}
|
||||
});
|
||||
// Invite queue (user-specific)
|
||||
client.subscribe('/user/queue/invites', msg => {
|
||||
const ev = JSON.parse(msg.body);
|
||||
if (ev.type === 'INVITE') {
|
||||
const accept = confirm(`${ev.from} invited you to chat. Accept?`);
|
||||
if (accept) {
|
||||
client.send('/app/invite/accept', {}, JSON.stringify({ inviter: ev.from }));
|
||||
} else {
|
||||
client.send('/app/invite/decline', {}, JSON.stringify({ inviter: ev.from }));
|
||||
}
|
||||
} else if (ev.type === 'ACCEPT') {
|
||||
// Both sides receive ACCEPT with roomId
|
||||
upsertRoom(ev.roomId, [ev.from, ev.to]);
|
||||
subscribeRoom(ev.roomId);
|
||||
} else if (ev.type === 'DECLINE') {
|
||||
alert(`${ev.from} declined your invite.`);
|
||||
}
|
||||
});
|
||||
// Get initial online users
|
||||
refreshOnline();
|
||||
}, (err) => {
|
||||
console.error('WS error', err);
|
||||
state.connected = false;
|
||||
setTimeout(connectWebSocket, 2000);
|
||||
});
|
||||
}
|
||||
|
||||
function subscribeRoom(roomId){
|
||||
if (!state.client) return;
|
||||
if (state.subscribedRooms.has(roomId)) return;
|
||||
state.subscribedRooms.add(roomId);
|
||||
state.client.subscribe(`/topic/room.${roomId}`, msg => {
|
||||
const chat = JSON.parse(msg.body);
|
||||
upsertRoom(chat.roomId);
|
||||
state.rooms[chat.roomId].messages.push(chat);
|
||||
renderMessages();
|
||||
});
|
||||
}
|
||||
|
||||
function sendInvite(to){
|
||||
if (!state.client) return;
|
||||
state.client.send('/app/invite/send', {}, JSON.stringify({ to }));
|
||||
alert(`Invite sent to ${to}`);
|
||||
}
|
||||
|
||||
function sendMessage(){
|
||||
const roomId = state.activeRoom;
|
||||
const content = els.messageInput.value.trim();
|
||||
if (!content || !roomId || !state.client) return;
|
||||
state.client.send('/app/chat/send', {}, JSON.stringify({ roomId, content }));
|
||||
els.messageInput.value = '';
|
||||
}
|
||||
|
||||
function refreshOnline(){
|
||||
api('/api/online').then(list => {
|
||||
state.online = new Set(list);
|
||||
renderUsers();
|
||||
}).catch(()=>{});
|
||||
}
|
||||
|
||||
function signup(){
|
||||
const raw = els.username.value.trim().toLowerCase();
|
||||
const username = raw.replace(/[^a-z0-9_-]/g, '');
|
||||
if (!username) { alert('Please enter a username'); return; }
|
||||
api('/api/signup', { method: 'POST', body: JSON.stringify({ username }) })
|
||||
.then(res => {
|
||||
state.username = res.username;
|
||||
state.token = res.token;
|
||||
localStorage.setItem('username', state.username);
|
||||
localStorage.setItem('token', state.token);
|
||||
setMe();
|
||||
connectWebSocket();
|
||||
refreshOnline();
|
||||
})
|
||||
.catch(err => alert('Signup failed: ' + err.message));
|
||||
}
|
||||
|
||||
// Init
|
||||
setMe();
|
||||
if (state.username && state.token) {
|
||||
connectWebSocket();
|
||||
refreshOnline();
|
||||
}
|
||||
|
||||
els.signupBtn.addEventListener('click', signup);
|
||||
els.messageInput.addEventListener('keydown', (e)=>{ if (e.key === 'Enter') sendMessage(); });
|
||||
els.sendBtn.addEventListener('click', sendMessage);
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
13
src/test/java/de/w665/testing/TestingApplicationTests.java
Normal file
13
src/test/java/de/w665/testing/TestingApplicationTests.java
Normal file
@@ -0,0 +1,13 @@
|
||||
package de.w665.testing;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest
|
||||
class TestingApplicationTests {
|
||||
|
||||
@Test
|
||||
void contextLoads() {
|
||||
}
|
||||
|
||||
}
|
Reference in New Issue
Block a user