Skip to content
This repository was archived by the owner on Nov 23, 2025. It is now read-only.

Commit cd79dc3

Browse files
committed
feat: Add API endpoints and service logic for creating admin and employee accounts.
1 parent 4d9422e commit cd79dc3

6 files changed

Lines changed: 278 additions & 261 deletions

File tree

auth-service/src/main/java/com/techtorque/auth_service/controller/AuthController.java

Lines changed: 72 additions & 95 deletions
Original file line numberDiff line numberDiff line change
@@ -23,220 +23,194 @@
2323
* Handles login, registration, and health check requests
2424
*/
2525
@RestController
26-
// Class-level request mapping removed — gateway strips prefixes before forwarding
26+
// Class-level request mapping removed — gateway strips prefixes before
27+
// forwarding
2728
// @RequestMapping("/api/v1/auth")
2829
// CORS handled at the API Gateway; remove @CrossOrigin to avoid conflicts
2930
// @CrossOrigin(origins = "*", maxAge = 3600)
3031
@Tag(name = "Authentication", description = "Authentication and user management endpoints")
3132
public class AuthController {
32-
33+
3334
@Autowired
3435
private AuthService authService;
35-
36+
3637
// --- NEW DEPENDENCY ---
3738
// We need UserService to call the createEmployee method
3839
@Autowired
3940
private UserService userService;
40-
41+
4142
/**
4243
* User login endpoint
44+
*
4345
* @param loginRequest Login credentials
4446
* @return JWT token and user details
4547
*/
46-
@Operation(
47-
summary = "User Login",
48-
description = "Authenticate user with username/email and password. Returns JWT token on success. Rate limited to prevent brute force attacks."
49-
)
48+
@Operation(summary = "User Login", description = "Authenticate user with username/email and password. Returns JWT token on success. Rate limited to prevent brute force attacks.")
5049
@ApiResponses(value = {
51-
@ApiResponse(responseCode = "200", description = "Login successful, JWT token returned"),
52-
@ApiResponse(responseCode = "401", description = "Invalid credentials or account locked"),
53-
@ApiResponse(responseCode = "400", description = "Invalid request format")
50+
@ApiResponse(responseCode = "200", description = "Login successful, JWT token returned"),
51+
@ApiResponse(responseCode = "401", description = "Invalid credentials or account locked"),
52+
@ApiResponse(responseCode = "400", description = "Invalid request format")
5453
})
5554
@PostMapping("/login")
56-
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest, HttpServletRequest request) {
55+
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest,
56+
HttpServletRequest request) {
5757
LoginResponse loginResponse = authService.authenticateUser(loginRequest, request);
5858
return ResponseEntity.ok(loginResponse);
5959
}
60-
60+
6161
/**
6262
* User registration endpoint
63+
*
6364
* @param registerRequest Registration details
6465
* @return Success message
6566
*/
66-
@Operation(
67-
summary = "Register New User",
68-
description = "Register a new customer account. Email verification is required before login."
69-
)
67+
@Operation(summary = "Register New User", description = "Register a new customer account. Email verification is required before login.")
7068
@ApiResponses(value = {
71-
@ApiResponse(responseCode = "201", description = "Registration successful, verification email sent"),
72-
@ApiResponse(responseCode = "400", description = "Invalid request or username/email already exists")
69+
@ApiResponse(responseCode = "201", description = "Registration successful, verification email sent"),
70+
@ApiResponse(responseCode = "400", description = "Invalid request or username/email already exists")
7371
})
7472
@PostMapping("/register")
7573
public ResponseEntity<?> registerUser(@Valid @RequestBody RegisterRequest registerRequest) {
7674
String message = authService.registerUser(registerRequest);
7775
return ResponseEntity.status(HttpStatus.CREATED).body(ApiSuccess.of(message));
7876
}
79-
77+
8078
/**
8179
* Verify email with token
8280
*/
83-
@Operation(
84-
summary = "Verify Email",
85-
description = "Verify user email address with token sent via email. Returns JWT tokens on success."
86-
)
81+
@Operation(summary = "Verify Email", description = "Verify user email address with token sent via email. Returns JWT tokens on success.")
8782
@ApiResponses(value = {
88-
@ApiResponse(responseCode = "200", description = "Email verified successfully, user logged in"),
89-
@ApiResponse(responseCode = "400", description = "Invalid, expired, or already used token")
83+
@ApiResponse(responseCode = "200", description = "Email verified successfully, user logged in"),
84+
@ApiResponse(responseCode = "400", description = "Invalid, expired, or already used token")
9085
})
9186
@PostMapping("/verify-email")
92-
public ResponseEntity<?> verifyEmail(@Valid @RequestBody VerifyEmailRequest request, HttpServletRequest httpRequest) {
87+
public ResponseEntity<?> verifyEmail(@Valid @RequestBody VerifyEmailRequest request,
88+
HttpServletRequest httpRequest) {
9389
LoginResponse response = authService.verifyEmail(request.getToken(), httpRequest);
9490
return ResponseEntity.ok(response);
9591
}
96-
92+
9793
/**
9894
* Resend verification email
9995
*/
100-
@Operation(
101-
summary = "Resend Verification Email",
102-
description = "Resend verification email to the specified address"
103-
)
96+
@Operation(summary = "Resend Verification Email", description = "Resend verification email to the specified address")
10497
@ApiResponses(value = {
105-
@ApiResponse(responseCode = "200", description = "Verification email sent successfully"),
106-
@ApiResponse(responseCode = "400", description = "Email not found or already verified")
98+
@ApiResponse(responseCode = "200", description = "Verification email sent successfully"),
99+
@ApiResponse(responseCode = "400", description = "Email not found or already verified")
107100
})
108101
@PostMapping("/resend-verification")
109102
public ResponseEntity<?> resendVerification(@Valid @RequestBody ResendVerificationRequest request) {
110103
String message = authService.resendVerificationEmail(request.getEmail());
111104
return ResponseEntity.ok(ApiSuccess.of(message));
112105
}
113-
106+
114107
/**
115108
* Refresh JWT token
116109
*/
117-
@Operation(
118-
summary = "Refresh Access Token",
119-
description = "Get a new access token using a valid refresh token"
120-
)
110+
@Operation(summary = "Refresh Access Token", description = "Get a new access token using a valid refresh token")
121111
@ApiResponses(value = {
122-
@ApiResponse(responseCode = "200", description = "New access token generated"),
123-
@ApiResponse(responseCode = "401", description = "Invalid, expired, or revoked refresh token")
112+
@ApiResponse(responseCode = "200", description = "New access token generated"),
113+
@ApiResponse(responseCode = "401", description = "Invalid, expired, or revoked refresh token")
124114
})
125115
@PostMapping("/refresh")
126116
public ResponseEntity<?> refreshToken(@Valid @RequestBody RefreshTokenRequest request) {
127117
LoginResponse response = authService.refreshToken(request.getRefreshToken());
128118
return ResponseEntity.ok(response);
129119
}
130-
120+
131121
/**
132122
* Logout endpoint
133123
*/
134-
@Operation(
135-
summary = "Logout User",
136-
description = "Logout user and revoke refresh token",
137-
security = @SecurityRequirement(name = "bearerAuth")
138-
)
124+
@Operation(summary = "Logout User", description = "Logout user and revoke refresh token", security = @SecurityRequirement(name = "bearerAuth"))
139125
@ApiResponses(value = {
140-
@ApiResponse(responseCode = "200", description = "Logged out successfully"),
141-
@ApiResponse(responseCode = "400", description = "Invalid refresh token")
126+
@ApiResponse(responseCode = "200", description = "Logged out successfully"),
127+
@ApiResponse(responseCode = "400", description = "Invalid refresh token")
142128
})
143129
@PostMapping("/logout")
144130
public ResponseEntity<?> logout(@Valid @RequestBody LogoutRequest request) {
145131
authService.logout(request.getRefreshToken());
146132
return ResponseEntity.ok(ApiSuccess.of("Logged out successfully"));
147133
}
148-
134+
149135
/**
150136
* Forgot password - request reset
151137
*/
152-
@Operation(
153-
summary = "Forgot Password",
154-
description = "Request password reset email"
155-
)
138+
@Operation(summary = "Forgot Password", description = "Request password reset email")
156139
@ApiResponses(value = {
157-
@ApiResponse(responseCode = "200", description = "Password reset email sent"),
158-
@ApiResponse(responseCode = "404", description = "Email not found")
140+
@ApiResponse(responseCode = "200", description = "Password reset email sent"),
141+
@ApiResponse(responseCode = "404", description = "Email not found")
159142
})
160143
@PostMapping("/forgot-password")
161144
public ResponseEntity<?> forgotPassword(@Valid @RequestBody ForgotPasswordRequest request) {
162145
String message = authService.forgotPassword(request.getEmail());
163146
return ResponseEntity.ok(ApiSuccess.of(message));
164147
}
165-
148+
166149
/**
167150
* Reset password with token
168151
*/
169-
@Operation(
170-
summary = "Reset Password",
171-
description = "Reset password using token from email"
172-
)
152+
@Operation(summary = "Reset Password", description = "Reset password using token from email")
173153
@ApiResponses(value = {
174-
@ApiResponse(responseCode = "200", description = "Password reset successfully"),
175-
@ApiResponse(responseCode = "400", description = "Invalid, expired, or already used token")
154+
@ApiResponse(responseCode = "200", description = "Password reset successfully"),
155+
@ApiResponse(responseCode = "400", description = "Invalid, expired, or already used token")
176156
})
177157
@PostMapping("/reset-password")
178158
public ResponseEntity<?> resetPassword(@Valid @RequestBody ResetPasswordWithTokenRequest request) {
179159
String message = authService.resetPassword(request.getToken(), request.getNewPassword());
180160
return ResponseEntity.ok(ApiSuccess.of(message));
181161
}
182-
162+
183163
/**
184164
* Change password (authenticated users)
185165
* Note: This endpoint moved to UserController as /users/me/change-password
186166
* Keeping for backwards compatibility
187167
*/
188-
@Operation(
189-
summary = "Change Password",
190-
description = "Change password for authenticated user. Use current password for verification.",
191-
security = @SecurityRequirement(name = "bearerAuth")
192-
)
168+
@Operation(summary = "Change Password", description = "Change password for authenticated user. Use current password for verification.", security = @SecurityRequirement(name = "bearerAuth"))
193169
@ApiResponses(value = {
194-
@ApiResponse(responseCode = "200", description = "Password changed successfully"),
195-
@ApiResponse(responseCode = "400", description = "Invalid current password"),
196-
@ApiResponse(responseCode = "401", description = "Authentication required")
170+
@ApiResponse(responseCode = "200", description = "Password changed successfully"),
171+
@ApiResponse(responseCode = "400", description = "Invalid current password"),
172+
@ApiResponse(responseCode = "401", description = "Authentication required")
197173
})
198174
@PutMapping("/change-password")
199175
@PreAuthorize("hasRole('CUSTOMER') or hasRole('EMPLOYEE') or hasRole('ADMIN') or hasRole('SUPER_ADMIN')")
200176
public ResponseEntity<?> changePassword(@Valid @RequestBody ChangePasswordRequest changeRequest) {
201177
try {
202-
Authentication authentication = org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication();
178+
Authentication authentication = org.springframework.security.core.context.SecurityContextHolder.getContext()
179+
.getAuthentication();
203180
String username = authentication.getName();
204-
205-
userService.changeUserPassword(username, changeRequest.getCurrentPassword(), changeRequest.getNewPassword());
181+
182+
userService.changeUserPassword(username, changeRequest.getCurrentPassword(),
183+
changeRequest.getNewPassword());
206184
return ResponseEntity.ok(ApiSuccess.of("Password changed successfully"));
207185
} catch (RuntimeException e) {
208186
return ResponseEntity.badRequest().body(ApiSuccess.of("Error: " + e.getMessage()));
209187
}
210188
}
211189

212-
213190
// --- NEW ENDPOINT FOR CREATING EMPLOYEES ---
214191
/**
215192
* ADMIN-ONLY endpoint for creating a new employee account.
193+
*
216194
* @param createEmployeeRequest DTO with username, email, and password.
217195
* @return A success or error message.
218196
*/
219-
@Operation(
220-
summary = "Create Employee Account",
221-
description = "Create a new employee account. Requires ADMIN role.",
222-
security = @SecurityRequirement(name = "bearerAuth")
223-
)
197+
@Operation(summary = "Create Employee Account", description = "Create a new employee account. Requires ADMIN role.", security = @SecurityRequirement(name = "bearerAuth"))
224198
@ApiResponses(value = {
225-
@ApiResponse(responseCode = "201", description = "Employee account created successfully"),
226-
@ApiResponse(responseCode = "400", description = "Invalid request or username already exists"),
227-
@ApiResponse(responseCode = "401", description = "Authentication required"),
228-
@ApiResponse(responseCode = "403", description = "Admin role required")
199+
@ApiResponse(responseCode = "201", description = "Employee account created successfully"),
200+
@ApiResponse(responseCode = "400", description = "Invalid request or username already exists"),
201+
@ApiResponse(responseCode = "401", description = "Authentication required"),
202+
@ApiResponse(responseCode = "403", description = "Admin role required")
229203
})
230204
@PostMapping("/users/employee")
231205
@PreAuthorize("hasRole('ADMIN') or hasRole('SUPER_ADMIN')")
232206
public ResponseEntity<?> createEmployee(@Valid @RequestBody CreateEmployeeRequest createEmployeeRequest) {
233207
try {
234208
// Now we are calling the method that was previously unused
235209
userService.createEmployee(
236-
createEmployeeRequest.getUsername(),
237-
createEmployeeRequest.getEmail(),
238-
createEmployeeRequest.getPassword()
239-
);
210+
createEmployeeRequest.getUsername(),
211+
createEmployeeRequest.getEmail(),
212+
createEmployeeRequest.getPassword(),
213+
createEmployeeRequest.getFullName());
240214
return ResponseEntity.status(HttpStatus.CREATED)
241215
.body(ApiSuccess.of("Employee account created successfully!"));
242216
} catch (RuntimeException e) {
@@ -248,6 +222,7 @@ public ResponseEntity<?> createEmployee(@Valid @RequestBody CreateEmployeeReques
248222
// --- NEW ENDPOINT FOR CREATING ADMINS (SUPER_ADMIN ONLY) ---
249223
/**
250224
* SUPER_ADMIN-ONLY endpoint for creating a new admin account.
225+
*
251226
* @param createAdminRequest DTO with username, email, and password.
252227
* @return A success or error message.
253228
*/
@@ -256,28 +231,30 @@ public ResponseEntity<?> createEmployee(@Valid @RequestBody CreateEmployeeReques
256231
public ResponseEntity<?> createAdmin(@Valid @RequestBody CreateAdminRequest createAdminRequest) {
257232
try {
258233
userService.createAdmin(
259-
createAdminRequest.getUsername(),
260-
createAdminRequest.getEmail(),
261-
createAdminRequest.getPassword()
262-
);
234+
createAdminRequest.getUsername(),
235+
createAdminRequest.getEmail(),
236+
createAdminRequest.getPassword(),
237+
createAdminRequest.getFullName());
263238
return ResponseEntity.status(HttpStatus.CREATED)
264239
.body(ApiSuccess.of("Admin account created successfully!"));
265240
} catch (RuntimeException e) {
266241
return ResponseEntity.badRequest().body(ApiSuccess.of("Error: " + e.getMessage()));
267242
}
268243
}
269-
244+
270245
/**
271246
* Health check endpoint
247+
*
272248
* @return Service status
273249
*/
274250
@GetMapping("/health")
275251
public ResponseEntity<?> health() {
276252
return ResponseEntity.ok(ApiSuccess.of("Authentication Service is running!"));
277253
}
278-
254+
279255
/**
280256
* Test endpoint for authenticated users
257+
*
281258
* @return Test message
282259
*/
283260
@GetMapping("/test")

auth-service/src/main/java/com/techtorque/auth_service/dto/request/CreateAdminRequest.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,13 @@
1414
@AllArgsConstructor
1515
@Builder
1616
public class CreateAdminRequest {
17-
17+
1818
private String username;
1919
private String email;
2020
private String password;
21-
21+
22+
private String fullName;
23+
2224
// Optional: Additional admin-specific fields
2325
private String firstName;
2426
private String lastName;

auth-service/src/main/java/com/techtorque/auth_service/dto/request/CreateEmployeeRequest.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,13 @@
1414
@AllArgsConstructor
1515
@Builder
1616
public class CreateEmployeeRequest {
17-
17+
1818
private String username;
1919
private String email;
2020
private String password;
21-
21+
22+
private String fullName;
23+
2224
// Optional: Additional employee-specific fields
2325
private String firstName;
2426
private String lastName;

0 commit comments

Comments
 (0)