add old files
This commit is contained in:
parent
53e4346d55
commit
19a40483aa
59 changed files with 20831 additions and 0 deletions
3
backend/.gitattributes
vendored
Normal file
3
backend/.gitattributes
vendored
Normal file
|
@ -0,0 +1,3 @@
|
|||
/gradlew text eol=lf
|
||||
*.bat text eol=crlf
|
||||
*.jar binary
|
37
backend/.gitignore
vendored
Normal file
37
backend/.gitignore
vendored
Normal file
|
@ -0,0 +1,37 @@
|
|||
HELP.md
|
||||
.gradle
|
||||
build/
|
||||
!gradle/wrapper/gradle-wrapper.jar
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
bin/
|
||||
!**/src/main/**/bin/
|
||||
!**/src/test/**/bin/
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
out/
|
||||
!**/src/main/**/out/
|
||||
!**/src/test/**/out/
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
33
backend/build.gradle
Normal file
33
backend/build.gradle
Normal file
|
@ -0,0 +1,33 @@
|
|||
plugins {
|
||||
id 'java'
|
||||
id 'org.springframework.boot' version '3.5.4'
|
||||
id 'io.spring.dependency-management' version '1.1.7'
|
||||
}
|
||||
|
||||
group = 'com.hackathon'
|
||||
version = '0.0.1-SNAPSHOT'
|
||||
|
||||
java {
|
||||
toolchain {
|
||||
languageVersion = JavaLanguageVersion.of(21)
|
||||
}
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation 'org.springframework.boot:spring-boot-starter-web'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-security'
|
||||
implementation 'io.jsonwebtoken:jjwt-api:0.12.6'
|
||||
implementation 'io.jsonwebtoken:jjwt-impl:0.12.6'
|
||||
implementation 'io.jsonwebtoken:jjwt-jackson:0.12.6'
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
testImplementation 'org.springframework.security:spring-security-test'
|
||||
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
|
||||
}
|
||||
|
||||
tasks.named('test') {
|
||||
useJUnitPlatform()
|
||||
}
|
251
backend/gradlew
vendored
Executable file
251
backend/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
backend/gradlew.bat
vendored
Normal file
94
backend/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
backend/settings.gradle
Normal file
1
backend/settings.gradle
Normal file
|
@ -0,0 +1 @@
|
|||
rootProject.name = 'backend'
|
|
@ -0,0 +1,13 @@
|
|||
package com.hackathon.backend;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class BackendApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(BackendApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,69 @@
|
|||
package com.hackathon.backend.config;
|
||||
|
||||
import com.hackathon.backend.service.JwtService;
|
||||
import com.hackathon.backend.service.UserService;
|
||||
import com.hackathon.backend.model.User;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Optional;
|
||||
|
||||
@Component
|
||||
public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
|
||||
@Autowired
|
||||
private JwtService jwtService;
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
@NonNull HttpServletRequest request,
|
||||
@NonNull HttpServletResponse response,
|
||||
@NonNull FilterChain filterChain) throws ServletException, IOException {
|
||||
|
||||
final String authHeader = request.getHeader("Authorization");
|
||||
final String jwt;
|
||||
final String userId;
|
||||
|
||||
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
|
||||
filterChain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
|
||||
jwt = authHeader.substring(7);
|
||||
userId = jwtService.extractUserId(jwt);
|
||||
|
||||
if (userId != null && SecurityContextHolder.getContext().getAuthentication() == null) {
|
||||
Optional<User> userOpt = userService.getUserById(userId);
|
||||
|
||||
if (userOpt.isPresent()) {
|
||||
User user = userOpt.get();
|
||||
|
||||
if (jwtService.isTokenValid(jwt, userId) && user.isActive()) {
|
||||
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
|
||||
user,
|
||||
null,
|
||||
new ArrayList<>());
|
||||
authToken.setDetails(
|
||||
new WebAuthenticationDetailsSource().buildDetails(request));
|
||||
SecurityContextHolder.getContext().setAuthentication(authToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,58 @@
|
|||
package com.hackathon.backend.config;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.cors.CorsConfigurationSource;
|
||||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
public class SecurityConfig {
|
||||
|
||||
@Autowired
|
||||
private SimpleTokenFilter simpleTokenFilter;
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
|
||||
.csrf(csrf -> csrf.disable())
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(authz -> authz
|
||||
// Public endpoints - no authentication required
|
||||
.requestMatchers("/api/radio-stations").permitAll() // Create station
|
||||
.requestMatchers("/api/radio-stations/join/**").permitAll() // Join by code
|
||||
.requestMatchers("/api/clients/connect").permitAll() // Client connections
|
||||
|
||||
// All other endpoints require authentication
|
||||
.anyRequest().authenticated())
|
||||
.addFilterBefore(simpleTokenFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CorsConfigurationSource corsConfigurationSource() {
|
||||
CorsConfiguration configuration = new CorsConfiguration();
|
||||
configuration.setAllowedOriginPatterns(List.of("*"));
|
||||
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
|
||||
configuration.setAllowedHeaders(Arrays.asList("*"));
|
||||
configuration.setAllowCredentials(true);
|
||||
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
source.registerCorsConfiguration("/api/**", configuration);
|
||||
return source;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,66 @@
|
|||
package com.hackathon.backend.config;
|
||||
|
||||
import com.hackathon.backend.service.SimpleTokenService;
|
||||
import com.hackathon.backend.model.TokenUser;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
|
||||
@Component
|
||||
public class SimpleTokenFilter extends OncePerRequestFilter {
|
||||
|
||||
@Autowired
|
||||
private SimpleTokenService tokenService;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
@NonNull HttpServletRequest request,
|
||||
@NonNull HttpServletResponse response,
|
||||
@NonNull FilterChain filterChain) throws ServletException, IOException {
|
||||
|
||||
final String authHeader = request.getHeader("Authorization");
|
||||
final String token;
|
||||
|
||||
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
|
||||
filterChain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
|
||||
token = authHeader.substring(7);
|
||||
|
||||
if (SecurityContextHolder.getContext().getAuthentication() == null) {
|
||||
try {
|
||||
if (tokenService.isTokenValid(token)) {
|
||||
String userId = tokenService.extractUserId(token);
|
||||
String username = tokenService.extractUsername(token);
|
||||
String role = tokenService.extractRole(token);
|
||||
|
||||
TokenUser tokenUser = new TokenUser(userId, username, role);
|
||||
|
||||
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
|
||||
tokenUser,
|
||||
null,
|
||||
new ArrayList<>());
|
||||
authToken.setDetails(
|
||||
new WebAuthenticationDetailsSource().buildDetails(request));
|
||||
SecurityContextHolder.getContext().setAuthentication(authToken);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// Invalid token, continue without authentication
|
||||
}
|
||||
}
|
||||
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,123 @@
|
|||
package com.hackathon.backend.controller;
|
||||
|
||||
import com.hackathon.backend.dto.ApiResponse;
|
||||
import com.hackathon.backend.dto.AuthResponse;
|
||||
import com.hackathon.backend.dto.LoginRequest;
|
||||
import com.hackathon.backend.dto.RegisterRequest;
|
||||
import com.hackathon.backend.model.User;
|
||||
import com.hackathon.backend.service.JwtService;
|
||||
import com.hackathon.backend.service.UserService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/auth")
|
||||
@CrossOrigin(origins = "*")
|
||||
public class AuthController {
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
@Autowired
|
||||
private JwtService jwtService;
|
||||
|
||||
@PostMapping("/register")
|
||||
public ResponseEntity<ApiResponse<AuthResponse>> register(@RequestBody RegisterRequest request) {
|
||||
if (request.getUsername() == null || request.getUsername().trim().isEmpty()) {
|
||||
return ResponseEntity.badRequest()
|
||||
.body(ApiResponse.error("Username is required"));
|
||||
}
|
||||
|
||||
if (request.getPassword() == null || request.getPassword().length() < 6) {
|
||||
return ResponseEntity.badRequest()
|
||||
.body(ApiResponse.error("Password must be at least 6 characters long"));
|
||||
}
|
||||
|
||||
if (request.getEmail() == null || request.getEmail().trim().isEmpty()) {
|
||||
return ResponseEntity.badRequest()
|
||||
.body(ApiResponse.error("Email is required"));
|
||||
}
|
||||
|
||||
Optional<User> userOpt = userService.registerUser(
|
||||
request.getUsername().trim(),
|
||||
request.getPassword(),
|
||||
request.getEmail().trim());
|
||||
|
||||
if (userOpt.isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.CONFLICT)
|
||||
.body(ApiResponse.error("Username already exists"));
|
||||
}
|
||||
|
||||
User user = userOpt.get();
|
||||
String token = jwtService.generateToken(user.getId(), user.getUsername());
|
||||
|
||||
AuthResponse authResponse = new AuthResponse(
|
||||
token,
|
||||
user.getId(),
|
||||
user.getUsername(),
|
||||
jwtService.getExpirationTime());
|
||||
|
||||
return ResponseEntity.status(HttpStatus.CREATED)
|
||||
.body(ApiResponse.success("User registered successfully", authResponse));
|
||||
}
|
||||
|
||||
@PostMapping("/login")
|
||||
public ResponseEntity<ApiResponse<AuthResponse>> login(@RequestBody LoginRequest request) {
|
||||
if (request.getUsername() == null || request.getUsername().trim().isEmpty()) {
|
||||
return ResponseEntity.badRequest()
|
||||
.body(ApiResponse.error("Username is required"));
|
||||
}
|
||||
|
||||
if (request.getPassword() == null || request.getPassword().isEmpty()) {
|
||||
return ResponseEntity.badRequest()
|
||||
.body(ApiResponse.error("Password is required"));
|
||||
}
|
||||
|
||||
Optional<User> userOpt = userService.authenticateUser(
|
||||
request.getUsername().trim(),
|
||||
request.getPassword());
|
||||
|
||||
if (userOpt.isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
|
||||
.body(ApiResponse.error("Invalid username or password"));
|
||||
}
|
||||
|
||||
User user = userOpt.get();
|
||||
String token = jwtService.generateToken(user.getId(), user.getUsername());
|
||||
|
||||
AuthResponse authResponse = new AuthResponse(
|
||||
token,
|
||||
user.getId(),
|
||||
user.getUsername(),
|
||||
jwtService.getExpirationTime());
|
||||
|
||||
return ResponseEntity.ok(ApiResponse.success("Login successful", authResponse));
|
||||
}
|
||||
|
||||
@GetMapping("/me")
|
||||
public ResponseEntity<ApiResponse<User>> getCurrentUser(@RequestHeader("Authorization") String authHeader) {
|
||||
try {
|
||||
String token = authHeader.substring(7); // Remove "Bearer "
|
||||
String userId = jwtService.extractUserId(token);
|
||||
|
||||
Optional<User> userOpt = userService.getUserById(userId);
|
||||
if (userOpt.isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(ApiResponse.error("User not found"));
|
||||
}
|
||||
|
||||
User user = userOpt.get();
|
||||
// Don't send password in response
|
||||
user.setPassword(null);
|
||||
|
||||
return ResponseEntity.ok(ApiResponse.success(user));
|
||||
} catch (Exception e) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
|
||||
.body(ApiResponse.error("Invalid token"));
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,151 @@
|
|||
package com.hackathon.backend.controller;
|
||||
|
||||
import com.hackathon.backend.dto.ApiResponse;
|
||||
import com.hackathon.backend.dto.ConnectClientRequest;
|
||||
import com.hackathon.backend.model.Client;
|
||||
import com.hackathon.backend.model.RadioStation;
|
||||
import com.hackathon.backend.service.RadioStationService;
|
||||
import com.hackathon.backend.service.SimpleTokenService;
|
||||
import com.hackathon.backend.util.AuthUtil;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/clients")
|
||||
@CrossOrigin(origins = "*")
|
||||
public class ClientController {
|
||||
|
||||
@Autowired
|
||||
private RadioStationService radioStationService;
|
||||
|
||||
@Autowired
|
||||
private SimpleTokenService tokenService;
|
||||
|
||||
@PostMapping("/connect")
|
||||
public ResponseEntity<ApiResponse<Map<String, Object>>> connectClient(@RequestBody ConnectClientRequest request) {
|
||||
// This endpoint is public - no authentication required for joining stations
|
||||
Optional<Client> client;
|
||||
|
||||
// If radioStationId is provided, use it with join code validation
|
||||
if (request.getRadioStationId() != null && !request.getRadioStationId().isEmpty()) {
|
||||
client = radioStationService.connectClient(
|
||||
request.getUsername(),
|
||||
request.getRadioStationId(),
|
||||
request.getJoinCode());
|
||||
} else {
|
||||
// Otherwise, connect by join code only
|
||||
client = radioStationService.connectClientByJoinCode(
|
||||
request.getUsername(),
|
||||
request.getJoinCode());
|
||||
}
|
||||
|
||||
if (client.isPresent()) {
|
||||
// Generate a client token
|
||||
String clientToken = tokenService.generateToken(request.getUsername(), "client");
|
||||
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
response.put("client", client.get());
|
||||
response.put("clientToken", clientToken);
|
||||
response.put("message", "Successfully connected to radio station. Use this token for further requests.");
|
||||
|
||||
return ResponseEntity.status(HttpStatus.CREATED)
|
||||
.body(ApiResponse.success("Successfully connected to radio station", response));
|
||||
} else {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(ApiResponse.error("Failed to connect to radio station. Invalid join code or station not found."));
|
||||
}
|
||||
}
|
||||
|
||||
@DeleteMapping("/{clientId}/disconnect")
|
||||
public ResponseEntity<ApiResponse<Void>> disconnectClient(@PathVariable String clientId) {
|
||||
String currentUserId = AuthUtil.getCurrentUserId();
|
||||
|
||||
// Check if user is authenticated
|
||||
if (currentUserId == null) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
|
||||
.body(ApiResponse.error("User not authenticated"));
|
||||
}
|
||||
|
||||
// Get client to check authorization
|
||||
Optional<Client> clientOpt = radioStationService.getClient(clientId);
|
||||
if (clientOpt.isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(ApiResponse.error("Client not found"));
|
||||
}
|
||||
|
||||
Client client = clientOpt.get();
|
||||
|
||||
// Get the station to check if current user is the owner
|
||||
Optional<RadioStation> stationOpt = radioStationService.getRadioStation(client.getRadioStationId());
|
||||
if (stationOpt.isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(ApiResponse.error("Radio station not found"));
|
||||
}
|
||||
|
||||
RadioStation station = stationOpt.get();
|
||||
|
||||
// Allow disconnection if:
|
||||
// 1. Current user is the station owner (can disconnect anyone)
|
||||
// 2. Current user is the client themselves (self-disconnect)
|
||||
boolean isOwner = currentUserId.equals(station.getOwnerId());
|
||||
// Note: For self-disconnect, we'd need to link clients to users, which isn't
|
||||
// implemented yet
|
||||
// For now, only station owners can disconnect clients
|
||||
|
||||
if (!isOwner) {
|
||||
return ResponseEntity.status(HttpStatus.FORBIDDEN)
|
||||
.body(ApiResponse.error("Only the station owner can disconnect clients"));
|
||||
}
|
||||
|
||||
boolean disconnected = radioStationService.disconnectClient(clientId);
|
||||
if (disconnected) {
|
||||
return ResponseEntity.ok(ApiResponse.success("Client disconnected successfully", null));
|
||||
} else {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(ApiResponse.error("Failed to disconnect client"));
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/{clientId}")
|
||||
public ResponseEntity<ApiResponse<Client>> getClient(@PathVariable String clientId) {
|
||||
String currentUserId = AuthUtil.getCurrentUserId();
|
||||
if (currentUserId == null) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
|
||||
.body(ApiResponse.error("User not authenticated"));
|
||||
}
|
||||
|
||||
Optional<Client> client = radioStationService.getClient(clientId);
|
||||
if (client.isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(ApiResponse.error("Client not found"));
|
||||
}
|
||||
|
||||
return ResponseEntity.ok(ApiResponse.success(client.get()));
|
||||
}
|
||||
|
||||
@GetMapping("/station/{radioStationId}")
|
||||
public ResponseEntity<ApiResponse<List<Client>>> getConnectedClients(@PathVariable String radioStationId) {
|
||||
String currentUserId = AuthUtil.getCurrentUserId();
|
||||
if (currentUserId == null) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
|
||||
.body(ApiResponse.error("User not authenticated"));
|
||||
}
|
||||
|
||||
// Check if station exists
|
||||
Optional<RadioStation> stationOpt = radioStationService.getRadioStation(radioStationId);
|
||||
if (stationOpt.isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(ApiResponse.error("Radio station not found"));
|
||||
}
|
||||
|
||||
List<Client> clients = radioStationService.getConnectedClients(radioStationId);
|
||||
return ResponseEntity.ok(ApiResponse.success(clients));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,170 @@
|
|||
package com.hackathon.backend.controller;
|
||||
|
||||
import com.hackathon.backend.dto.ApiResponse;
|
||||
import com.hackathon.backend.dto.CreateRadioStationRequest;
|
||||
import com.hackathon.backend.dto.UpdateRadioStationRequest;
|
||||
import com.hackathon.backend.model.RadioStation;
|
||||
import com.hackathon.backend.service.RadioStationService;
|
||||
import com.hackathon.backend.service.SimpleTokenService;
|
||||
import com.hackathon.backend.util.AuthUtil;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/radio-stations")
|
||||
@CrossOrigin(origins = "*")
|
||||
public class RadioStationController {
|
||||
|
||||
@Autowired
|
||||
private RadioStationService radioStationService;
|
||||
|
||||
@Autowired
|
||||
private SimpleTokenService tokenService;
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<ApiResponse<Map<String, Object>>> createRadioStation(@RequestBody CreateRadioStationRequest request) {
|
||||
try {
|
||||
// Generate a token for the station owner
|
||||
String ownerToken = tokenService.generateToken(request.getName() + "_owner", "owner");
|
||||
String ownerId = tokenService.extractUserId(ownerToken);
|
||||
|
||||
RadioStation station = radioStationService.createRadioStation(
|
||||
request.getName(),
|
||||
request.getDescription(),
|
||||
ownerId);
|
||||
|
||||
// Return both the station and the owner token
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
response.put("station", station);
|
||||
response.put("ownerToken", ownerToken);
|
||||
response.put("message", "Radio station created successfully. Use this token to manage your station.");
|
||||
|
||||
return ResponseEntity.status(HttpStatus.CREATED)
|
||||
.body(ApiResponse.success("Radio station created successfully", response));
|
||||
} catch (Exception e) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(ApiResponse.error("Failed to create radio station: " + e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<ApiResponse<List<RadioStation>>> getAllRadioStations(
|
||||
@RequestParam(defaultValue = "false") boolean activeOnly) {
|
||||
String currentUserId = AuthUtil.getCurrentUserId();
|
||||
if (currentUserId == null) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
|
||||
.body(ApiResponse.error("User not authenticated"));
|
||||
}
|
||||
|
||||
List<RadioStation> stations = activeOnly ? radioStationService.getActiveRadioStations()
|
||||
: radioStationService.getAllRadioStations();
|
||||
return ResponseEntity.ok(ApiResponse.success(stations));
|
||||
}
|
||||
|
||||
@GetMapping("/{stationId}")
|
||||
public ResponseEntity<ApiResponse<RadioStation>> getRadioStation(@PathVariable String stationId) {
|
||||
String currentUserId = AuthUtil.getCurrentUserId();
|
||||
if (currentUserId == null) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
|
||||
.body(ApiResponse.error("User not authenticated"));
|
||||
}
|
||||
|
||||
Optional<RadioStation> station = radioStationService.getRadioStation(stationId);
|
||||
if (station.isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(ApiResponse.error("Radio station not found"));
|
||||
}
|
||||
|
||||
return ResponseEntity.ok(ApiResponse.success(station.get()));
|
||||
}
|
||||
|
||||
@GetMapping("/join/{joinCode}")
|
||||
public ResponseEntity<ApiResponse<RadioStation>> getRadioStationByJoinCode(@PathVariable String joinCode) {
|
||||
// This endpoint is public - no authentication required
|
||||
Optional<RadioStation> station = radioStationService.getRadioStationByJoinCode(joinCode);
|
||||
if (station.isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(ApiResponse.error("Radio station not found with join code"));
|
||||
}
|
||||
|
||||
return ResponseEntity.ok(ApiResponse.success(station.get()));
|
||||
}
|
||||
|
||||
@PutMapping("/{stationId}")
|
||||
public ResponseEntity<ApiResponse<RadioStation>> updateRadioStation(
|
||||
@PathVariable String stationId,
|
||||
@RequestBody UpdateRadioStationRequest request) {
|
||||
|
||||
String currentUserId = AuthUtil.getCurrentUserId();
|
||||
if (currentUserId == null) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
|
||||
.body(ApiResponse.error("User not authenticated"));
|
||||
}
|
||||
|
||||
// Check if station exists
|
||||
Optional<RadioStation> stationOpt = radioStationService.getRadioStation(stationId);
|
||||
if (stationOpt.isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(ApiResponse.error("Radio station not found"));
|
||||
}
|
||||
|
||||
RadioStation station = stationOpt.get();
|
||||
|
||||
// Check if current user is the owner
|
||||
if (!currentUserId.equals(station.getOwnerId())) {
|
||||
return ResponseEntity.status(HttpStatus.FORBIDDEN)
|
||||
.body(ApiResponse.error("Only the station owner can update the radio station"));
|
||||
}
|
||||
|
||||
Optional<RadioStation> updated = radioStationService.updateRadioStation(
|
||||
stationId,
|
||||
request.getName(),
|
||||
request.getDescription());
|
||||
|
||||
if (updated.isPresent()) {
|
||||
return ResponseEntity.ok(ApiResponse.success("Radio station updated successfully", updated.get()));
|
||||
} else {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(ApiResponse.error("Failed to update radio station"));
|
||||
}
|
||||
}
|
||||
|
||||
@DeleteMapping("/{stationId}")
|
||||
public ResponseEntity<ApiResponse<Void>> deleteRadioStation(@PathVariable String stationId) {
|
||||
String currentUserId = AuthUtil.getCurrentUserId();
|
||||
if (currentUserId == null) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
|
||||
.body(ApiResponse.error("User not authenticated"));
|
||||
}
|
||||
|
||||
// Check if station exists
|
||||
Optional<RadioStation> stationOpt = radioStationService.getRadioStation(stationId);
|
||||
if (stationOpt.isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(ApiResponse.error("Radio station not found"));
|
||||
}
|
||||
|
||||
RadioStation station = stationOpt.get();
|
||||
|
||||
// Check if current user is the owner
|
||||
if (!currentUserId.equals(station.getOwnerId())) {
|
||||
return ResponseEntity.status(HttpStatus.FORBIDDEN)
|
||||
.body(ApiResponse.error("Only the station owner can delete the radio station"));
|
||||
}
|
||||
|
||||
boolean deleted = radioStationService.deleteRadioStation(stationId);
|
||||
if (deleted) {
|
||||
return ResponseEntity.ok(ApiResponse.success("Radio station deleted successfully", null));
|
||||
} else {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(ApiResponse.error("Failed to delete radio station"));
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,168 @@
|
|||
package com.hackathon.backend.controller;
|
||||
|
||||
import com.hackathon.backend.dto.AddSongRequest;
|
||||
import com.hackathon.backend.dto.ApiResponse;
|
||||
import com.hackathon.backend.dto.VoteRequest;
|
||||
import com.hackathon.backend.model.RadioStation;
|
||||
import com.hackathon.backend.model.Song;
|
||||
import com.hackathon.backend.service.RadioStationService;
|
||||
import com.hackathon.backend.util.AuthUtil;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/radio-stations/{stationId}/songs")
|
||||
@CrossOrigin(origins = "*")
|
||||
public class SongController {
|
||||
|
||||
@Autowired
|
||||
private RadioStationService radioStationService;
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<ApiResponse<Song>> addSongToQueue(
|
||||
@PathVariable String stationId,
|
||||
@RequestBody AddSongRequest request) {
|
||||
|
||||
String currentUserId = AuthUtil.getCurrentUserId();
|
||||
if (currentUserId == null) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
|
||||
.body(ApiResponse.error("User not authenticated"));
|
||||
}
|
||||
|
||||
// Check if station exists
|
||||
Optional<RadioStation> stationOpt = radioStationService.getRadioStation(stationId);
|
||||
if (stationOpt.isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(ApiResponse.error("Radio station not found"));
|
||||
}
|
||||
|
||||
// Use the authenticated user as the one adding the song
|
||||
Optional<Song> song = radioStationService.addSongToQueue(
|
||||
stationId,
|
||||
request.getTitle(),
|
||||
request.getArtist(),
|
||||
request.getAlbum(),
|
||||
request.getDuration(),
|
||||
request.getUrl(),
|
||||
currentUserId);
|
||||
|
||||
if (song.isPresent()) {
|
||||
return ResponseEntity.status(HttpStatus.CREATED)
|
||||
.body(ApiResponse.success("Song added to queue successfully", song.get()));
|
||||
} else {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(ApiResponse.error("Failed to add song to queue"));
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/queue")
|
||||
public ResponseEntity<ApiResponse<List<Song>>> getSongQueue(@PathVariable String stationId) {
|
||||
String currentUserId = AuthUtil.getCurrentUserId();
|
||||
if (currentUserId == null) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
|
||||
.body(ApiResponse.error("User not authenticated"));
|
||||
}
|
||||
|
||||
List<Song> queue = radioStationService.getSongQueue(stationId);
|
||||
return ResponseEntity.ok(ApiResponse.success(queue));
|
||||
}
|
||||
|
||||
@GetMapping("/current")
|
||||
public ResponseEntity<ApiResponse<Song>> getCurrentlyPlaying(@PathVariable String stationId) {
|
||||
String currentUserId = AuthUtil.getCurrentUserId();
|
||||
if (currentUserId == null) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
|
||||
.body(ApiResponse.error("User not authenticated"));
|
||||
}
|
||||
|
||||
Optional<Song> current = radioStationService.getCurrentlyPlaying(stationId);
|
||||
if (current.isPresent()) {
|
||||
return ResponseEntity.ok(ApiResponse.success(current.get()));
|
||||
} else {
|
||||
return ResponseEntity.ok(ApiResponse.success("No song currently playing", null));
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/next")
|
||||
public ResponseEntity<ApiResponse<Song>> playNextSong(@PathVariable String stationId) {
|
||||
String currentUserId = AuthUtil.getCurrentUserId();
|
||||
if (currentUserId == null) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
|
||||
.body(ApiResponse.error("User not authenticated"));
|
||||
}
|
||||
|
||||
// Check if station exists
|
||||
Optional<RadioStation> stationOpt = radioStationService.getRadioStation(stationId);
|
||||
if (stationOpt.isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(ApiResponse.error("Radio station not found"));
|
||||
}
|
||||
|
||||
RadioStation station = stationOpt.get();
|
||||
|
||||
// Only station owner can control playback
|
||||
if (!currentUserId.equals(station.getOwnerId())) {
|
||||
return ResponseEntity.status(HttpStatus.FORBIDDEN)
|
||||
.body(ApiResponse.error("Only the station owner can control playback"));
|
||||
}
|
||||
|
||||
Optional<Song> nextSong = radioStationService.playNextSong(stationId);
|
||||
if (nextSong.isPresent()) {
|
||||
return ResponseEntity.ok(ApiResponse.success("Playing next song", nextSong.get()));
|
||||
} else {
|
||||
return ResponseEntity.ok(ApiResponse.success("No songs in queue", null));
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/{songId}/vote")
|
||||
public ResponseEntity<ApiResponse<Song>> voteSong(
|
||||
@PathVariable String stationId,
|
||||
@PathVariable String songId,
|
||||
@RequestBody VoteRequest request) {
|
||||
|
||||
String currentUserId = AuthUtil.getCurrentUserId();
|
||||
if (currentUserId == null) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
|
||||
.body(ApiResponse.error("User not authenticated"));
|
||||
}
|
||||
|
||||
// Use the authenticated user as the one voting
|
||||
Optional<Song> song = radioStationService.voteSong(
|
||||
stationId,
|
||||
songId,
|
||||
currentUserId,
|
||||
request.getVoteType());
|
||||
|
||||
if (song.isPresent()) {
|
||||
return ResponseEntity.ok(ApiResponse.success("Vote recorded successfully", song.get()));
|
||||
} else {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(ApiResponse.error("Failed to record vote"));
|
||||
}
|
||||
}
|
||||
|
||||
@DeleteMapping("/{songId}/vote")
|
||||
public ResponseEntity<ApiResponse<Void>> removeSongVote(
|
||||
@PathVariable String stationId,
|
||||
@PathVariable String songId) {
|
||||
|
||||
String currentUserId = AuthUtil.getCurrentUserId();
|
||||
if (currentUserId == null) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
|
||||
.body(ApiResponse.error("User not authenticated"));
|
||||
}
|
||||
|
||||
boolean removed = radioStationService.removeSongVote(stationId, songId, currentUserId);
|
||||
if (removed) {
|
||||
return ResponseEntity.ok(ApiResponse.success("Vote removed successfully", null));
|
||||
} else {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(ApiResponse.error("Failed to remove vote"));
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,70 @@
|
|||
package com.hackathon.backend.dto;
|
||||
|
||||
public class AddSongRequest {
|
||||
private String title;
|
||||
private String artist;
|
||||
private String album;
|
||||
private int duration;
|
||||
private String url;
|
||||
private String addedBy;
|
||||
|
||||
public AddSongRequest() {
|
||||
}
|
||||
|
||||
public AddSongRequest(String title, String artist, String album, int duration, String url, String addedBy) {
|
||||
this.title = title;
|
||||
this.artist = artist;
|
||||
this.album = album;
|
||||
this.duration = duration;
|
||||
this.url = url;
|
||||
this.addedBy = addedBy;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public String getArtist() {
|
||||
return artist;
|
||||
}
|
||||
|
||||
public void setArtist(String artist) {
|
||||
this.artist = artist;
|
||||
}
|
||||
|
||||
public String getAlbum() {
|
||||
return album;
|
||||
}
|
||||
|
||||
public void setAlbum(String album) {
|
||||
this.album = album;
|
||||
}
|
||||
|
||||
public int getDuration() {
|
||||
return duration;
|
||||
}
|
||||
|
||||
public void setDuration(int duration) {
|
||||
this.duration = duration;
|
||||
}
|
||||
|
||||
public String getUrl() {
|
||||
return url;
|
||||
}
|
||||
|
||||
public void setUrl(String url) {
|
||||
this.url = url;
|
||||
}
|
||||
|
||||
public String getAddedBy() {
|
||||
return addedBy;
|
||||
}
|
||||
|
||||
public void setAddedBy(String addedBy) {
|
||||
this.addedBy = addedBy;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,52 @@
|
|||
package com.hackathon.backend.dto;
|
||||
|
||||
public class ApiResponse<T> {
|
||||
private boolean success;
|
||||
private String message;
|
||||
private T data;
|
||||
|
||||
public ApiResponse() {
|
||||
}
|
||||
|
||||
public ApiResponse(boolean success, String message, T data) {
|
||||
this.success = success;
|
||||
this.message = message;
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public static <T> ApiResponse<T> success(T data) {
|
||||
return new ApiResponse<>(true, "Success", data);
|
||||
}
|
||||
|
||||
public static <T> ApiResponse<T> success(String message, T data) {
|
||||
return new ApiResponse<>(true, message, data);
|
||||
}
|
||||
|
||||
public static <T> ApiResponse<T> error(String message) {
|
||||
return new ApiResponse<>(false, message, null);
|
||||
}
|
||||
|
||||
public boolean isSuccess() {
|
||||
return success;
|
||||
}
|
||||
|
||||
public void setSuccess(boolean success) {
|
||||
this.success = success;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public T getData() {
|
||||
return data;
|
||||
}
|
||||
|
||||
public void setData(T data) {
|
||||
this.data = data;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
package com.hackathon.backend.dto;
|
||||
|
||||
public class AuthResponse {
|
||||
private String token;
|
||||
private String userId;
|
||||
private String username;
|
||||
private long expiresIn; // milliseconds
|
||||
|
||||
public AuthResponse() {
|
||||
}
|
||||
|
||||
public AuthResponse(String token, String userId, String username, long expiresIn) {
|
||||
this.token = token;
|
||||
this.userId = userId;
|
||||
this.username = username;
|
||||
this.expiresIn = expiresIn;
|
||||
}
|
||||
|
||||
public String getToken() {
|
||||
return token;
|
||||
}
|
||||
|
||||
public void setToken(String token) {
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
public String getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(String userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public long getExpiresIn() {
|
||||
return expiresIn;
|
||||
}
|
||||
|
||||
public void setExpiresIn(long expiresIn) {
|
||||
this.expiresIn = expiresIn;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,40 @@
|
|||
package com.hackathon.backend.dto;
|
||||
|
||||
public class ConnectClientRequest {
|
||||
private String username;
|
||||
private String radioStationId;
|
||||
private String joinCode;
|
||||
|
||||
public ConnectClientRequest() {
|
||||
}
|
||||
|
||||
public ConnectClientRequest(String username, String radioStationId, String joinCode) {
|
||||
this.username = username;
|
||||
this.radioStationId = radioStationId;
|
||||
this.joinCode = joinCode;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getRadioStationId() {
|
||||
return radioStationId;
|
||||
}
|
||||
|
||||
public void setRadioStationId(String radioStationId) {
|
||||
this.radioStationId = radioStationId;
|
||||
}
|
||||
|
||||
public String getJoinCode() {
|
||||
return joinCode;
|
||||
}
|
||||
|
||||
public void setJoinCode(String joinCode) {
|
||||
this.joinCode = joinCode;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package com.hackathon.backend.dto;
|
||||
|
||||
public class CreateRadioStationRequest {
|
||||
private String name;
|
||||
private String description;
|
||||
|
||||
public CreateRadioStationRequest() {
|
||||
}
|
||||
|
||||
public CreateRadioStationRequest(String name, String description) {
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package com.hackathon.backend.dto;
|
||||
|
||||
public class LoginRequest {
|
||||
private String username;
|
||||
private String password;
|
||||
|
||||
public LoginRequest() {
|
||||
}
|
||||
|
||||
public LoginRequest(String username, String password) {
|
||||
this.username = username;
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,40 @@
|
|||
package com.hackathon.backend.dto;
|
||||
|
||||
public class RegisterRequest {
|
||||
private String username;
|
||||
private String password;
|
||||
private String email;
|
||||
|
||||
public RegisterRequest() {
|
||||
}
|
||||
|
||||
public RegisterRequest(String username, String password, String email) {
|
||||
this.username = username;
|
||||
this.password = password;
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package com.hackathon.backend.dto;
|
||||
|
||||
public class UpdateRadioStationRequest {
|
||||
private String name;
|
||||
private String description;
|
||||
|
||||
public UpdateRadioStationRequest() {
|
||||
}
|
||||
|
||||
public UpdateRadioStationRequest(String name, String description) {
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.hackathon.backend.dto;
|
||||
|
||||
import com.hackathon.backend.model.VoteType;
|
||||
|
||||
public class VoteRequest {
|
||||
private String clientId;
|
||||
private VoteType voteType;
|
||||
|
||||
public VoteRequest() {
|
||||
}
|
||||
|
||||
public VoteRequest(String clientId, VoteType voteType) {
|
||||
this.clientId = clientId;
|
||||
this.voteType = voteType;
|
||||
}
|
||||
|
||||
public String getClientId() {
|
||||
return clientId;
|
||||
}
|
||||
|
||||
public void setClientId(String clientId) {
|
||||
this.clientId = clientId;
|
||||
}
|
||||
|
||||
public VoteType getVoteType() {
|
||||
return voteType;
|
||||
}
|
||||
|
||||
public void setVoteType(VoteType voteType) {
|
||||
this.voteType = voteType;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,65 @@
|
|||
package com.hackathon.backend.model;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
public class Client {
|
||||
private String id;
|
||||
private String username;
|
||||
private String radioStationId;
|
||||
private LocalDateTime connectedAt;
|
||||
private boolean isActive;
|
||||
|
||||
public Client() {
|
||||
this.id = UUID.randomUUID().toString();
|
||||
this.connectedAt = LocalDateTime.now();
|
||||
this.isActive = true;
|
||||
}
|
||||
|
||||
public Client(String username, String radioStationId) {
|
||||
this();
|
||||
this.username = username;
|
||||
this.radioStationId = radioStationId;
|
||||
}
|
||||
|
||||
// Getters and Setters
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getRadioStationId() {
|
||||
return radioStationId;
|
||||
}
|
||||
|
||||
public void setRadioStationId(String radioStationId) {
|
||||
this.radioStationId = radioStationId;
|
||||
}
|
||||
|
||||
public LocalDateTime getConnectedAt() {
|
||||
return connectedAt;
|
||||
}
|
||||
|
||||
public void setConnectedAt(LocalDateTime connectedAt) {
|
||||
this.connectedAt = connectedAt;
|
||||
}
|
||||
|
||||
public boolean isActive() {
|
||||
return isActive;
|
||||
}
|
||||
|
||||
public void setActive(boolean active) {
|
||||
isActive = active;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,128 @@
|
|||
package com.hackathon.backend.model;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.UUID;
|
||||
|
||||
public class RadioStation {
|
||||
private String id;
|
||||
private String name;
|
||||
private String description;
|
||||
private String ownerId;
|
||||
private String joinCode;
|
||||
private LocalDateTime createdAt;
|
||||
private boolean isActive;
|
||||
private List<String> connectedClients;
|
||||
private List<Song> songQueue;
|
||||
private Song currentlyPlaying;
|
||||
|
||||
public RadioStation() {
|
||||
this.id = UUID.randomUUID().toString();
|
||||
this.joinCode = generateJoinCode();
|
||||
this.createdAt = LocalDateTime.now();
|
||||
this.isActive = true;
|
||||
this.connectedClients = new ArrayList<>();
|
||||
this.songQueue = new ArrayList<>();
|
||||
}
|
||||
|
||||
public RadioStation(String name, String description, String ownerId) {
|
||||
this();
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
this.ownerId = ownerId;
|
||||
}
|
||||
|
||||
private String generateJoinCode() {
|
||||
// Generate a 6-character alphanumeric code
|
||||
String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
Random random = new Random();
|
||||
StringBuilder code = new StringBuilder();
|
||||
for (int i = 0; i < 6; i++) {
|
||||
code.append(chars.charAt(random.nextInt(chars.length())));
|
||||
}
|
||||
return code.toString();
|
||||
}
|
||||
|
||||
// Getters and Setters
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public String getOwnerId() {
|
||||
return ownerId;
|
||||
}
|
||||
|
||||
public void setOwnerId(String ownerId) {
|
||||
this.ownerId = ownerId;
|
||||
}
|
||||
|
||||
public String getJoinCode() {
|
||||
return joinCode;
|
||||
}
|
||||
|
||||
public void setJoinCode(String joinCode) {
|
||||
this.joinCode = joinCode;
|
||||
}
|
||||
|
||||
public LocalDateTime getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(LocalDateTime createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
public boolean isActive() {
|
||||
return isActive;
|
||||
}
|
||||
|
||||
public void setActive(boolean active) {
|
||||
isActive = active;
|
||||
}
|
||||
|
||||
public List<String> getConnectedClients() {
|
||||
return connectedClients;
|
||||
}
|
||||
|
||||
public void setConnectedClients(List<String> connectedClients) {
|
||||
this.connectedClients = connectedClients;
|
||||
}
|
||||
|
||||
public List<Song> getSongQueue() {
|
||||
return songQueue;
|
||||
}
|
||||
|
||||
public void setSongQueue(List<Song> songQueue) {
|
||||
this.songQueue = songQueue;
|
||||
}
|
||||
|
||||
public Song getCurrentlyPlaying() {
|
||||
return currentlyPlaying;
|
||||
}
|
||||
|
||||
public void setCurrentlyPlaying(Song currentlyPlaying) {
|
||||
this.currentlyPlaying = currentlyPlaying;
|
||||
}
|
||||
}
|
163
backend/src/main/java/com/hackathon/backend/model/Song.java
Normal file
163
backend/src/main/java/com/hackathon/backend/model/Song.java
Normal file
|
@ -0,0 +1,163 @@
|
|||
package com.hackathon.backend.model;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
public class Song {
|
||||
private String id;
|
||||
private String title;
|
||||
private String artist;
|
||||
private String album;
|
||||
private int duration; // in seconds
|
||||
private String url;
|
||||
private String addedBy;
|
||||
private LocalDateTime addedAt;
|
||||
private Map<String, VoteType> votes; // clientId -> vote
|
||||
private int upvotes;
|
||||
private int downvotes;
|
||||
|
||||
public Song() {
|
||||
this.id = UUID.randomUUID().toString();
|
||||
this.addedAt = LocalDateTime.now();
|
||||
this.votes = new HashMap<>();
|
||||
this.upvotes = 0;
|
||||
this.downvotes = 0;
|
||||
}
|
||||
|
||||
public Song(String title, String artist, String album, int duration, String url, String addedBy) {
|
||||
this();
|
||||
this.title = title;
|
||||
this.artist = artist;
|
||||
this.album = album;
|
||||
this.duration = duration;
|
||||
this.url = url;
|
||||
this.addedBy = addedBy;
|
||||
}
|
||||
|
||||
public void addVote(String clientId, VoteType voteType) {
|
||||
VoteType previousVote = votes.get(clientId);
|
||||
|
||||
// Remove previous vote count
|
||||
if (previousVote != null) {
|
||||
if (previousVote == VoteType.UPVOTE) {
|
||||
upvotes--;
|
||||
} else if (previousVote == VoteType.DOWNVOTE) {
|
||||
downvotes--;
|
||||
}
|
||||
}
|
||||
|
||||
// Add new vote
|
||||
votes.put(clientId, voteType);
|
||||
if (voteType == VoteType.UPVOTE) {
|
||||
upvotes++;
|
||||
} else if (voteType == VoteType.DOWNVOTE) {
|
||||
downvotes++;
|
||||
}
|
||||
}
|
||||
|
||||
public void removeVote(String clientId) {
|
||||
VoteType previousVote = votes.remove(clientId);
|
||||
if (previousVote != null) {
|
||||
if (previousVote == VoteType.UPVOTE) {
|
||||
upvotes--;
|
||||
} else if (previousVote == VoteType.DOWNVOTE) {
|
||||
downvotes--;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int getScore() {
|
||||
return upvotes - downvotes;
|
||||
}
|
||||
|
||||
// Getters and Setters
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public String getArtist() {
|
||||
return artist;
|
||||
}
|
||||
|
||||
public void setArtist(String artist) {
|
||||
this.artist = artist;
|
||||
}
|
||||
|
||||
public String getAlbum() {
|
||||
return album;
|
||||
}
|
||||
|
||||
public void setAlbum(String album) {
|
||||
this.album = album;
|
||||
}
|
||||
|
||||
public int getDuration() {
|
||||
return duration;
|
||||
}
|
||||
|
||||
public void setDuration(int duration) {
|
||||
this.duration = duration;
|
||||
}
|
||||
|
||||
public String getUrl() {
|
||||
return url;
|
||||
}
|
||||
|
||||
public void setUrl(String url) {
|
||||
this.url = url;
|
||||
}
|
||||
|
||||
public String getAddedBy() {
|
||||
return addedBy;
|
||||
}
|
||||
|
||||
public void setAddedBy(String addedBy) {
|
||||
this.addedBy = addedBy;
|
||||
}
|
||||
|
||||
public LocalDateTime getAddedAt() {
|
||||
return addedAt;
|
||||
}
|
||||
|
||||
public void setAddedAt(LocalDateTime addedAt) {
|
||||
this.addedAt = addedAt;
|
||||
}
|
||||
|
||||
public Map<String, VoteType> getVotes() {
|
||||
return votes;
|
||||
}
|
||||
|
||||
public void setVotes(Map<String, VoteType> votes) {
|
||||
this.votes = votes;
|
||||
}
|
||||
|
||||
public int getUpvotes() {
|
||||
return upvotes;
|
||||
}
|
||||
|
||||
public void setUpvotes(int upvotes) {
|
||||
this.upvotes = upvotes;
|
||||
}
|
||||
|
||||
public int getDownvotes() {
|
||||
return downvotes;
|
||||
}
|
||||
|
||||
public void setDownvotes(int downvotes) {
|
||||
this.downvotes = downvotes;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package com.hackathon.backend.model;
|
||||
|
||||
public class TokenUser {
|
||||
private String userId;
|
||||
private String username;
|
||||
private String role; // "owner" or "client"
|
||||
|
||||
public TokenUser(String userId, String username, String role) {
|
||||
this.userId = userId;
|
||||
this.username = username;
|
||||
this.role = role;
|
||||
}
|
||||
|
||||
public String getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(String userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getRole() {
|
||||
return role;
|
||||
}
|
||||
|
||||
public void setRole(String role) {
|
||||
this.role = role;
|
||||
}
|
||||
|
||||
public boolean isOwner() {
|
||||
return "owner".equals(role);
|
||||
}
|
||||
|
||||
public boolean isClient() {
|
||||
return "client".equals(role);
|
||||
}
|
||||
}
|
75
backend/src/main/java/com/hackathon/backend/model/User.java
Normal file
75
backend/src/main/java/com/hackathon/backend/model/User.java
Normal file
|
@ -0,0 +1,75 @@
|
|||
package com.hackathon.backend.model;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
public class User {
|
||||
private String id;
|
||||
private String username;
|
||||
private String password; // This would be hashed in a real application
|
||||
private String email;
|
||||
private LocalDateTime createdAt;
|
||||
private boolean isActive;
|
||||
|
||||
public User() {
|
||||
this.id = UUID.randomUUID().toString();
|
||||
this.createdAt = LocalDateTime.now();
|
||||
this.isActive = true;
|
||||
}
|
||||
|
||||
public User(String username, String password, String email) {
|
||||
this();
|
||||
this.username = username;
|
||||
this.password = password;
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
// Getters and Setters
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public LocalDateTime getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(LocalDateTime createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
public boolean isActive() {
|
||||
return isActive;
|
||||
}
|
||||
|
||||
public void setActive(boolean active) {
|
||||
isActive = active;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
package com.hackathon.backend.model;
|
||||
|
||||
public enum VoteType {
|
||||
UPVOTE,
|
||||
DOWNVOTE
|
||||
}
|
|
@ -0,0 +1,74 @@
|
|||
package com.hackathon.backend.service;
|
||||
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
@Service
|
||||
public class JwtService {
|
||||
|
||||
private static final String SECRET_KEY = "404E635266556A586E3272357538782F413F4428472B4B6250645367566B5970";
|
||||
private static final long JWT_EXPIRATION = 24 * 60 * 60 * 1000; // 24 hours
|
||||
|
||||
public String extractUserId(String token) {
|
||||
return extractClaim(token, Claims::getSubject);
|
||||
}
|
||||
|
||||
public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
|
||||
final Claims claims = extractAllClaims(token);
|
||||
return claimsResolver.apply(claims);
|
||||
}
|
||||
|
||||
public String generateToken(String userId, String username) {
|
||||
Map<String, Object> claims = new HashMap<>();
|
||||
claims.put("username", username);
|
||||
return createToken(claims, userId);
|
||||
}
|
||||
|
||||
private String createToken(Map<String, Object> extraClaims, String userId) {
|
||||
return Jwts.builder()
|
||||
.claims(extraClaims)
|
||||
.subject(userId)
|
||||
.issuedAt(new Date(System.currentTimeMillis()))
|
||||
.expiration(new Date(System.currentTimeMillis() + JWT_EXPIRATION))
|
||||
.signWith(getSignInKey())
|
||||
.compact();
|
||||
}
|
||||
|
||||
public boolean isTokenValid(String token, String userId) {
|
||||
final String extractedUserId = extractUserId(token);
|
||||
return (extractedUserId.equals(userId)) && !isTokenExpired(token);
|
||||
}
|
||||
|
||||
private boolean isTokenExpired(String token) {
|
||||
return extractExpiration(token).before(new Date());
|
||||
}
|
||||
|
||||
private Date extractExpiration(String token) {
|
||||
return extractClaim(token, Claims::getExpiration);
|
||||
}
|
||||
|
||||
private Claims extractAllClaims(String token) {
|
||||
return Jwts.parser()
|
||||
.verifyWith(getSignInKey())
|
||||
.build()
|
||||
.parseSignedClaims(token)
|
||||
.getPayload();
|
||||
}
|
||||
|
||||
private SecretKey getSignInKey() {
|
||||
byte[] keyBytes = SECRET_KEY.getBytes();
|
||||
return Keys.hmacShaKeyFor(keyBytes);
|
||||
}
|
||||
|
||||
public long getExpirationTime() {
|
||||
return JWT_EXPIRATION;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,207 @@
|
|||
package com.hackathon.backend.service;
|
||||
|
||||
import com.hackathon.backend.model.RadioStation;
|
||||
import com.hackathon.backend.model.Song;
|
||||
import com.hackathon.backend.model.Client;
|
||||
import com.hackathon.backend.model.VoteType;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
public class RadioStationService {
|
||||
|
||||
private final Map<String, RadioStation> radioStations = new HashMap<>();
|
||||
private final Map<String, Client> clients = new HashMap<>();
|
||||
|
||||
// Radio Station Management
|
||||
public RadioStation createRadioStation(String name, String description, String ownerId) {
|
||||
RadioStation station = new RadioStation(name, description, ownerId);
|
||||
radioStations.put(station.getId(), station);
|
||||
return station;
|
||||
}
|
||||
|
||||
public Optional<RadioStation> getRadioStation(String stationId) {
|
||||
return Optional.ofNullable(radioStations.get(stationId));
|
||||
}
|
||||
|
||||
public Optional<RadioStation> getRadioStationByJoinCode(String joinCode) {
|
||||
return radioStations.values().stream()
|
||||
.filter(station -> station.getJoinCode().equals(joinCode) && station.isActive())
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
public List<RadioStation> getAllRadioStations() {
|
||||
return new ArrayList<>(radioStations.values());
|
||||
}
|
||||
|
||||
public List<RadioStation> getActiveRadioStations() {
|
||||
return radioStations.values().stream()
|
||||
.filter(RadioStation::isActive)
|
||||
.toList();
|
||||
}
|
||||
|
||||
public Optional<RadioStation> updateRadioStation(String stationId, String name, String description) {
|
||||
RadioStation station = radioStations.get(stationId);
|
||||
if (station != null) {
|
||||
if (name != null)
|
||||
station.setName(name);
|
||||
if (description != null)
|
||||
station.setDescription(description);
|
||||
return Optional.of(station);
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
public boolean deleteRadioStation(String stationId) {
|
||||
RadioStation station = radioStations.get(stationId);
|
||||
if (station != null) {
|
||||
station.setActive(false);
|
||||
// Disconnect all clients
|
||||
station.getConnectedClients().clear();
|
||||
// Remove from clients map
|
||||
clients.entrySet().removeIf(entry -> stationId.equals(entry.getValue().getRadioStationId()));
|
||||
radioStations.remove(stationId);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Client Management
|
||||
public Optional<Client> connectClient(String username, String radioStationId, String joinCode) {
|
||||
RadioStation station = radioStations.get(radioStationId);
|
||||
if (station != null && station.isActive() && station.getJoinCode().equals(joinCode)) {
|
||||
Client client = new Client(username, radioStationId);
|
||||
clients.put(client.getId(), client);
|
||||
station.getConnectedClients().add(client.getId());
|
||||
return Optional.of(client);
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
public Optional<Client> connectClientByJoinCode(String username, String joinCode) {
|
||||
Optional<RadioStation> stationOpt = getRadioStationByJoinCode(joinCode);
|
||||
if (stationOpt.isPresent()) {
|
||||
RadioStation station = stationOpt.get();
|
||||
Client client = new Client(username, station.getId());
|
||||
clients.put(client.getId(), client);
|
||||
station.getConnectedClients().add(client.getId());
|
||||
return Optional.of(client);
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
public boolean disconnectClient(String clientId) {
|
||||
Client client = clients.get(clientId);
|
||||
if (client != null) {
|
||||
RadioStation station = radioStations.get(client.getRadioStationId());
|
||||
if (station != null) {
|
||||
station.getConnectedClients().remove(clientId);
|
||||
// Remove votes from all songs
|
||||
station.getSongQueue().forEach(song -> song.removeVote(clientId));
|
||||
}
|
||||
clients.remove(clientId);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public Optional<Client> getClient(String clientId) {
|
||||
return Optional.ofNullable(clients.get(clientId));
|
||||
}
|
||||
|
||||
public List<Client> getConnectedClients(String radioStationId) {
|
||||
RadioStation station = radioStations.get(radioStationId);
|
||||
if (station != null) {
|
||||
return station.getConnectedClients().stream()
|
||||
.map(clients::get)
|
||||
.filter(client -> client != null)
|
||||
.toList();
|
||||
}
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
// Song Management
|
||||
public Optional<Song> addSongToQueue(String radioStationId, String title, String artist,
|
||||
String album, int duration, String url, String addedBy) {
|
||||
RadioStation station = radioStations.get(radioStationId);
|
||||
if (station != null && station.isActive()) {
|
||||
Song song = new Song(title, artist, album, duration, url, addedBy);
|
||||
station.getSongQueue().add(song);
|
||||
return Optional.of(song);
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
public Optional<Song> voteSong(String radioStationId, String songId, String userId, VoteType voteType) {
|
||||
RadioStation station = radioStations.get(radioStationId);
|
||||
if (station != null) {
|
||||
Optional<Song> songOpt = station.getSongQueue().stream()
|
||||
.filter(song -> song.getId().equals(songId))
|
||||
.findFirst();
|
||||
|
||||
if (songOpt.isPresent()) {
|
||||
Song song = songOpt.get();
|
||||
song.addVote(userId, voteType);
|
||||
return Optional.of(song);
|
||||
}
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
public boolean removeSongVote(String radioStationId, String songId, String userId) {
|
||||
RadioStation station = radioStations.get(radioStationId);
|
||||
if (station != null) {
|
||||
Optional<Song> songOpt = station.getSongQueue().stream()
|
||||
.filter(song -> song.getId().equals(songId))
|
||||
.findFirst();
|
||||
|
||||
if (songOpt.isPresent()) {
|
||||
Song song = songOpt.get();
|
||||
song.removeVote(userId);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public List<Song> getSongQueue(String radioStationId) {
|
||||
RadioStation station = radioStations.get(radioStationId);
|
||||
if (station != null) {
|
||||
// Sort by score (upvotes - downvotes) descending
|
||||
return station.getSongQueue().stream()
|
||||
.sorted((s1, s2) -> Integer.compare(s2.getScore(), s1.getScore()))
|
||||
.toList();
|
||||
}
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
public Optional<Song> getCurrentlyPlaying(String radioStationId) {
|
||||
RadioStation station = radioStations.get(radioStationId);
|
||||
if (station != null) {
|
||||
return Optional.ofNullable(station.getCurrentlyPlaying());
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
public Optional<Song> playNextSong(String radioStationId) {
|
||||
RadioStation station = radioStations.get(radioStationId);
|
||||
if (station != null && !station.getSongQueue().isEmpty()) {
|
||||
// Get the song with highest score
|
||||
Song nextSong = station.getSongQueue().stream()
|
||||
.max((s1, s2) -> Integer.compare(s1.getScore(), s2.getScore()))
|
||||
.orElse(null);
|
||||
|
||||
if (nextSong != null) {
|
||||
station.getSongQueue().remove(nextSong);
|
||||
station.setCurrentlyPlaying(nextSong);
|
||||
return Optional.of(nextSong);
|
||||
}
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,85 @@
|
|||
package com.hackathon.backend.service;
|
||||
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Function;
|
||||
|
||||
@Service
|
||||
public class SimpleTokenService {
|
||||
|
||||
private static final String SECRET_KEY = "404E635266556A586E3272357538782F413F4428472B4B6250645367566B5970";
|
||||
private static final long TOKEN_EXPIRATION = 7 * 24 * 60 * 60 * 1000; // 7 days
|
||||
|
||||
public String generateToken(String username, String role) {
|
||||
String userId = UUID.randomUUID().toString();
|
||||
Map<String, Object> claims = new HashMap<>();
|
||||
claims.put("username", username);
|
||||
claims.put("role", role); // "owner" or "client"
|
||||
|
||||
return Jwts.builder()
|
||||
.claims(claims)
|
||||
.subject(userId)
|
||||
.issuedAt(new Date(System.currentTimeMillis()))
|
||||
.expiration(new Date(System.currentTimeMillis() + TOKEN_EXPIRATION))
|
||||
.signWith(getSignInKey())
|
||||
.compact();
|
||||
}
|
||||
|
||||
public String extractUserId(String token) {
|
||||
return extractClaim(token, Claims::getSubject);
|
||||
}
|
||||
|
||||
public String extractUsername(String token) {
|
||||
return extractClaim(token, claims -> claims.get("username", String.class));
|
||||
}
|
||||
|
||||
public String extractRole(String token) {
|
||||
return extractClaim(token, claims -> claims.get("role", String.class));
|
||||
}
|
||||
|
||||
public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
|
||||
final Claims claims = extractAllClaims(token);
|
||||
return claimsResolver.apply(claims);
|
||||
}
|
||||
|
||||
public boolean isTokenValid(String token) {
|
||||
try {
|
||||
return !isTokenExpired(token);
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isTokenExpired(String token) {
|
||||
return extractExpiration(token).before(new Date());
|
||||
}
|
||||
|
||||
private Date extractExpiration(String token) {
|
||||
return extractClaim(token, Claims::getExpiration);
|
||||
}
|
||||
|
||||
private Claims extractAllClaims(String token) {
|
||||
return Jwts.parser()
|
||||
.verifyWith(getSignInKey())
|
||||
.build()
|
||||
.parseSignedClaims(token)
|
||||
.getPayload();
|
||||
}
|
||||
|
||||
private SecretKey getSignInKey() {
|
||||
byte[] keyBytes = SECRET_KEY.getBytes();
|
||||
return Keys.hmacShaKeyFor(keyBytes);
|
||||
}
|
||||
|
||||
public long getExpirationTime() {
|
||||
return TOKEN_EXPIRATION;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,60 @@
|
|||
package com.hackathon.backend.service;
|
||||
|
||||
import com.hackathon.backend.model.User;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
public class UserService {
|
||||
|
||||
private final Map<String, User> users = new HashMap<>();
|
||||
private final Map<String, String> usersByUsername = new HashMap<>();
|
||||
|
||||
@Autowired
|
||||
private PasswordEncoder passwordEncoder;
|
||||
|
||||
public Optional<User> registerUser(String username, String password, String email) {
|
||||
// Check if username already exists
|
||||
if (usersByUsername.containsKey(username)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
// Hash the password
|
||||
String hashedPassword = passwordEncoder.encode(password);
|
||||
User user = new User(username, hashedPassword, email);
|
||||
users.put(user.getId(), user);
|
||||
usersByUsername.put(username, user.getId());
|
||||
|
||||
return Optional.of(user);
|
||||
}
|
||||
|
||||
public Optional<User> authenticateUser(String username, String password) {
|
||||
String userId = usersByUsername.get(username);
|
||||
if (userId != null) {
|
||||
User user = users.get(userId);
|
||||
// Compare hashed passwords
|
||||
if (user != null && passwordEncoder.matches(password, user.getPassword()) && user.isActive()) {
|
||||
return Optional.of(user);
|
||||
}
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
public Optional<User> getUserById(String userId) {
|
||||
return Optional.ofNullable(users.get(userId));
|
||||
}
|
||||
|
||||
public Optional<User> getUserByUsername(String username) {
|
||||
String userId = usersByUsername.get(username);
|
||||
return userId != null ? Optional.ofNullable(users.get(userId)) : Optional.empty();
|
||||
}
|
||||
|
||||
public boolean userExists(String username) {
|
||||
return usersByUsername.containsKey(username);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.hackathon.backend.util;
|
||||
|
||||
import com.hackathon.backend.model.TokenUser;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
public class AuthUtil {
|
||||
|
||||
public static TokenUser getCurrentUser() {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null && authentication.getPrincipal() instanceof TokenUser) {
|
||||
return (TokenUser) authentication.getPrincipal();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static String getCurrentUserId() {
|
||||
TokenUser user = getCurrentUser();
|
||||
return user != null ? user.getUserId() : null;
|
||||
}
|
||||
|
||||
public static String getCurrentUsername() {
|
||||
TokenUser user = getCurrentUser();
|
||||
return user != null ? user.getUsername() : null;
|
||||
}
|
||||
|
||||
public static boolean isCurrentUserOwner(String ownerId) {
|
||||
String currentUserId = getCurrentUserId();
|
||||
return currentUserId != null && currentUserId.equals(ownerId);
|
||||
}
|
||||
|
||||
public static boolean hasOwnerRole() {
|
||||
TokenUser user = getCurrentUser();
|
||||
return user != null && user.isOwner();
|
||||
}
|
||||
}
|
8
backend/src/main/resources/application.properties
Normal file
8
backend/src/main/resources/application.properties
Normal file
|
@ -0,0 +1,8 @@
|
|||
spring.application.name=backend
|
||||
server.port=8080
|
||||
|
||||
# CORS Configuration
|
||||
spring.web.cors.allowed-origins=*
|
||||
spring.web.cors.allowed-methods=GET,POST,PUT,DELETE,OPTIONS
|
||||
spring.web.cors.allowed-headers=*
|
||||
spring.web.cors.max-age=3600
|
|
@ -0,0 +1,13 @@
|
|||
package com.hackathon.backend;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest
|
||||
class BackendApplicationTests {
|
||||
|
||||
@Test
|
||||
void contextLoads() {
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,154 @@
|
|||
package com.hackathon.backend.service;
|
||||
|
||||
import com.hackathon.backend.model.RadioStation;
|
||||
import com.hackathon.backend.model.Client;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class RadioStationServiceTest {
|
||||
|
||||
private RadioStationService radioStationService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
radioStationService = new RadioStationService();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should create radio station with join code")
|
||||
void shouldCreateRadioStationWithJoinCode() {
|
||||
// Given
|
||||
String name = "Test Station";
|
||||
String description = "Test Description";
|
||||
String ownerId = "owner123";
|
||||
|
||||
// When
|
||||
RadioStation station = radioStationService.createRadioStation(name, description, ownerId);
|
||||
|
||||
// Then
|
||||
assertNotNull(station);
|
||||
assertNotNull(station.getId());
|
||||
assertNotNull(station.getJoinCode());
|
||||
assertEquals(6, station.getJoinCode().length());
|
||||
assertEquals(name, station.getName());
|
||||
assertEquals(description, station.getDescription());
|
||||
assertEquals(ownerId, station.getOwnerId());
|
||||
assertTrue(station.isActive());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should find radio station by join code")
|
||||
void shouldFindRadioStationByJoinCode() {
|
||||
// Given
|
||||
RadioStation station = radioStationService.createRadioStation("Test Station", "Description", "owner123");
|
||||
String joinCode = station.getJoinCode();
|
||||
|
||||
// When
|
||||
Optional<RadioStation> foundStation = radioStationService.getRadioStationByJoinCode(joinCode);
|
||||
|
||||
// Then
|
||||
assertTrue(foundStation.isPresent());
|
||||
assertEquals(station.getId(), foundStation.get().getId());
|
||||
assertEquals(joinCode, foundStation.get().getJoinCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should not find radio station with invalid join code")
|
||||
void shouldNotFindRadioStationWithInvalidJoinCode() {
|
||||
// Given
|
||||
radioStationService.createRadioStation("Test Station", "Description", "owner123");
|
||||
String invalidJoinCode = "INVALID";
|
||||
|
||||
// When
|
||||
Optional<RadioStation> foundStation = radioStationService.getRadioStationByJoinCode(invalidJoinCode);
|
||||
|
||||
// Then
|
||||
assertFalse(foundStation.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should connect client with valid join code")
|
||||
void shouldConnectClientWithValidJoinCode() {
|
||||
// Given
|
||||
RadioStation station = radioStationService.createRadioStation("Test Station", "Description", "owner123");
|
||||
String username = "testuser";
|
||||
String joinCode = station.getJoinCode();
|
||||
|
||||
// When
|
||||
Optional<Client> client = radioStationService.connectClient(username, station.getId(), joinCode);
|
||||
|
||||
// Then
|
||||
assertTrue(client.isPresent());
|
||||
assertEquals(username, client.get().getUsername());
|
||||
assertEquals(station.getId(), client.get().getRadioStationId());
|
||||
assertTrue(station.getConnectedClients().contains(client.get().getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should not connect client with invalid join code")
|
||||
void shouldNotConnectClientWithInvalidJoinCode() {
|
||||
// Given
|
||||
RadioStation station = radioStationService.createRadioStation("Test Station", "Description", "owner123");
|
||||
String username = "testuser";
|
||||
String invalidJoinCode = "WRONG1";
|
||||
|
||||
// When
|
||||
Optional<Client> client = radioStationService.connectClient(username, station.getId(), invalidJoinCode);
|
||||
|
||||
// Then
|
||||
assertFalse(client.isPresent());
|
||||
assertTrue(station.getConnectedClients().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should connect client using join code only")
|
||||
void shouldConnectClientUsingJoinCodeOnly() {
|
||||
// Given
|
||||
RadioStation station = radioStationService.createRadioStation("Test Station", "Description", "owner123");
|
||||
String username = "testuser";
|
||||
String joinCode = station.getJoinCode();
|
||||
|
||||
// When
|
||||
Optional<Client> client = radioStationService.connectClientByJoinCode(username, joinCode);
|
||||
|
||||
// Then
|
||||
assertTrue(client.isPresent());
|
||||
assertEquals(username, client.get().getUsername());
|
||||
assertEquals(station.getId(), client.get().getRadioStationId());
|
||||
assertTrue(station.getConnectedClients().contains(client.get().getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should not connect client to inactive radio station")
|
||||
void shouldNotConnectClientToInactiveRadioStation() {
|
||||
// Given
|
||||
RadioStation station = radioStationService.createRadioStation("Test Station", "Description", "owner123");
|
||||
station.setActive(false);
|
||||
String username = "testuser";
|
||||
String joinCode = station.getJoinCode();
|
||||
|
||||
// When
|
||||
Optional<Client> client = radioStationService.connectClient(username, station.getId(), joinCode);
|
||||
|
||||
// Then
|
||||
assertFalse(client.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should generate unique join codes for different stations")
|
||||
void shouldGenerateUniqueJoinCodesForDifferentStations() {
|
||||
// Given & When
|
||||
RadioStation station1 = radioStationService.createRadioStation("Station 1", "Desc 1", "owner1");
|
||||
RadioStation station2 = radioStationService.createRadioStation("Station 2", "Desc 2", "owner2");
|
||||
|
||||
// Then
|
||||
assertNotEquals(station1.getJoinCode(), station2.getJoinCode());
|
||||
assertEquals(6, station1.getJoinCode().length());
|
||||
assertEquals(6, station2.getJoinCode().length());
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue