add old files

This commit is contained in:
Lukas Weger 2025-08-01 17:37:41 +02:00
parent 53e4346d55
commit 19a40483aa
59 changed files with 20831 additions and 0 deletions

22
.gitignore vendored Normal file
View file

@ -0,0 +1,22 @@
frontend/node_modules
backend/gradle
**/build/
# Ignore Gradle GUI config
gradle-app.setting
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
!gradle-wrapper.jar
# Avoid ignore Gradle wrappper properties
!gradle-wrapper.properties
# Cache of project
.gradletasknamecache
# Eclipse Gradle plugin generated files
# Eclipse Core
.project
# JDT-specific (Eclipse Java Development Tools)
.classpath

220
API_DOCUMENTATION.md Normal file
View file

@ -0,0 +1,220 @@
# SERENA API
## Authentication
This system uses JWT-like tokens generated automatically during key actions:
- **Creating a radio station** generates an **owner token**.
- **Joining a radio station** generates a **client token**.
All subsequent requests require this token in the `Authorization` header:
```
Authorization: Bearer <token>
```
### Token Generation Endpoints
#### Create Radio Station → Owner Token
- **POST** `/api/radio-stations`
- **No authentication required**
- **Body**:
```json
{
"name": "My Radio Station",
"description": "A cool radio station"
}
```
**Response:**
```json
{
"success": true,
"message": "Radio station created successfully",
"data": {
"station": {
/* station object */
},
"ownerToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
}
```
#### Connect to Radio Station → Client Token
- **POST** `/api/clients/connect`
- **No authentication required**
- **Body Options**:
- With Station ID + Join Code
```json
{
"username": "john_doe",
"radioStationId": "station123",
"joinCode": "ABC123"
}
```
- With Join Code only
```json
{ "username": "john_doe", "joinCode": "ABC123" }
```
**Response:**
```json
{
"success": true,
"message": "Successfully connected to radio station",
"data": {
"client": {
/* client object */
},
"clientToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
}
```
---
## API Endpoints
### Radio Station Management
- **Create Station** `POST /api/radio-stations` (No auth; returns owner token)
- **Get All Stations** `GET /api/radio-stations` (Auth: owner or client)
- Optional query param: `activeOnly=true`
- **Get by ID** `GET /api/radio-stations/{stationId}` (Auth required)
- **Get by Join Code** `GET /api/radio-stations/join/{joinCode}` (Public)
- **Update Station** `PUT /api/radio-stations/{stationId}` (Owner only)
- **Delete Station** `DELETE /api/radio-stations/{stationId}` (Owner only)
### Client Management
- **Connect Client** `POST /api/clients/connect` (No auth; returns client token)
- **Disconnect Client** `DELETE /api/clients/{clientId}/disconnect` (Owner only)
- **Get Client Info** `GET /api/clients/{clientId}` (Auth required)
- **Get Station Clients** `GET /api/clients/station/{radioStationId}` (Auth required)
### Song Management
> All endpoints require a valid **owner** or **client** token unless specified.
- **Add Song** `POST /api/radio-stations/{stationId}/songs`
- **Get Queue** `GET /api/radio-stations/{stationId}/songs/queue`
- **Get Current Song** `GET /api/radio-stations/{stationId}/songs/current`
- **Play Next Song** `POST /api/radio-stations/{stationId}/songs/next` (Owner only)
- **Vote on Song** `POST /api/radio-stations/{stationId}/songs/{songId}/vote`
```json
{ "voteType": "UPVOTE" }
```
`voteType` can be `"UPVOTE"` or `"DOWNVOTE"`.
- **Remove Vote** `DELETE /api/radio-stations/{stationId}/songs/{songId}/vote`
---
## Models
### RadioStation
- `id`, `name`, `description`, `ownerId`, `joinCode`, `createdAt`, `isActive`, `connectedClients`, `songQueue`, `currentlyPlaying`
### Song
- `id`, `title`, `artist`, `album`, `duration`, `url`, `addedBy`, `addedAt`, `votes`, `upvotes`, `downvotes`
### Client
- `id`, `username`, `radioStationId`, `connectedAt`, `isActive`
---
## Authentication & Authorization
- **Public**: Join stations via join code, connect clients.
- **Authenticated User**: Add/vote on songs, view stations, connect to stations.
- **Station Owner**: Manage station (update/delete), control playback, disconnect clients.
---
## Features
- JWT-based authentication for most operations.
- Join codebased client connection.
- Owner-only management (updates, deletes, playback).
- Song queue sorted by votes.
- Full CORS support.
---
## Example Flow
1. User registers/logs in → gets JWT.
2. Owner creates station → gets join code + owner token.
3. Clients join via join code → get client token.
4. Authenticated users add/vote on songs.
5. Owner controls playback & manages station.
---
## Running the Application
```bash
cd backend
./gradlew bootRun
```
Server runs on port `8080`.
### Quick Auth Test
```bash
curl -X POST http://localhost:8080/api/auth/register -H "Content-Type: application/json" -d '{"username":"testuser","password":"password123","email":"test@example.com"}'
curl -X POST http://localhost:8080/api/auth/login -H "Content-Type: application/json" -d '{"username":"testuser","password":"password123"}'
curl -X GET http://localhost:8080/api/radio-stations -H "Authorization: Bearer <token>"
```
---
### **SERENA API Endpoint Table**
| Method | Endpoint | Description | Auth Required | Notes |
| ---------- | ------------------------------------- | ------------------------ | ------------- | -------------------------- |
| **POST** | `/api/radio-stations` | Create a radio station | ❌ | Returns **owner token** |
| **GET** | `/api/radio-stations` | Get all stations | ✅ | `activeOnly=true` optional |
| **GET** | `/api/radio-stations/{stationId}` | Get station by ID | ✅ | — |
| **GET** | `/api/radio-stations/join/{joinCode}` | Get station by join code | ❌ | Public lookup |
| **PUT** | `/api/radio-stations/{stationId}` | Update station | ✅ (Owner) | Owner only |
| **DELETE** | `/api/radio-stations/{stationId}` | Delete station | ✅ (Owner) | Owner only |
#### 👥 **Client Management**
| Method | Endpoint | Description | Auth Required | Notes |
| ---------- | --------------------------------------- | -------------------------- | ------------- | ------------------------ |
| **POST** | `/api/clients/connect` | Connect to station | ❌ | Returns **client token** |
| **DELETE** | `/api/clients/{clientId}/disconnect` | Disconnect client | ✅ (Owner) | Owner only |
| **GET** | `/api/clients/{clientId}` | Get client info | ✅ | — |
| **GET** | `/api/clients/station/{radioStationId}` | Get all clients in station | ✅ | — |
#### 🎵 **Song Management**
| Method | Endpoint | Description | Auth Required | Notes |
| ---------- | ----------------------------------------------------- | -------------------------- | ------------- | --------------------------- |
| **POST** | `/api/radio-stations/{stationId}/songs` | Add song to queue | ✅ | Client or Owner |
| **GET** | `/api/radio-stations/{stationId}/songs/queue` | Get song queue | ✅ | Sorted by votes |
| **GET** | `/api/radio-stations/{stationId}/songs/current` | Get currently playing song | ✅ | — |
| **POST** | `/api/radio-stations/{stationId}/songs/next` | Play next song | ✅ (Owner) | Moves top song to “current” |
| **POST** | `/api/radio-stations/{stationId}/songs/{songId}/vote` | Vote on song | ✅ | `voteType`: UPVOTE/DOWNVOTE |
| **DELETE** | `/api/radio-stations/{stationId}/songs/{songId}/vote` | Remove vote | ✅ | Removes users vote |
---

