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