feat: implement authentication with JWT and user management
This commit is contained in:
parent
c4c762cafe
commit
35d8fbaea0
42 changed files with 989 additions and 397 deletions
|
@ -51,6 +51,9 @@ dependencies {
|
|||
implementation("org.springframework.boot:spring-boot-starter-oauth2-client:3.4.5")
|
||||
runtimeOnly("org.postgresql:postgresql")
|
||||
implementation("org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.8")
|
||||
implementation("io.jsonwebtoken:jjwt-api:0.11.5")
|
||||
runtimeOnly("io.jsonwebtoken:jjwt-impl:0.11.5")
|
||||
runtimeOnly("io.jsonwebtoken:jjwt-jackson:0.11.5")
|
||||
}
|
||||
|
||||
tasks.withType<Test> {
|
||||
|
|
|
@ -30,10 +30,10 @@ public class BlackJackGameController {
|
|||
|
||||
@GetMapping("/blackjack/{id}")
|
||||
public ResponseEntity<Object> getGame(@PathVariable Long id, @RequestHeader("Authorization") String token) {
|
||||
Optional<UserEntity> optionalUser = userService.getCurrentUser(token);
|
||||
Optional<UserEntity> optionalUser = userService.getCurrentUser();
|
||||
|
||||
if (optionalUser.isEmpty()) {
|
||||
throw new UserNotFoundException();
|
||||
throw new UserNotFoundException("User not found");
|
||||
}
|
||||
|
||||
UserEntity user = optionalUser.get();
|
||||
|
@ -47,10 +47,10 @@ public class BlackJackGameController {
|
|||
|
||||
@PostMapping("/blackjack/{id}/hit")
|
||||
public ResponseEntity<Object> hit(@PathVariable Long id, @RequestHeader("Authorization") String token) {
|
||||
Optional<UserEntity> optionalUser = userService.getCurrentUser(token);
|
||||
Optional<UserEntity> optionalUser = userService.getCurrentUser();
|
||||
|
||||
if (optionalUser.isEmpty()) {
|
||||
throw new UserNotFoundException();
|
||||
throw new UserNotFoundException("User not found");
|
||||
}
|
||||
|
||||
UserEntity user = optionalUser.get();
|
||||
|
@ -64,10 +64,10 @@ public class BlackJackGameController {
|
|||
|
||||
@PostMapping("/blackjack/{id}/stand")
|
||||
public ResponseEntity<Object> stand(@PathVariable Long id, @RequestHeader("Authorization") String token) {
|
||||
Optional<UserEntity> optionalUser = userService.getCurrentUser(token);
|
||||
Optional<UserEntity> optionalUser = userService.getCurrentUser();
|
||||
|
||||
if (optionalUser.isEmpty()) {
|
||||
throw new UserNotFoundException();
|
||||
throw new UserNotFoundException("User not found");
|
||||
}
|
||||
|
||||
UserEntity user = optionalUser.get();
|
||||
|
@ -81,10 +81,10 @@ public class BlackJackGameController {
|
|||
|
||||
@PostMapping("/blackjack/{id}/doubleDown")
|
||||
public ResponseEntity<Object> doubleDown(@PathVariable Long id, @RequestHeader("Authorization") String token) {
|
||||
Optional<UserEntity> optionalUser = userService.getCurrentUser(token);
|
||||
Optional<UserEntity> optionalUser = userService.getCurrentUser();
|
||||
|
||||
if (optionalUser.isEmpty()) {
|
||||
throw new UserNotFoundException();
|
||||
throw new UserNotFoundException("User not found");
|
||||
}
|
||||
|
||||
UserEntity user = optionalUser.get();
|
||||
|
@ -98,10 +98,10 @@ public class BlackJackGameController {
|
|||
|
||||
@PostMapping("/blackjack/{id}/split")
|
||||
public ResponseEntity<Object> split(@PathVariable Long id, @RequestHeader("Authorization") String token) {
|
||||
Optional<UserEntity> optionalUser = userService.getCurrentUser(token);
|
||||
Optional<UserEntity> optionalUser = userService.getCurrentUser();
|
||||
|
||||
if (optionalUser.isEmpty()) {
|
||||
throw new UserNotFoundException();
|
||||
throw new UserNotFoundException("User not found");
|
||||
}
|
||||
|
||||
UserEntity user = optionalUser.get();
|
||||
|
@ -115,10 +115,10 @@ public class BlackJackGameController {
|
|||
|
||||
@PostMapping("/blackjack/start")
|
||||
public ResponseEntity<Object> createBlackJackGame(@RequestBody @Valid BetDto betDto, @RequestHeader("Authorization") String token) {
|
||||
Optional<UserEntity> optionalUser = userService.getCurrentUser(token);
|
||||
Optional<UserEntity> optionalUser = userService.getCurrentUser();
|
||||
|
||||
if (optionalUser.isEmpty()) {
|
||||
throw new UserNotFoundException();
|
||||
throw new UserNotFoundException("User not found");
|
||||
}
|
||||
|
||||
UserEntity user = optionalUser.get();
|
||||
|
|
30
backend/src/main/java/de/szut/casino/config/WebConfig.java
Normal file
30
backend/src/main/java/de/szut/casino/config/WebConfig.java
Normal file
|
@ -0,0 +1,30 @@
|
|||
package de.szut.casino.config;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
public class WebConfig {
|
||||
|
||||
@Value("${app.frontend-host}")
|
||||
private String frontendHost;
|
||||
|
||||
@Bean
|
||||
public WebMvcConfigurer corsConfigurer() {
|
||||
return new WebMvcConfigurer() {
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/**")
|
||||
.allowedOrigins(frontendHost)
|
||||
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
|
||||
.allowedHeaders("*")
|
||||
.exposedHeaders("*")
|
||||
.allowCredentials(true)
|
||||
.maxAge(3600);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
|
@ -50,7 +50,7 @@ public class DepositController {
|
|||
Stripe.apiKey = stripeKey;
|
||||
|
||||
KeycloakUserDto userData = getAuthentikUserInfo(token);
|
||||
Optional<UserEntity> optionalUserEntity = this.userRepository.findOneByAuthentikId(userData.getSub());
|
||||
Optional<UserEntity> optionalUserEntity = this.userRepository.findByEmail(userData.getSub());
|
||||
|
||||
SessionCreateParams params = SessionCreateParams.builder()
|
||||
.addLineItem(SessionCreateParams.LineItem.builder()
|
||||
|
|
|
@ -5,7 +5,7 @@ import org.springframework.web.bind.annotation.ResponseStatus;
|
|||
|
||||
@ResponseStatus(value = HttpStatus.NOT_FOUND)
|
||||
public class UserNotFoundException extends RuntimeException {
|
||||
public UserNotFoundException() {
|
||||
super("user not found");
|
||||
public UserNotFoundException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -37,9 +37,9 @@ public class LootBoxController {
|
|||
|
||||
LootBoxEntity lootBox = optionalLootBox.get();
|
||||
|
||||
Optional<UserEntity> optionalUser = userService.getCurrentUser(token);
|
||||
Optional<UserEntity> optionalUser = userService.getCurrentUser();
|
||||
if (optionalUser.isEmpty()) {
|
||||
throw new UserNotFoundException();
|
||||
throw new UserNotFoundException("User not found");
|
||||
}
|
||||
|
||||
UserEntity user = optionalUser.get();
|
||||
|
|
|
@ -0,0 +1,31 @@
|
|||
package de.szut.casino.security;
|
||||
|
||||
import de.szut.casino.security.dto.AuthResponseDto;
|
||||
import de.szut.casino.security.dto.LoginRequestDto;
|
||||
import de.szut.casino.security.service.AuthService;
|
||||
import de.szut.casino.user.dto.CreateUserDto;
|
||||
import de.szut.casino.user.dto.GetUserDto;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/auth")
|
||||
public class AuthController {
|
||||
|
||||
@Autowired
|
||||
private AuthService authService;
|
||||
|
||||
@PostMapping("/login")
|
||||
public ResponseEntity<AuthResponseDto> authenticateUser(@Valid @RequestBody LoginRequestDto loginRequest) {
|
||||
AuthResponseDto response = authService.login(loginRequest);
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
|
||||
@PostMapping("/register")
|
||||
public ResponseEntity<GetUserDto> registerUser(@Valid @RequestBody CreateUserDto signUpRequest) {
|
||||
GetUserDto response = authService.register(signUpRequest);
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
package de.szut.casino.security;
|
||||
|
||||
import jakarta.servlet.*;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@Component
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||
public class CorsFilter implements Filter {
|
||||
|
||||
@Value("${app.frontend-host}")
|
||||
private String frontendHost;
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
|
||||
throws IOException, ServletException {
|
||||
|
||||
HttpServletResponse response = (HttpServletResponse) res;
|
||||
HttpServletRequest request = (HttpServletRequest) req;
|
||||
|
||||
// Allow requests from the frontend
|
||||
response.setHeader("Access-Control-Allow-Origin", frontendHost);
|
||||
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS");
|
||||
response.setHeader("Access-Control-Allow-Headers", "*");
|
||||
response.setHeader("Access-Control-Expose-Headers", "*");
|
||||
response.setHeader("Access-Control-Allow-Credentials", "true");
|
||||
response.setHeader("Access-Control-Max-Age", "3600");
|
||||
|
||||
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
|
||||
response.setStatus(HttpServletResponse.SC_OK);
|
||||
return;
|
||||
}
|
||||
|
||||
chain.doFilter(req, res);
|
||||
}
|
||||
}
|
|
@ -1,12 +1,22 @@
|
|||
package de.szut.casino.security;
|
||||
|
||||
import de.szut.casino.security.jwt.JwtAuthenticationFilter;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.Customizer;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
|
||||
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||
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.core.userdetails.UserDetailsService;
|
||||
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;
|
||||
|
@ -16,23 +26,51 @@ import java.util.List;
|
|||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@EnableMethodSecurity
|
||||
public class SecurityConfig {
|
||||
|
||||
@Value("${app.frontend-host}")
|
||||
private String frontendHost;
|
||||
|
||||
@Autowired
|
||||
private UserDetailsService userDetailsService;
|
||||
|
||||
@Autowired
|
||||
private JwtAuthenticationFilter jwtAuthenticationFilter;
|
||||
|
||||
@Bean
|
||||
public DaoAuthenticationProvider authenticationProvider() {
|
||||
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
|
||||
|
||||
authProvider.setUserDetailsService(userDetailsService);
|
||||
authProvider.setPasswordEncoder(passwordEncoder());
|
||||
|
||||
return authProvider;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
|
||||
return authConfig.getAuthenticationManager();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.cors(Customizer.withDefaults())
|
||||
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
|
||||
.csrf(csrf -> csrf.disable())
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth -> {
|
||||
auth.requestMatchers("/webhook", "/swagger/**", "/swagger-ui/**", "/health").permitAll()
|
||||
auth.requestMatchers("/api/auth/**", "/webhook", "/swagger/**", "/swagger-ui/**", "/health", "/error").permitAll()
|
||||
.requestMatchers(org.springframework.http.HttpMethod.OPTIONS, "/**").permitAll()
|
||||
.anyRequest().authenticated();
|
||||
})
|
||||
.oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt ->
|
||||
jwt.jwtAuthenticationConverter(new CustomJwtAuthenticationConverter())
|
||||
));
|
||||
.authenticationProvider(authenticationProvider())
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
|
||||
return http.build();
|
||||
}
|
||||
|
@ -42,9 +80,10 @@ public class SecurityConfig {
|
|||
CorsConfiguration configuration = new CorsConfiguration();
|
||||
configuration.setAllowedOrigins(List.of(this.frontendHost));
|
||||
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
|
||||
configuration.setAllowedHeaders(Arrays.asList("authorization", "content-type", "x-auth-token", "Access-Control-Allow-Origin"));
|
||||
configuration.setExposedHeaders(List.of("x-auth-token"));
|
||||
configuration.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type", "Accept", "Origin", "X-Requested-With", "Access-Control-Request-Method", "Access-Control-Request-Headers", "x-auth-token"));
|
||||
configuration.setExposedHeaders(Arrays.asList("Authorization", "Content-Type", "x-auth-token", "Access-Control-Allow-Origin", "Access-Control-Allow-Methods", "Access-Control-Allow-Headers"));
|
||||
configuration.setAllowCredentials(true);
|
||||
configuration.setMaxAge(3600L);
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
source.registerCorsConfiguration("/**", configuration);
|
||||
return source;
|
||||
|
|
|
@ -0,0 +1,19 @@
|
|||
package de.szut.casino.security.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class AuthResponseDto {
|
||||
private String token;
|
||||
private String tokenType = "Bearer";
|
||||
|
||||
public AuthResponseDto(String token) {
|
||||
this.token = token;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package de.szut.casino.security.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class LoginRequestDto {
|
||||
@NotBlank(message = "Username or email is required")
|
||||
private String usernameOrEmail;
|
||||
|
||||
@NotBlank(message = "Password is required")
|
||||
private String password;
|
||||
}
|
|
@ -0,0 +1,64 @@
|
|||
package de.szut.casino.security.jwt;
|
||||
|
||||
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.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@Component
|
||||
public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
|
||||
@Autowired
|
||||
private JwtUtils jwtUtils;
|
||||
|
||||
@Autowired
|
||||
private UserDetailsService userDetailsService;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
try {
|
||||
String jwt = parseJwt(request);
|
||||
if (jwt != null) {
|
||||
String username = jwtUtils.extractUsername(jwt);
|
||||
|
||||
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
|
||||
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
|
||||
|
||||
if (jwtUtils.validateToken(jwt, userDetails)) {
|
||||
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
|
||||
userDetails, null, userDetails.getAuthorities());
|
||||
|
||||
authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
|
||||
SecurityContextHolder.getContext().setAuthentication(authToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("Cannot set user authentication: {}", e);
|
||||
}
|
||||
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
|
||||
private String parseJwt(HttpServletRequest request) {
|
||||
String headerAuth = request.getHeader("Authorization");
|
||||
|
||||
if (StringUtils.hasText(headerAuth) && headerAuth.startsWith("Bearer ")) {
|
||||
return headerAuth.substring(7);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,83 @@
|
|||
package de.szut.casino.security.jwt;
|
||||
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.security.Key;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
@Component
|
||||
public class JwtUtils {
|
||||
|
||||
@Value("${jwt.secret}")
|
||||
private String jwtSecret;
|
||||
|
||||
@Value("${jwt.expiration.ms}")
|
||||
private int jwtExpirationMs;
|
||||
|
||||
private Key getSigningKey() {
|
||||
return Keys.hmacShaKeyFor(jwtSecret.getBytes());
|
||||
}
|
||||
|
||||
public String generateToken(Authentication authentication) {
|
||||
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
|
||||
return generateToken(userDetails.getUsername());
|
||||
}
|
||||
|
||||
public String generateToken(String username) {
|
||||
Map<String, Object> claims = new HashMap<>();
|
||||
return createToken(claims, username);
|
||||
}
|
||||
|
||||
private String createToken(Map<String, Object> claims, String subject) {
|
||||
Date now = new Date();
|
||||
Date expiryDate = new Date(now.getTime() + jwtExpirationMs);
|
||||
|
||||
return Jwts.builder()
|
||||
.setClaims(claims)
|
||||
.setSubject(subject)
|
||||
.setIssuedAt(now)
|
||||
.setExpiration(expiryDate)
|
||||
.signWith(getSigningKey(), SignatureAlgorithm.HS256)
|
||||
.compact();
|
||||
}
|
||||
|
||||
public String extractUsername(String token) {
|
||||
return extractClaim(token, Claims::getSubject);
|
||||
}
|
||||
|
||||
public Date extractExpiration(String token) {
|
||||
return extractClaim(token, Claims::getExpiration);
|
||||
}
|
||||
|
||||
public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
|
||||
final Claims claims = extractAllClaims(token);
|
||||
return claimsResolver.apply(claims);
|
||||
}
|
||||
|
||||
private Claims extractAllClaims(String token) {
|
||||
return Jwts.parserBuilder()
|
||||
.setSigningKey(getSigningKey())
|
||||
.build()
|
||||
.parseClaimsJws(token)
|
||||
.getBody();
|
||||
}
|
||||
|
||||
private Boolean isTokenExpired(String token) {
|
||||
return extractExpiration(token).before(new Date());
|
||||
}
|
||||
|
||||
public Boolean validateToken(String token, UserDetails userDetails) {
|
||||
final String username = extractUsername(token);
|
||||
return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
package de.szut.casino.security.service;
|
||||
|
||||
import de.szut.casino.security.dto.AuthResponseDto;
|
||||
import de.szut.casino.security.dto.LoginRequestDto;
|
||||
import de.szut.casino.security.jwt.JwtUtils;
|
||||
import de.szut.casino.user.UserEntity;
|
||||
import de.szut.casino.user.UserService;
|
||||
import de.szut.casino.user.dto.CreateUserDto;
|
||||
import de.szut.casino.user.dto.GetUserDto;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class AuthService {
|
||||
|
||||
@Autowired
|
||||
private AuthenticationManager authenticationManager;
|
||||
|
||||
@Autowired
|
||||
private JwtUtils jwtUtils;
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
public AuthResponseDto login(LoginRequestDto loginRequest) {
|
||||
Authentication authentication = authenticationManager.authenticate(
|
||||
new UsernamePasswordAuthenticationToken(
|
||||
loginRequest.getUsernameOrEmail(),
|
||||
loginRequest.getPassword()));
|
||||
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
String jwt = jwtUtils.generateToken(authentication);
|
||||
|
||||
return new AuthResponseDto(jwt);
|
||||
}
|
||||
|
||||
public GetUserDto register(CreateUserDto signUpRequest) {
|
||||
UserEntity user = userService.createUser(signUpRequest);
|
||||
return new GetUserDto(
|
||||
user.getId(),
|
||||
user.getEmail(),
|
||||
user.getUsername(),
|
||||
user.getBalance()
|
||||
);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,48 @@
|
|||
package de.szut.casino.security.service;
|
||||
|
||||
import de.szut.casino.exceptionHandling.exceptions.UserNotFoundException;
|
||||
import de.szut.casino.user.UserEntity;
|
||||
import de.szut.casino.user.UserRepository;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
public class UserDetailsServiceImpl implements UserDetailsService {
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Override
|
||||
public UserDetails loadUserByUsername(String usernameOrEmail) throws UsernameNotFoundException {
|
||||
Optional<UserEntity> user = userRepository.findByUsername(usernameOrEmail);
|
||||
|
||||
if (user.isEmpty()) {
|
||||
user = userRepository.findByEmail(usernameOrEmail);
|
||||
}
|
||||
|
||||
UserEntity userEntity = user.orElseThrow(() ->
|
||||
new UsernameNotFoundException("User not found with username or email: " + usernameOrEmail));
|
||||
|
||||
return new org.springframework.security.core.userdetails.User(
|
||||
userEntity.getUsername(),
|
||||
userEntity.getPassword(),
|
||||
new ArrayList<>());
|
||||
}
|
||||
|
||||
public UserEntity getUserByUsernameOrEmail(String usernameOrEmail) {
|
||||
Optional<UserEntity> user = userRepository.findByUsername(usernameOrEmail);
|
||||
|
||||
if (user.isEmpty()) {
|
||||
user = userRepository.findByEmail(usernameOrEmail);
|
||||
}
|
||||
|
||||
return user.orElseThrow(() ->
|
||||
new UserNotFoundException("User not found with username or email: " + usernameOrEmail));
|
||||
}
|
||||
}
|
|
@ -30,10 +30,10 @@ public class SlotController {
|
|||
|
||||
@PostMapping("/slots/spin")
|
||||
public ResponseEntity<Object> spinSlots(@RequestBody @Valid BetDto betDto, @RequestHeader("Authorization") String token) {
|
||||
Optional<UserEntity> optionalUser = userService.getCurrentUser(token);
|
||||
Optional<UserEntity> optionalUser = userService.getCurrentUser();
|
||||
|
||||
if (optionalUser.isEmpty()) {
|
||||
throw new UserNotFoundException();
|
||||
throw new UserNotFoundException("User not found");
|
||||
}
|
||||
|
||||
UserEntity user = optionalUser.get();
|
||||
|
|
|
@ -1,43 +1,41 @@
|
|||
package de.szut.casino.user;
|
||||
|
||||
import de.szut.casino.exceptionHandling.exceptions.UserNotFoundException;
|
||||
import de.szut.casino.user.dto.CreateUserDto;
|
||||
import de.szut.casino.user.dto.GetUserDto;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@Slf4j
|
||||
@RestController
|
||||
@CrossOrigin
|
||||
@RequestMapping("/api/users")
|
||||
public class UserController {
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
@PostMapping("/user")
|
||||
public ResponseEntity<?> createUser(@RequestBody @Valid CreateUserDto userData) {
|
||||
if (userService.exists(userData.getAuthentikId())) {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.add("Location", "/user");
|
||||
@Autowired
|
||||
private UserMappingService userMappingService;
|
||||
|
||||
return new ResponseEntity<>(headers, HttpStatus.FOUND);
|
||||
}
|
||||
|
||||
return ResponseEntity.ok(userService.createUser(userData));
|
||||
@GetMapping("/me")
|
||||
public ResponseEntity<GetUserDto> getCurrentUser() {
|
||||
return ResponseEntity.ok(userMappingService.mapToGetUserDto(userService.getCurrentUser().orElseThrow()));
|
||||
}
|
||||
|
||||
@GetMapping("/user")
|
||||
public ResponseEntity<GetUserDto> getCurrentUser(@RequestHeader("Authorization") String token) {
|
||||
GetUserDto userData = userService.getCurrentUserAsDto(token);
|
||||
|
||||
if (userData == null) {
|
||||
throw new UserNotFoundException();
|
||||
}
|
||||
|
||||
return ResponseEntity.ok(userData);
|
||||
|
||||
@GetMapping("/current")
|
||||
public ResponseEntity<GetUserDto> getCurrentUserAlternative() {
|
||||
return ResponseEntity.ok(userMappingService.mapToGetUserDto(userService.getCurrentUser().orElseThrow()));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ResponseEntity<GetUserDto> getUserById(@PathVariable Long id) {
|
||||
return ResponseEntity.ok(userService.getUserById(id));
|
||||
}
|
||||
|
||||
@GetMapping("/username/{username}")
|
||||
public ResponseEntity<GetUserDto> getUserByUsername(@PathVariable String username) {
|
||||
return ResponseEntity.ok(userService.getUserByUsername(username));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -18,16 +18,22 @@ public class UserEntity {
|
|||
@Id
|
||||
@GeneratedValue
|
||||
private Long id;
|
||||
|
||||
@Column(unique = true)
|
||||
private String email;
|
||||
|
||||
@Column(unique = true)
|
||||
private String authentikId;
|
||||
private String username;
|
||||
|
||||
|
||||
private String password;
|
||||
|
||||
@Column(precision = 19, scale = 2)
|
||||
private BigDecimal balance;
|
||||
|
||||
public UserEntity(String authentikId, String username, BigDecimal balance) {
|
||||
this.authentikId = authentikId;
|
||||
public UserEntity(String email, String username, String password, BigDecimal balance) {
|
||||
this.email = email;
|
||||
this.username = username;
|
||||
this.password = password;
|
||||
this.balance = balance;
|
||||
}
|
||||
|
||||
|
|
|
@ -2,18 +2,17 @@ package de.szut.casino.user;
|
|||
|
||||
import de.szut.casino.user.dto.CreateUserDto;
|
||||
import de.szut.casino.user.dto.GetUserDto;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
@Service
|
||||
public class UserMappingService {
|
||||
|
||||
public GetUserDto mapToGetUserDto(UserEntity user) {
|
||||
return new GetUserDto(user.getAuthentikId(), user.getUsername(), user.getBalance());
|
||||
}
|
||||
|
||||
public UserEntity mapToUserEntity(CreateUserDto createUserDto) {
|
||||
return new UserEntity(createUserDto.getAuthentikId(), createUserDto.getUsername(), BigDecimal.ZERO);
|
||||
return new GetUserDto(user.getId(), user.getEmail(), user.getUsername(), user.getBalance());
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -1,15 +1,17 @@
|
|||
package de.szut.casino.user;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
public interface UserRepository extends JpaRepository<UserEntity, Long> {
|
||||
@Query("SELECT u FROM UserEntity u WHERE u.authentikId = ?1")
|
||||
Optional<UserEntity> findOneByAuthentikId(String authentikId);
|
||||
|
||||
boolean existsByAuthentikId(String authentikId);
|
||||
Optional<UserEntity> findByUsername(String username);
|
||||
|
||||
Optional<UserEntity> findByEmail(String email);
|
||||
|
||||
boolean existsByUsername(String username);
|
||||
|
||||
boolean existsByEmail(String email);
|
||||
}
|
||||
|
|
|
@ -1,16 +1,14 @@
|
|||
package de.szut.casino.user;
|
||||
|
||||
import de.szut.casino.exceptionHandling.exceptions.UserNotFoundException;
|
||||
import de.szut.casino.user.dto.CreateUserDto;
|
||||
import de.szut.casino.user.dto.GetUserDto;
|
||||
import de.szut.casino.user.dto.KeycloakUserDto;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
|
@ -18,64 +16,69 @@ public class UserService {
|
|||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Autowired
|
||||
private RestTemplate http;
|
||||
|
||||
@Autowired
|
||||
private UserMappingService mappingService;
|
||||
|
||||
@Autowired
|
||||
private PasswordEncoder passwordEncoder;
|
||||
|
||||
public UserEntity createUser(CreateUserDto createUserDto) {
|
||||
UserEntity user = mappingService.mapToUserEntity(createUserDto);
|
||||
userRepository.save(user);
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
public GetUserDto getUser(String authentikId) {
|
||||
Optional<UserEntity> user = this.userRepository.findOneByAuthentikId(authentikId);
|
||||
|
||||
return user.map(userEntity -> mappingService.mapToGetUserDto(userEntity)).orElse(null);
|
||||
}
|
||||
|
||||
public GetUserDto getCurrentUserAsDto(String token) {
|
||||
KeycloakUserDto userData = getAuthentikUserInfo(token);
|
||||
|
||||
if (userData == null) {
|
||||
return null;
|
||||
if (userRepository.existsByUsername(createUserDto.getUsername())) {
|
||||
throw new IllegalArgumentException("Username is already taken");
|
||||
}
|
||||
Optional<UserEntity> user = this.userRepository.findOneByAuthentikId(userData.getSub());
|
||||
|
||||
return user.map(userEntity -> mappingService.mapToGetUserDto(userEntity)).orElse(null);
|
||||
}
|
||||
|
||||
public Optional<UserEntity> getCurrentUser(String token) {
|
||||
KeycloakUserDto userData = getAuthentikUserInfo(token);
|
||||
|
||||
if (userData == null) {
|
||||
return Optional.empty();
|
||||
if (userRepository.existsByEmail(createUserDto.getEmail())) {
|
||||
throw new IllegalArgumentException("Email is already in use");
|
||||
}
|
||||
return this.userRepository.findOneByAuthentikId(userData.getSub());
|
||||
|
||||
UserEntity user = new UserEntity(
|
||||
createUserDto.getEmail(),
|
||||
createUserDto.getUsername(),
|
||||
passwordEncoder.encode(createUserDto.getPassword()),
|
||||
BigDecimal.valueOf(1000) // Starting balance
|
||||
);
|
||||
|
||||
return userRepository.save(user);
|
||||
}
|
||||
|
||||
private KeycloakUserDto getAuthentikUserInfo(String token) {
|
||||
try {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.set("Authorization", token);
|
||||
ResponseEntity<KeycloakUserDto> response = this.http.exchange(
|
||||
"https://oauth.simonis.lol/application/o/userinfo/",
|
||||
HttpMethod.GET,
|
||||
new HttpEntity<>(headers),
|
||||
KeycloakUserDto.class
|
||||
);
|
||||
|
||||
return response.getBody();
|
||||
} catch (Exception e) {
|
||||
System.err.println("Error fetching user info from Authentik: " + e.getMessage());
|
||||
return null;
|
||||
}
|
||||
public GetUserDto getUserById(Long id) {
|
||||
UserEntity user = userRepository.findById(id)
|
||||
.orElseThrow(() -> new UserNotFoundException("User not found with id: " + id));
|
||||
|
||||
return mappingService.mapToGetUserDto(user);
|
||||
}
|
||||
|
||||
public GetUserDto getUserByUsername(String username) {
|
||||
UserEntity user = userRepository.findByUsername(username)
|
||||
.orElseThrow(() -> new UserNotFoundException("User not found with username: " + username));
|
||||
|
||||
return mappingService.mapToGetUserDto(user);
|
||||
}
|
||||
|
||||
public GetUserDto getUserByEmail(String email) {
|
||||
UserEntity user = userRepository.findByEmail(email)
|
||||
.orElseThrow(() -> new UserNotFoundException("User not found with email: " + email));
|
||||
|
||||
return mappingService.mapToGetUserDto(user);
|
||||
}
|
||||
|
||||
public boolean exists(String authentikId) {
|
||||
return userRepository.existsByAuthentikId(authentikId);
|
||||
public Optional<UserEntity> getCurrentUser() {
|
||||
String username = SecurityContextHolder.getContext().getAuthentication().getName();
|
||||
|
||||
return userRepository.findByUsername(username);
|
||||
}
|
||||
|
||||
public UserEntity getCurrentUserEntity() {
|
||||
String username = SecurityContextHolder.getContext().getAuthentication().getName();
|
||||
return userRepository.findByUsername(username)
|
||||
.orElseThrow(() -> new UserNotFoundException("User not found with username: " + username));
|
||||
}
|
||||
|
||||
public boolean existsByUsername(String username) {
|
||||
return userRepository.existsByUsername(username);
|
||||
}
|
||||
|
||||
public boolean existsByEmail(String email) {
|
||||
return userRepository.existsByEmail(email);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,5 +1,8 @@
|
|||
package de.szut.casino.user.dto;
|
||||
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
@ -10,6 +13,15 @@ import lombok.Setter;
|
|||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class CreateUserDto {
|
||||
private String authentikId;
|
||||
@NotBlank(message = "Email is required")
|
||||
@Email(message = "Email should be valid")
|
||||
private String email;
|
||||
|
||||
@NotBlank(message = "Username is required")
|
||||
@Size(min = 3, max = 20, message = "Username must be between 3 and 20 characters")
|
||||
private String username;
|
||||
|
||||
@NotBlank(message = "Password is required")
|
||||
@Size(min = 6, message = "Password must be at least 6 characters")
|
||||
private String password;
|
||||
}
|
||||
|
|
|
@ -12,7 +12,8 @@ import java.math.BigDecimal;
|
|||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class GetUserDto {
|
||||
private String authentikId;
|
||||
private Long id;
|
||||
private String email;
|
||||
private String username;
|
||||
private BigDecimal balance;
|
||||
}
|
||||
|
|
|
@ -22,7 +22,7 @@ public class GetTransactionService {
|
|||
private TransactionRepository transactionRepository;
|
||||
|
||||
public UserTransactionsDto getUserTransactionsDto(String authToken, Integer limit, Integer offset) {
|
||||
Optional<UserEntity> user = this.userService.getCurrentUser(authToken);
|
||||
Optional<UserEntity> user = this.userService.getCurrentUser();
|
||||
if (user.isPresent()) {
|
||||
List<TransactionEntity> transactionEntities = this.transactionRepository.findByUserIdWithLimit(user.get(), limit, offset);
|
||||
Boolean hasMore = this.transactionRepository.hasMore(user.get(), limit, offset);
|
||||
|
|
|
@ -8,33 +8,15 @@ stripe.webhook.secret=${STRIPE_WEBHOOK_SECRET:whsec_746b6a488665f6057118bdb4a2b3
|
|||
app.frontend-host=${FE_URL:http://localhost:4200}
|
||||
|
||||
spring.application.name=casino
|
||||
#client registration configuration
|
||||
|
||||
spring.security.oauth2.client.registration.authentik.client-id=${AUTH_CLIENT_ID:MDqjm1kcWKuZfqHJXjxwAV20i44aT7m4VhhTL3Nm}
|
||||
spring.security.oauth2.client.registration.authentik.client-secret=${AUTH_CLIENT_SECRET:GY2F8te6iAVYt1TNAUVLzWZEXb6JoMNp6chbjqaXNq4gS5xTDL54HqBiAlV1jFKarN28LQ7FUsYX4SbwjfEhZhgeoKuBnZKjR9eiu7RawnGgxIK9ffvUfMkjRxnmiGI5}
|
||||
spring.security.oauth2.client.registration.authentik.provider=authentik
|
||||
spring.security.oauth2.client.registration.authentik.client-name=Authentik
|
||||
spring.security.oauth2.client.registration.authentik.scope=openid,email,profile
|
||||
spring.security.oauth2.client.registration.authentik.client-authentication-method=client_secret_basic
|
||||
spring.security.oauth2.client.registration.authentik.authorization-grant-type=authorization_code
|
||||
spring.security.oauth2.client.registration.authentik.redirect-uri={baseUrl}/login/oauth2/code/{registrationId}
|
||||
# JWT Configuration
|
||||
jwt.secret=${JWT_SECRET:5367566B59703373367639792F423F4528482B4D6251655468576D5A71347437}
|
||||
jwt.expiration.ms=${JWT_EXPIRATION_MS:86400000}
|
||||
|
||||
# Provider settings
|
||||
spring.security.oauth2.client.provider.authentik.issuer-uri=${AUTH_PROVIDER_ISSUER:https://oauth.simonis.lol/application/o/casino-dev/}
|
||||
spring.security.oauth2.client.provider.authentik.authorization-uri=${AUTH_PROVIDER_AUTHORIZE_URI:https://oauth.simonis.lol/application/o/authorize/}
|
||||
spring.security.oauth2.client.provider.authentik.token-uri=${AUTH_PROVIDER_TOKEN_URI:https://oauth.simonis.lol/application/o/token/}
|
||||
spring.security.oauth2.client.provider.authentik.user-info-uri=${AUTH_PROVIDER_USERINFO_URI:https://oauth.simonis.lol/application/o/userinfo/}
|
||||
spring.security.oauth2.client.provider.authentik.jwk-set-uri=${AUTH_PROVIDER_JWKS_URI:https://oauth.simonis.lol/application/o/casino-dev/jwks/}
|
||||
spring.security.oauth2.client.provider.authentik.user-name-attribute=${AUTH_PROVIDER_NAME_ATTR:preferred_username}
|
||||
|
||||
# Resource server config
|
||||
spring.security.oauth2.resourceserver.jwt.issuer-uri=${AUTH_JWT_ISSUER_URI:https://oauth.simonis.lol/application/o/casino-dev}/
|
||||
spring.security.oauth2.resourceserver.jwt.jwk-set-uri=${AUTH_JWT_JWT_SET_URI:https://oauth.simonis.lol/application/o/casino-dev/jwks/}
|
||||
|
||||
#OIDC provider configuration:
|
||||
# Logging
|
||||
logging.level.org.springframework.security=DEBUG
|
||||
#validating JWT token against our Authentik server
|
||||
|
||||
# Swagger
|
||||
springdoc.swagger-ui.path=swagger
|
||||
springdoc.swagger-ui.try-it-out-enabled=true
|
||||
|
||||
|
|
Reference in a new issue