-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthController.java
More file actions
executable file
·336 lines (300 loc) · 12.4 KB
/
AuthController.java
File metadata and controls
executable file
·336 lines (300 loc) · 12.4 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
package fr.inote.inote_api.controller;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.MailException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import fr.inote.inote_api.cross_cutting.constants.Endpoint;
import fr.inote.inote_api.cross_cutting.constants.MessagesEn;
import fr.inote.inote_api.cross_cutting.exceptions.*;
import fr.inote.inote_api.cross_cutting.security.impl.JwtServiceImpl;
import fr.inote.inote_api.dto.*;
import fr.inote.inote_api.entity.User;
import fr.inote.inote_api.service.impl.UserServiceImpl;
import java.util.Locale;
import java.util.Map;
import static fr.inote.inote_api.cross_cutting.constants.HttpRequestBody.BEARER;
import static fr.inote.inote_api.cross_cutting.constants.HttpRequestBody.REFRESH;
import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.http.HttpStatus.OK;
/**
* Controller for account user routes
*
* @author atsuhiko Mochizuki
* @date 10/04/2024
*/
/*
* Nota:
* The @RestController annotation is a specialized version of the @Controller
* annotation in Spring MVC.
* It combines the functionality of the @Controller and @ResponseBody
* annotations, which simplifies
* the implementation of RESTful web services.
* When a class is annotated with @RestController, the following points apply:
* -> It acts as a controller, handling client requests.
* -> The @ResponseBody annotation is automatically included, allowing the
* automatic serialization
* of the return object into the HttpResponse.
*/
@RestController
public class AuthController {
/* DEPENDENCIES INJECTION */
/* ============================================================ */
/*
* The AuthenticationManager in Spring Security is responsible for
* authenticating user credentials. It provides methods to authenticate user
* credentials and determine if the user is authorized to access the requested
* resource. Here’s how it works:
*
* 1- Implement the AuthenticationManager interface or use the provided
* ProviderManager implementation.
*
* 2- In your custom implementation or configuration, configure one or more
* AuthenticationProvider instances. An AuthenticationProvider is responsible
* for authenticating a specific type of credential (e.g., username/password,
* OAuth2, LDAP, etc.).
*
* 3- The AuthenticationManager delegates the authentication process to the
* appropriate AuthenticationProvider based on the credential type.
*
* 4- If the authentication is successful, the AuthenticationManager creates an
* Authentication object containing the authenticated user’s information.
* Otherwise, it throws an appropriate exception (e.g., BadCredentialsException,
* DisabledException, LockedException).
*/
private final AuthenticationManager authenticationManager;
private final UserServiceImpl userService;
private final JwtServiceImpl jwtService;
private final ResourceBundleMessageSource source;
public AuthController(
AuthenticationManager authenticationManager,
UserServiceImpl userService,
JwtServiceImpl jwtService,
ResourceBundleMessageSource source) {
this.authenticationManager = authenticationManager;
this.userService = userService;
this.jwtService = jwtService;
this.source = source;
}
/* PUBLIC METHODS */
/* ============================================================ */
/**
* Create user account
*
* @param registerRequestDto
* @return ResponseEntity<String> Response entity (http gestion facilities) that
* contains type of data in response body
* @throws InoteExistingEmailException
* @throws InoteInvalidEmailException
* @throws InoteRoleNotFoundException
* @throws InoteInvalidPasswordFormatException
*
* @author atsuhikoMochizuki
* @throws InoteMailException
* @throws MailException
* @since 19/05/2024
*/
@PostMapping(path = Endpoint.REGISTER)
public ResponseEntity<String> register(
@RequestHeader(name = "Accept-Language", required = false)
final Locale locale,
@RequestBody
final RegisterRequestDto registerRequestDto)
throws MailException,
InoteExistingEmailException,
InoteInvalidEmailException,
InoteRoleNotFoundException,
InoteInvalidPasswordFormatException,
InoteMailException {
User userToRegister = User.builder()
.email(registerRequestDto.username())
.name(registerRequestDto.pseudo())
.password(registerRequestDto.password())
.build();
this.userService.register(userToRegister);
return ResponseEntity
.status(HttpStatusCode.valueOf(201))
.body(source.getMessage(
"activation.ACTIVATION_NEED_ACTIVATION",
null,
locale));
}
/**
* Activate a user using the code provided on registration
*
* @param activationCode a String for activation code provided by email on
* registration
* @return a response entity that contains status code and a msg that concerns
* request
*
* @throws InoteValidationNotFoundException
* @throws InoteUserNotFoundException
* @throws InoteValidationExpiredException
*
* @author atsuhikoMochizuki
* @date 19-05-2024
*/
@PostMapping(path = Endpoint.ACTIVATION)
public ResponseEntity<String> activation(
@RequestHeader(name = "Accept-Language", required = false)
final Locale locale,
@RequestBody
ActivationRequestDto activationRequestDto)
throws InoteValidationNotFoundException,
InoteValidationExpiredException,
InoteUserNotFoundException {
this.userService.activation(activationRequestDto.code());
return ResponseEntity
.status(OK)
.body(source.getMessage(
"user.ACTIVATION_OF_USER_OK",
null,
locale));
}
/**
* Authenticate an user and give him a JWT token for secured actions in app
*
* @param signInRequestDto that contains required user informations
* @return a JWT token if user is authenticated or null
*
* @author atsuhikoMochizuki
* @date 19-05-2024
*/
@PostMapping(path = Endpoint.SIGN_IN)
public ResponseEntity<SignInResponseDto> signIn(@RequestBody SignInRequestDto signInRequestDto) throws AuthenticationException{
Authentication authenticate = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(signInRequestDto.username(),
signInRequestDto.password()));
UserDetails userDetails = (UserDetails) authenticate.getPrincipal();
Map<String, String> map = this.jwtService.generate(userDetails.getUsername());
SignInResponseDto signInReponseDto = new SignInResponseDto(map.get(BEARER), map.get(REFRESH));
return ResponseEntity
.status(OK)
.body(signInReponseDto);
}
/**
* Change password
*
* @param email of user concerned
* @throws InoteMailException
* @throws MailException
*
* @author atsuhikoMochizuki
* @throws InoteInvalidEmailException
* @date 19-05-2024
*/
@PostMapping(path = Endpoint.CHANGE_PASSWORD)
public ResponseEntity<String> changePassword(@RequestBody ChangePasswordRequestDto changePasswordRequestDto)
throws MailException, InoteMailException, InoteInvalidEmailException {
this.userService.changePassword(changePasswordRequestDto.email());
return ResponseEntity
.status(OK)
.body(MessagesEn.ACTIVATION_NEED_ACTIVATION);
}
/**
* Validate the new password with activation code provided on change password
* request
*
* @param requiredInfos NewPasswordDto that contains email, code and
* passwordToChange
* @return status code whith associated comment
*
* @author atsuhikoMochizuki
* @throws InoteInvalidPasswordFormatException
* @throws InoteValidationNotFoundException
* @throws UsernameNotFoundException
* @date 19-05-2024
*/
@PostMapping(path = Endpoint.NEW_PASSWORD)
public ResponseEntity<String> newPassword(@RequestBody NewPasswordRequestDto newPasswordRequestDto)
throws UsernameNotFoundException, InoteValidationNotFoundException, InoteInvalidPasswordFormatException {
this.userService.newPassword(
newPasswordRequestDto.email(),
newPasswordRequestDto.password(),
newPasswordRequestDto.code());
return ResponseEntity
.status(OK)
.body(MessagesEn.NEW_PASSWORD_SUCCESS);
}
/**
* Refresh connection with refresh token
*
* @param refreshConnectionDto the value of refresh token
* @return the value of new bearer and refresh token
* @throws InoteExpiredRefreshTokenException
* @throws InoteJwtNotFoundException
*/
/**
*
* @param refreshRequestDto RefreshConnectionDto
* @return
* @throws InoteJwtNotFoundException
* @throws InoteExpiredRefreshTokenException
*/
@PostMapping(path = Endpoint.REFRESH_TOKEN)
public ResponseEntity<SignInResponseDto> refreshConnectionWithRefreshTokenValue(
@RequestBody RefreshRequestDto refreshRequestDto)
throws InoteJwtNotFoundException, InoteExpiredRefreshTokenException {
Map<String, String> response;
response = this.jwtService.refreshConnectionWithRefreshTokenValue(refreshRequestDto.refresh());
SignInResponseDto signInResponseDto = new SignInResponseDto(
response.get(BEARER),
response.get(REFRESH));
return ResponseEntity
.status(CREATED)
.body(signInResponseDto);
}
/**
* user signout
* @throws InoteJwtNotFoundException
*/
/**
* User sign out
*
* @return status code with associated comment
* @throws InoteJwtNotFoundException
* @author atsuhikoMochizuki
* @date 19-05-2024
*/
@PostMapping(path = Endpoint.SIGN_OUT)
public ResponseEntity<String> signOut() throws InoteJwtNotFoundException {
this.jwtService.signOut();
return ResponseEntity
.status(OK)
.body(MessagesEn.USER_SIGNOUT_SUCCESS);
}
/**
* Get informations of current connected user
*
* @param user
* @return ResponseEntity<Map<String, PublicUserDto>>
* @throws InoteUserNotFoundException
*
* @author AtsuhikoMochizuki
* @date 14-05-2024
*/
@GetMapping(path = Endpoint.GET_CURRENT_USER)
public ResponseEntity<PublicUserRequestDto> getCurrentUser(@AuthenticationPrincipal User user)
throws InoteUserNotFoundException {
if (user == null) {
throw new InoteUserNotFoundException();
}
PublicUserRequestDto publicUserDto = new PublicUserRequestDto(user.getName(), user.getUsername(), null, user.isActif(),
user.getRole().getName().toString());
return ResponseEntity
.status(HttpStatus.OK)
.body(publicUserDto);
}
}