View Javadoc
1   package fr.tiogars.domaintemplate.domains.auth.services;
2   
3   import org.springframework.security.authentication.AuthenticationManager;
4   import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
5   import org.springframework.security.core.userdetails.UserDetails;
6   import org.springframework.stereotype.Service;
7   
8   import fr.tiogars.domaintemplate.domains.auth.models.LoginRequest;
9   import fr.tiogars.domaintemplate.domains.auth.models.LoginResponse;
10  import fr.tiogars.domaintemplate.domains.auth.user.entities.User;
11  import fr.tiogars.domaintemplate.domains.auth.user.services.UserService;
12  
13  /** Authenticates credentials and issues JWT access tokens. */
14  @Service
15  public class AuthService {
16  
17      private final AuthenticationManager authenticationManager;
18      private final JwtTokenService jwtTokenService;
19      private final UserService userService;
20  
21      AuthService(AuthenticationManager authenticationManager, JwtTokenService jwtTokenService, UserService userService) {
22          this.authenticationManager = authenticationManager;
23          this.jwtTokenService = jwtTokenService;
24          this.userService = userService;
25      }
26  
27      public LoginResponse login(LoginRequest request) {
28          UserDetails principal = (UserDetails) authenticationManager.authenticate(
29                  new UsernamePasswordAuthenticationToken(request.username(), request.password())).getPrincipal();
30          User user = userService.findByUsername(principal.getUsername()).orElseThrow();
31          return new LoginResponse(
32                  jwtTokenService.generateToken(principal),
33                  "Bearer",
34                  jwtTokenService.expiresAt(),
35                  user);
36      }
37  }