refactor: handle optional user inside userservice, replace @autowire
All checks were successful
CI / Get Changed Files (pull_request) Successful in 11s
CI / eslint (pull_request) Has been skipped
CI / oxlint (pull_request) Has been skipped
CI / Docker frontend validation (pull_request) Has been skipped
CI / prettier (pull_request) Has been skipped
CI / test-build (pull_request) Has been skipped
CI / Checkstyle Main (pull_request) Successful in 51s
CI / Docker backend validation (pull_request) Successful in 53s

This commit is contained in:
Phan Huy Tran 2025-05-28 10:40:42 +02:00
commit 1c45ff0058
21 changed files with 127 additions and 151 deletions

View file

@ -59,13 +59,7 @@ public class BlackJackGameController {
@PostMapping("/blackjack/start") @PostMapping("/blackjack/start")
public ResponseEntity<Object> createBlackJackGame(@RequestBody @Valid BetDto betDto) { public ResponseEntity<Object> createBlackJackGame(@RequestBody @Valid BetDto betDto) {
Optional<UserEntity> optionalUser = userService.getCurrentUser(); UserEntity user = this.userService.getCurrentUser();
if (optionalUser.isEmpty()) {
throw new UserNotFoundException();
}
UserEntity user = optionalUser.get();
if (!this.balanceService.hasFunds(user, betDto)) { if (!this.balanceService.hasFunds(user, betDto)) {
throw new InsufficientFundsException(); throw new InsufficientFundsException();
@ -75,13 +69,7 @@ public class BlackJackGameController {
} }
private BlackJackGameEntity getBlackJackGame(Long gameId) { private BlackJackGameEntity getBlackJackGame(Long gameId) {
Optional<UserEntity> optionalUser = userService.getCurrentUser(); UserEntity user = userService.getCurrentUser();
if (optionalUser.isEmpty()) {
throw new UserNotFoundException();
}
UserEntity user = optionalUser.get();
BlackJackGameEntity game = blackJackService.getBlackJackGame(gameId); BlackJackGameEntity game = blackJackService.getBlackJackGame(gameId);
if (game == null || !Objects.equals(game.getUserId(), user.getId())) { if (game == null || !Objects.equals(game.getUserId(), user.getId())) {
throw new UserBlackJackGameMismatchException(gameId); throw new UserBlackJackGameMismatchException(gameId);

View file

@ -28,13 +28,7 @@ public class CoinflipController {
@PostMapping("/coinflip") @PostMapping("/coinflip")
public ResponseEntity<Object> coinFlip(@RequestBody @Valid CoinflipDto coinflipDto) { public ResponseEntity<Object> coinFlip(@RequestBody @Valid CoinflipDto coinflipDto) {
Optional<UserEntity> optionalUser = userService.getCurrentUser(); UserEntity user = userService.getCurrentUser();
if (optionalUser.isEmpty()) {
throw new UserNotFoundException();
}
UserEntity user = optionalUser.get();
if (!this.balanceService.hasFunds(user, coinflipDto)) { if (!this.balanceService.hasFunds(user, coinflipDto)) {
throw new InsufficientFundsException(); throw new InsufficientFundsException();

View file

@ -16,8 +16,6 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.util.Optional;
@RestController @RestController
public class DepositController { public class DepositController {
@ -29,7 +27,7 @@ public class DepositController {
private final TransactionService transactionService; private final TransactionService transactionService;
private UserService userService; private final UserService userService;
public DepositController(TransactionService transactionService, UserService userService) { public DepositController(TransactionService transactionService, UserService userService) {
this.transactionService = transactionService; this.transactionService = transactionService;
@ -40,7 +38,7 @@ public class DepositController {
public ResponseEntity<SessionIdDto> checkout(@RequestBody @Valid AmountDto amountDto, @RequestHeader("Authorization") String token) throws StripeException { public ResponseEntity<SessionIdDto> checkout(@RequestBody @Valid AmountDto amountDto, @RequestHeader("Authorization") String token) throws StripeException {
Stripe.apiKey = stripeKey; Stripe.apiKey = stripeKey;
Optional<UserEntity> optionalUserEntity = this.userService.getCurrentUser(); UserEntity user = userService.getCurrentUser();
SessionCreateParams params = SessionCreateParams.builder() SessionCreateParams params = SessionCreateParams.builder()
.addLineItem(SessionCreateParams.LineItem.builder() .addLineItem(SessionCreateParams.LineItem.builder()
@ -60,11 +58,7 @@ public class DepositController {
Session session = Session.create(params); Session session = Session.create(params);
if (optionalUserEntity.isEmpty()) { transactionService.createTransaction(user, session.getId(), amountDto.getAmount());
throw new RuntimeException("User doesnt exist");
}
transactionService.createTransaction(optionalUserEntity.get(), session.getId(), amountDto.getAmount());
return ResponseEntity.ok(new SessionIdDto(session.getId())); return ResponseEntity.ok(new SessionIdDto(session.getId()));
} }

View file

@ -27,13 +27,7 @@ public class DiceController {
@PostMapping("/dice") @PostMapping("/dice")
public ResponseEntity<Object> rollDice(@RequestBody @Valid DiceDto diceDto) { public ResponseEntity<Object> rollDice(@RequestBody @Valid DiceDto diceDto) {
Optional<UserEntity> optionalUser = userService.getCurrentUser(); UserEntity user = userService.getCurrentUser();
if (optionalUser.isEmpty()) {
throw new UserNotFoundException();
}
UserEntity user = optionalUser.get();
if (!this.balanceService.hasFunds(user, diceDto)) { if (!this.balanceService.hasFunds(user, diceDto)) {
throw new InsufficientFundsException(); throw new InsufficientFundsException();

View file

@ -38,13 +38,7 @@ public class LootBoxController {
} }
LootBoxEntity lootBox = optionalLootBox.get(); LootBoxEntity lootBox = optionalLootBox.get();
UserEntity user = userService.getCurrentUser();
Optional<UserEntity> optionalUser = userService.getCurrentUser();
if (optionalUser.isEmpty()) {
throw new UserNotFoundException();
}
UserEntity user = optionalUser.get();
if (lootBoxService.hasSufficientBalance(user, lootBox.getPrice())) { if (lootBoxService.hasSufficientBalance(user, lootBox.getPrice())) {
throw new InsufficientFundsException(); throw new InsufficientFundsException();

View file

@ -9,7 +9,6 @@ import de.szut.casino.user.dto.CreateUserDto;
import de.szut.casino.user.dto.GetUserDto; import de.szut.casino.user.dto.GetUserDto;
import jakarta.mail.MessagingException; import jakarta.mail.MessagingException;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@ -20,8 +19,11 @@ import java.io.IOException;
public class AuthController { public class AuthController {
@Autowired private final AuthService authService;
private AuthService authService;
public AuthController(AuthService authService) {
this.authService = authService;
}
@PostMapping("/login") @PostMapping("/login")
public ResponseEntity<AuthResponseDto> authenticateUser(@Valid @RequestBody LoginRequestDto loginRequest) throws EmailNotVerifiedException { public ResponseEntity<AuthResponseDto> authenticateUser(@Valid @RequestBody LoginRequestDto loginRequest) throws EmailNotVerifiedException {

View file

@ -1,7 +1,6 @@
package de.szut.casino.security; package de.szut.casino.security;
import de.szut.casino.security.jwt.JwtAuthenticationFilter; import de.szut.casino.security.jwt.JwtAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@ -32,11 +31,13 @@ public class SecurityConfig {
@Value("${app.frontend-host}") @Value("${app.frontend-host}")
private String frontendHost; private String frontendHost;
@Autowired private final UserDetailsService userDetailsService;
private UserDetailsService userDetailsService; private final JwtAuthenticationFilter jwtAuthenticationFilter;
@Autowired public SecurityConfig(UserDetailsService userDetailsService, JwtAuthenticationFilter jwtAuthenticationFilter) {
private JwtAuthenticationFilter jwtAuthenticationFilter; this.userDetailsService = userDetailsService;
this.jwtAuthenticationFilter = jwtAuthenticationFilter;
}
@Bean @Bean

View file

@ -4,7 +4,6 @@ import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException; import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
@ -19,11 +18,13 @@ import java.io.IOException;
@Component @Component
public class JwtAuthenticationFilter extends OncePerRequestFilter { public class JwtAuthenticationFilter extends OncePerRequestFilter {
@Autowired private final JwtUtils jwtUtils;
private JwtUtils jwtUtils; private final UserDetailsService userDetailsService;
@Autowired public JwtAuthenticationFilter(JwtUtils jwtUtils, UserDetailsService userDetailsService) {
private UserDetailsService userDetailsService; this.jwtUtils = jwtUtils;
this.userDetailsService = userDetailsService;
}
@Override @Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)

View file

@ -4,7 +4,6 @@ import de.szut.casino.exceptionHandling.exceptions.OAuth2AuthenticationProcessin
import de.szut.casino.user.AuthProvider; import de.szut.casino.user.AuthProvider;
import de.szut.casino.user.UserEntity; import de.szut.casino.user.UserEntity;
import de.szut.casino.user.UserRepository; import de.szut.casino.user.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException; import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
@ -22,11 +21,13 @@ import java.util.UUID;
@Service @Service
public class CustomOAuth2UserService extends DefaultOAuth2UserService { public class CustomOAuth2UserService extends DefaultOAuth2UserService {
@Autowired private final UserRepository userRepository;
private UserRepository userRepository; private final PasswordEncoder oauth2PasswordEncoder;
@Autowired public CustomOAuth2UserService(UserRepository userRepository, PasswordEncoder oauth2PasswordEncoder) {
private PasswordEncoder oauth2PasswordEncoder; this.userRepository = userRepository;
this.oauth2PasswordEncoder = oauth2PasswordEncoder;
}
@Override @Override
public OAuth2User loadUser(OAuth2UserRequest oAuth2UserRequest) throws OAuth2AuthenticationException { public OAuth2User loadUser(OAuth2UserRequest oAuth2UserRequest) throws OAuth2AuthenticationException {

View file

@ -5,7 +5,6 @@ import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
@ -21,8 +20,11 @@ public class OAuth2AuthenticationSuccessHandler extends SimpleUrlAuthenticationS
@Value("${app.oauth2.authorizedRedirectUris}") @Value("${app.oauth2.authorizedRedirectUris}")
private String redirectUri; private String redirectUri;
@Autowired private final JwtUtils jwtUtils;
private JwtUtils jwtUtils;
public OAuth2AuthenticationSuccessHandler(JwtUtils jwtUtils) {
this.jwtUtils = jwtUtils;
}
@Override @Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)

View file

@ -3,7 +3,6 @@ package de.szut.casino.security.oauth2.github;
import de.szut.casino.security.dto.AuthResponseDto; import de.szut.casino.security.dto.AuthResponseDto;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@ -23,8 +22,11 @@ public class GitHubController {
@Value("${spring.security.oauth2.client.registration.github.redirect-uri}") @Value("${spring.security.oauth2.client.registration.github.redirect-uri}")
private String redirectUri; private String redirectUri;
@Autowired private final GitHubService githubService;
private GitHubService githubService;
public GitHubController(GitHubService githubService) {
this.githubService = githubService;
}
@GetMapping("/authorize") @GetMapping("/authorize")
public RedirectView authorizeGithub() { public RedirectView authorizeGithub() {

View file

@ -5,7 +5,6 @@ import de.szut.casino.security.jwt.JwtUtils;
import de.szut.casino.user.AuthProvider; import de.szut.casino.user.AuthProvider;
import de.szut.casino.user.UserEntity; import de.szut.casino.user.UserEntity;
import de.szut.casino.user.UserRepository; import de.szut.casino.user.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity; import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
@ -29,17 +28,17 @@ public class GitHubService {
@Value("${spring.security.oauth2.client.registration.github.client-secret}") @Value("${spring.security.oauth2.client.registration.github.client-secret}")
private String clientSecret; private String clientSecret;
@Autowired private final AuthenticationManager authenticationManager;
private AuthenticationManager authenticationManager; private final UserRepository userRepository;
private final JwtUtils jwtUtils;
private final PasswordEncoder oauth2PasswordEncoder;
@Autowired public GitHubService(AuthenticationManager authenticationManager, UserRepository userRepository, JwtUtils jwtUtils, PasswordEncoder oauth2PasswordEncoder) {
private UserRepository userRepository; this.authenticationManager = authenticationManager;
this.userRepository = userRepository;
@Autowired this.jwtUtils = jwtUtils;
private JwtUtils jwtUtils; this.oauth2PasswordEncoder = oauth2PasswordEncoder;
}
@Autowired
private PasswordEncoder oauth2PasswordEncoder;
public AuthResponseDto processGithubCode(String code) { public AuthResponseDto processGithubCode(String code) {
try { try {

View file

@ -4,7 +4,6 @@ import de.szut.casino.security.dto.AuthResponseDto;
import de.szut.casino.security.oauth2.github.GithubCallbackDto; import de.szut.casino.security.oauth2.github.GithubCallbackDto;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@ -24,8 +23,11 @@ public class GoogleController {
@Value("${spring.security.oauth2.client.registration.google.redirect-uri}") @Value("${spring.security.oauth2.client.registration.google.redirect-uri}")
private String redirectUri; private String redirectUri;
@Autowired private final GoogleService googleService;
private GoogleService googleService;
public GoogleController(GoogleService googleService) {
this.googleService = googleService;
}
@GetMapping("/authorize") @GetMapping("/authorize")
public RedirectView authorizeGoogle() { public RedirectView authorizeGoogle() {

View file

@ -7,7 +7,6 @@ import de.szut.casino.user.UserEntity;
import de.szut.casino.user.UserRepository; import de.szut.casino.user.UserRepository;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity; import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
@ -23,7 +22,9 @@ import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.*; import java.util.Map;
import java.util.Optional;
import java.util.UUID;
@Service @Service
public class GoogleService { public class GoogleService {
@ -44,17 +45,17 @@ public class GoogleService {
@Value("${spring.security.oauth2.client.provider.google.user-info-uri}") @Value("${spring.security.oauth2.client.provider.google.user-info-uri}")
private String userInfoUri; private String userInfoUri;
@Autowired private final AuthenticationManager authenticationManager;
private AuthenticationManager authenticationManager; private final UserRepository userRepository;
private final JwtUtils jwtUtils;
private final PasswordEncoder oauth2PasswordEncoder;
@Autowired public GoogleService(AuthenticationManager authenticationManager, UserRepository userRepository, JwtUtils jwtUtils, PasswordEncoder oauth2PasswordEncoder) {
private UserRepository userRepository; this.authenticationManager = authenticationManager;
this.userRepository = userRepository;
@Autowired this.jwtUtils = jwtUtils;
private JwtUtils jwtUtils; this.oauth2PasswordEncoder = oauth2PasswordEncoder;
}
@Autowired
private PasswordEncoder oauth2PasswordEncoder;
public AuthResponseDto processGoogleCode(String code) { public AuthResponseDto processGoogleCode(String code) {
try { try {

View file

@ -11,7 +11,6 @@ import de.szut.casino.user.dto.CreateUserDto;
import de.szut.casino.user.dto.GetUserDto; import de.szut.casino.user.dto.GetUserDto;
import jakarta.mail.MessagingException; import jakarta.mail.MessagingException;
import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
@ -25,20 +24,19 @@ import java.util.Optional;
@Service @Service
public class AuthService { public class AuthService {
@Autowired private final AuthenticationManager authenticationManager;
private AuthenticationManager authenticationManager; private final JwtUtils jwtUtils;
private final UserService userService;
private final EmailService emailService;
private final PasswordEncoder passwordEncoder;
@Autowired public AuthService(AuthenticationManager authenticationManager, JwtUtils jwtUtils, UserService userService, EmailService emailService, PasswordEncoder passwordEncoder) {
private JwtUtils jwtUtils; this.authenticationManager = authenticationManager;
this.jwtUtils = jwtUtils;
@Autowired this.userService = userService;
private UserService userService; this.emailService = emailService;
this.passwordEncoder = passwordEncoder;
@Autowired }
private EmailService emailService;
@Autowired
private PasswordEncoder passwordEncoder;
public AuthResponseDto login(LoginRequestDto loginRequest) throws EmailNotVerifiedException { public AuthResponseDto login(LoginRequestDto loginRequest) throws EmailNotVerifiedException {
if (!userService.isVerified(loginRequest.getUsernameOrEmail())) { if (!userService.isVerified(loginRequest.getUsernameOrEmail())) {

View file

@ -2,7 +2,6 @@ package de.szut.casino.security.service;
import de.szut.casino.user.UserEntity; import de.szut.casino.user.UserEntity;
import de.szut.casino.user.UserRepository; 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.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.core.userdetails.UsernameNotFoundException;
@ -14,8 +13,11 @@ import java.util.Optional;
@Service @Service
public class UserDetailsServiceImpl implements UserDetailsService { public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired private final UserRepository userRepository;
private UserRepository userRepository;
public UserDetailsServiceImpl(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override @Override
public UserDetails loadUserByUsername(String usernameOrEmail) throws UsernameNotFoundException { public UserDetails loadUserByUsername(String usernameOrEmail) throws UsernameNotFoundException {

View file

@ -32,13 +32,7 @@ public class SlotController {
@PostMapping("/slots/spin") @PostMapping("/slots/spin")
public ResponseEntity<Object> spinSlots(@RequestBody @Valid BetDto betDto) { public ResponseEntity<Object> spinSlots(@RequestBody @Valid BetDto betDto) {
Optional<UserEntity> optionalUser = userService.getCurrentUser(); UserEntity user = userService.getCurrentUser();
if (optionalUser.isEmpty()) {
throw new UserNotFoundException();
}
UserEntity user = optionalUser.get();
if (!this.balanceService.hasFunds(user, betDto)) { if (!this.balanceService.hasFunds(user, betDto)) {
throw new InsufficientFundsException(); throw new InsufficientFundsException();

View file

@ -2,7 +2,6 @@ package de.szut.casino.user;
import de.szut.casino.user.dto.GetUserDto; import de.szut.casino.user.dto.GetUserDto;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
@ -15,14 +14,17 @@ import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/users") @RequestMapping("/users")
public class UserController { public class UserController {
@Autowired private final UserService userService;
private UserService userService;
@Autowired private final UserMappingService userMappingService;
private UserMappingService userMappingService;
public UserController(UserService userService, UserMappingService userMappingService) {
this.userService = userService;
this.userMappingService = userMappingService;
}
@GetMapping("/me") @GetMapping("/me")
public ResponseEntity<GetUserDto> getCurrentUser() { public ResponseEntity<GetUserDto> getCurrentUser() {
return ResponseEntity.ok(userMappingService.mapToGetUserDto(userService.getCurrentUser().orElseThrow())); return ResponseEntity.ok(userMappingService.mapToGetUserDto(userService.getCurrentUser()));
} }
} }

View file

@ -1,9 +1,9 @@
package de.szut.casino.user; 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.CreateUserDto;
import jakarta.persistence.EntityExistsException; import jakarta.persistence.EntityExistsException;
import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -13,11 +13,13 @@ import java.util.Optional;
@Service @Service
public class UserService { public class UserService {
@Autowired private final UserRepository userRepository;
private UserRepository userRepository; private final PasswordEncoder passwordEncoder;
@Autowired public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) {
private PasswordEncoder passwordEncoder; this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}
public UserEntity createUser(CreateUserDto createUserDto) { public UserEntity createUser(CreateUserDto createUserDto) {
if (userRepository.existsByUsername(createUserDto.getUsername())) { if (userRepository.existsByUsername(createUserDto.getUsername())) {
@ -39,10 +41,15 @@ public class UserService {
return userRepository.save(user); return userRepository.save(user);
} }
public Optional<UserEntity> getCurrentUser() { public UserEntity getCurrentUser() {
String username = SecurityContextHolder.getContext().getAuthentication().getName(); String username = SecurityContextHolder.getContext().getAuthentication().getName();
return userRepository.findByUsername(username); Optional<UserEntity> optionalUser = userRepository.findByUsername(username);
if (optionalUser.isEmpty()) {
throw new UserNotFoundException();
}
return optionalUser.get();
} }
public Optional<UserEntity> getUserByVerificationToken(String token) { public Optional<UserEntity> getUserByVerificationToken(String token) {

View file

@ -6,31 +6,29 @@ import de.szut.casino.user.UserEntity;
import de.szut.casino.user.UserService; import de.szut.casino.user.UserService;
import de.szut.casino.user.transaction.dto.GetTransactionDto; import de.szut.casino.user.transaction.dto.GetTransactionDto;
import de.szut.casino.user.transaction.dto.UserTransactionsDto; import de.szut.casino.user.transaction.dto.UserTransactionsDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.List; import java.util.List;
import java.util.Optional;
@Service @Service
public class GetTransactionService { public class GetTransactionService {
@Autowired private final UserService userService;
private UserService userService;
@Autowired private final TransactionRepository transactionRepository;
private TransactionRepository transactionRepository;
public UserTransactionsDto getUserTransactionsDto(String authToken, Integer limit, Integer offset) { public GetTransactionService(UserService userService, TransactionRepository transactionRepository) {
Optional<UserEntity> user = this.userService.getCurrentUser(); this.userService = userService;
if (user.isPresent()) { this.transactionRepository = transactionRepository;
List<TransactionEntity> transactionEntities = this.transactionRepository.findByUserIdWithLimit(user.get(), limit, offset);
Boolean hasMore = this.transactionRepository.hasMore(user.get(), limit, offset);
return new UserTransactionsDto(mapTransactionsToDtos(transactionEntities), hasMore);
} }
return new UserTransactionsDto(List.of(), false); public UserTransactionsDto getUserTransactionsDto(Integer limit, Integer offset) {
UserEntity user = userService.getCurrentUser();
List<TransactionEntity> transactionEntities = this.transactionRepository.findByUserIdWithLimit(user, limit, offset);
Boolean hasMore = this.transactionRepository.hasMore(user, limit, offset);
return new UserTransactionsDto(mapTransactionsToDtos(transactionEntities), hasMore);
} }
public List<GetTransactionDto> mapTransactionsToDtos(List<TransactionEntity> transactions) { public List<GetTransactionDto> mapTransactionsToDtos(List<TransactionEntity> transactions) {

View file

@ -1,26 +1,26 @@
package de.szut.casino.user.transaction; package de.szut.casino.user.transaction;
import de.szut.casino.user.transaction.dto.UserTransactionsDto; import de.szut.casino.user.transaction.dto.UserTransactionsDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@RestController @RestController
public class TransactionController { public class TransactionController {
@Autowired private final GetTransactionService transactionService;
private GetTransactionService transactionService;
public TransactionController(GetTransactionService transactionService) {
this.transactionService = transactionService;
}
@GetMapping("/user/transactions") @GetMapping("/user/transactions")
public ResponseEntity<UserTransactionsDto> getUserTransactions( public ResponseEntity<UserTransactionsDto> getUserTransactions(
@RequestHeader("Authorization") String authToken,
@RequestParam(value = "limit", required = false) Integer limit, @RequestParam(value = "limit", required = false) Integer limit,
@RequestParam(value = "offset", required = false) Integer offset @RequestParam(value = "offset", required = false) Integer offset
) { ) {
UserTransactionsDto transactionEntities = this.transactionService.getUserTransactionsDto(authToken, limit, offset); UserTransactionsDto transactionEntities = this.transactionService.getUserTransactionsDto(limit, offset);
return ResponseEntity.ok(transactionEntities); return ResponseEntity.ok(transactionEntities);
} }