-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthenticationController.java
More file actions
50 lines (38 loc) · 2.02 KB
/
Copy pathAuthenticationController.java
File metadata and controls
50 lines (38 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.neflodev.expensestrackerapi.web;
import com.neflodev.expensestrackerapi.dto.authentication.LoginResponse;
import com.neflodev.expensestrackerapi.dto.authentication.LoginUserDTO;
import com.neflodev.expensestrackerapi.dto.authentication.RegisterUserDTO;
import com.neflodev.expensestrackerapi.exception.custom.ConflictException;
import com.neflodev.expensestrackerapi.model.UserEntity;
import com.neflodev.expensestrackerapi.service.authentication.AuthenticationService;
import com.neflodev.expensestrackerapi.service.authentication.JwtService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/auth")
public class AuthenticationController {
private final JwtService jwtService;
private final AuthenticationService authenticationService;
public AuthenticationController(JwtService jwtService, AuthenticationService authenticationService) {
this.jwtService = jwtService;
this.authenticationService = authenticationService;
}
@PostMapping("/signup")
public ResponseEntity<UserEntity> registerUser(@RequestBody RegisterUserDTO registerDTO) {
if (authenticationService.isUserRegistered(registerDTO)){
throw new ConflictException();
}
UserEntity registeredUser = authenticationService.signup(registerDTO);
return ResponseEntity.ok(registeredUser);
}
@PostMapping("/login")
public ResponseEntity<LoginResponse> authenticateUser(@RequestBody LoginUserDTO loginDTO) {
UserEntity authenticatedUser = authenticationService.authenticate(loginDTO);
String jwtToken = jwtService.generateToken(authenticatedUser);
LoginResponse loginResponse = new LoginResponse(jwtToken, jwtService.getExpirationTime());
return ResponseEntity.ok(loginResponse);
}
}