0
Dockerfile Normal file
View file

3
backend/.gitattributes vendored Normal file
View file

@ -0,0 +1,3 @@
/gradlew text eol=lf
*.bat text eol=crlf
*.jar binary

37
backend/.gitignore vendored Normal file
View 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
View 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
View 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
View 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
View file

@ -0,0 +1 @@
rootProject.name = 'backend'

View file

@ -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);
}
}

View file

@ -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);
}
}

View file

@ -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;
}
}

View file

@ -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);
}
}

View file

@ -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"));
}
}
}

View file

@ -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));
}
}

View file

@ -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"));
}
}
}

View file

@ -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"));
}
}
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View 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;
}
}

View file

@ -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);
}
}

View 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;
}
}

View file

@ -0,0 +1,6 @@
package com.hackathon.backend.model;
public enum VoteType {
UPVOTE,
DOWNVOTE
}

View file

@ -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;
}
}

View file

@ -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();
}
}

View file

@ -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;
}
}

View file

@ -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);
}
}

View file

@ -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();
}
}

View 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

View file

@ -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() {
}
}

View file

@ -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());
}
}

0
docker-compose.yml Normal file
View file

23
frontend/.gitignore vendored Normal file
View file

@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

70
frontend/README.md Normal file
View file

@ -0,0 +1,70 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
The page will reload when you make changes.\
You may also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you can't go back!**
If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
### Analyzing the Bundle Size
This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
### Making a Progressive Web App
This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
### Advanced Configuration
This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
### Deployment
This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
### `npm run build` fails to minify
This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)

17536
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

39
frontend/package.json Normal file
View file

@ -0,0 +1,39 @@
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/dom": "^10.4.1",
"@testing-library/jest-dom": "^6.6.4",
"@testing-library/react": "^16.3.0",
"@testing-library/user-event": "^13.5.0",
"react": "^19.1.1",
"react-dom": "^19.1.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

BIN
frontend/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

View file

@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

BIN
frontend/public/logo192.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

BIN
frontend/public/logo512.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

View file

@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View file

@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

38
frontend/src/App.css Normal file
View file

@ -0,0 +1,38 @@
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

25
frontend/src/App.js Normal file
View file

@ -0,0 +1,25 @@
import logo from './logo.svg';
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;

8
frontend/src/App.test.js Normal file
View file

@ -0,0 +1,8 @@
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});

13
frontend/src/index.css Normal file
View file

@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}

17
frontend/src/index.js Normal file
View file

@ -0,0 +1,17 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

1
frontend/src/logo.svg Normal file
View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3"><g fill="#61DAFB"><path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/><circle cx="420.9" cy="296.5" r="45.7"/><path d="M520.5 78.1z"/></g></svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

View file

@ -0,0 +1,13 @@
const reportWebVitals = onPerfEntry => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;

View file

@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';