-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdminController.java
More file actions
323 lines (285 loc) · 12.7 KB
/
Copy pathAdminController.java
File metadata and controls
323 lines (285 loc) · 12.7 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
package com.crimeLink.analyzer.controller;
import com.crimeLink.analyzer.dto.AuditLogDTO;
import com.crimeLink.analyzer.entity.BackupMetadata;
import com.crimeLink.analyzer.entity.LoginAudit;
import com.crimeLink.analyzer.entity.User;
import com.crimeLink.analyzer.repository.LoginAuditRepository;
import com.crimeLink.analyzer.repository.UserRepository;
import com.crimeLink.analyzer.service.BackupService;
import com.crimeLink.analyzer.service.SystemSettingsService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/api/admin")
@RequiredArgsConstructor
public class AdminController {
private final UserRepository userRepo;
private final LoginAuditRepository auditRepo;
private final PasswordEncoder passwordEncoder;
private final BackupService backupService;
private final SystemSettingsService settingsService;
// ════════════════════════════════════════════════════════════════
// USER MANAGEMENT (Admin + OIC)
// ════════════════════════════════════════════════════════════════
/**
* Get all users or filter by role/status
* GET /api/admin/users?role=Admin&status=Active
*/
@GetMapping("/users")
public ResponseEntity<List<User>> getUsers(
@RequestParam(required = false) String role,
@RequestParam(required = false) String status) {
List<User> users;
if (role != null && status != null) {
users = userRepo.findByRoleAndStatus(role, status);
} else if (role != null) {
users = userRepo.findByRole(role);
} else if (status != null) {
users = userRepo.findByRoleAndStatus(null, status);
} else {
users = userRepo.findAll();
}
return ResponseEntity.ok(users);
}
/**
* Create new user
* POST /api/admin/users
*/
@PostMapping("/users")
public ResponseEntity<?> createUser(@RequestBody User user) {
try {
// Check if email already exists
if (userRepo.existsByEmail(user.getEmail())) {
return ResponseEntity.badRequest()
.body(Map.of("message", "Email already exists"));
}
// Hash password
if (user.getPasswordHash() != null && !user.getPasswordHash().isEmpty()) {
user.setPasswordHash(passwordEncoder.encode(user.getPasswordHash()));
}
User savedUser = userRepo.save(user);
return ResponseEntity.ok(savedUser);
} catch (Exception e) {
return ResponseEntity.badRequest()
.body(Map.of("message", "Failed to create user: " + e.getMessage()));
}
}
/**
* Update existing user
* PUT /api/admin/users/{id}
*/
@PutMapping("/users/{id}")
public ResponseEntity<?> updateUser(
@PathVariable Integer id,
@RequestBody User updatedUser) {
return userRepo.findById(id)
.map(user -> {
user.setName(updatedUser.getName());
user.setEmail(updatedUser.getEmail());
user.setDob(updatedUser.getDob());
user.setGender(updatedUser.getGender());
user.setAddress(updatedUser.getAddress());
user.setRole(updatedUser.getRole());
user.setBadgeNo(updatedUser.getBadgeNo());
user.setStatus(updatedUser.getStatus());
// Only update password if provided
if (updatedUser.getPasswordHash() != null
&& !updatedUser.getPasswordHash().isEmpty()) {
user.setPasswordHash(
passwordEncoder.encode(updatedUser.getPasswordHash()));
}
User saved = userRepo.save(user);
return ResponseEntity.ok(saved);
})
.orElse(ResponseEntity.notFound().build());
}
/**
* Deactivate user (set status to Inactive)
* DELETE /api/admin/users/{id}
*/
@DeleteMapping("/users/{id}")
public ResponseEntity<?> deactivateUser(@PathVariable Integer id) {
return userRepo.findById(id)
.map(user -> {
user.setStatus("Inactive");
userRepo.save(user);
return ResponseEntity.ok(
Map.of("message", "User deactivated successfully"));
})
.orElse(ResponseEntity.notFound().build());
}
// ════════════════════════════════════════════════════════════════
// AUDIT LOGS (Admin + OIC)
// ════════════════════════════════════════════════════════════════
/**
* Get audit logs
* GET /api/admin/audit-logs?limit=100&offset=0
*/
@GetMapping("/audit-logs")
public ResponseEntity<List<AuditLogDTO>> getAuditLogs(
@RequestParam(defaultValue = "100") int limit,
@RequestParam(defaultValue = "0") int offset) {
PageRequest pageRequest = PageRequest.of(
offset / limit,
limit,
Sort.by(Sort.Direction.DESC, "loginTime")
);
List<LoginAudit> logs = auditRepo.findAll(pageRequest).getContent();
// Map LoginAudit to AuditLogDTO with user names
List<AuditLogDTO> dtoList = logs.stream().map(log -> {
AuditLogDTO dto = new AuditLogDTO();
dto.setId(log.getAuditId());
dto.setUserId(log.getUserId());
dto.setEmail(log.getEmail());
dto.setIpAddress(log.getIpAddress());
dto.setLoginTime(log.getLoginTime() != null ? log.getLoginTime().toString() : null);
dto.setLogoutTime(null); // LoginAudit doesn't track logout time
dto.setSuccess(log.getSuccess());
// Determine action based on success and failure reason
if (log.getSuccess()) {
dto.setAction("Login Success");
} else {
String reason = log.getFailureReason();
if (reason != null) {
dto.setAction("Login Failed: " + reason);
} else {
dto.setAction("Login Failed");
}
}
// Get user name from userId if available
if (log.getUserId() != null) {
userRepo.findById(log.getUserId()).ifPresent(user -> {
dto.setUserName(user.getName());
});
} else {
// Use email as fallback
dto.setUserName(log.getEmail());
}
return dto;
}).collect(Collectors.toList());
return ResponseEntity.ok(dtoList);
}
// ════════════════════════════════════════════════════════════════
// BACKUP & RESTORE (Admin only)
// ════════════════════════════════════════════════════════════════
/**
* Trigger database backup
* POST /api/admin/backup
*/
@PostMapping("/backup")
@PreAuthorize("hasRole('Admin')")
public ResponseEntity<?> triggerBackup(Authentication authentication) {
try {
String userEmail = authentication.getName();
BackupMetadata metadata = backupService.createBackup(userEmail);
return ResponseEntity.ok(Map.of(
"message", "Backup created successfully",
"file", metadata.getFilename(),
"sizeBytes", metadata.getSizeBytes(),
"createdAt", metadata.getCreatedAt().toString()
));
} catch (Exception e) {
return ResponseEntity.status(500).body(
Map.of("message", "Backup failed: " + e.getMessage())
);
}
}
/**
* Restore from backup
* POST /api/admin/restore
*/
@PostMapping("/restore")
@PreAuthorize("hasRole('Admin')")
public ResponseEntity<?> restoreBackup(
@RequestBody Map<String, String> request,
Authentication authentication) {
try {
String filename = request.get("filename");
if (filename == null || filename.isBlank()) {
return ResponseEntity.badRequest()
.body(Map.of("message", "Filename is required"));
}
String userEmail = authentication.getName();
backupService.restoreBackup(filename, userEmail);
return ResponseEntity.ok(Map.of(
"message", "Database restored successfully from " + filename
));
} catch (IllegalArgumentException e) {
return ResponseEntity.badRequest().body(
Map.of("message", e.getMessage())
);
} catch (Exception e) {
return ResponseEntity.status(500).body(
Map.of("message", "Restore failed: " + e.getMessage())
);
}
}
/**
* List all available backups
* GET /api/admin/backups
*/
@GetMapping("/backups")
@PreAuthorize("hasRole('Admin')")
public ResponseEntity<List<BackupMetadata>> listBackups() {
return ResponseEntity.ok(backupService.listBackups());
}
// ════════════════════════════════════════════════════════════════
// SYSTEM SETTINGS (Admin only)
// ════════════════════════════════════════════════════════════════
/**
* Get all system settings
* GET /api/admin/settings
*/
@GetMapping("/settings")
@PreAuthorize("hasRole('Admin')")
public ResponseEntity<Map<String, String>> getSettings() {
return ResponseEntity.ok(settingsService.getAllSettings());
}
/**
* Update system settings
* PUT /api/admin/settings
*/
@PutMapping("/settings")
@PreAuthorize("hasRole('Admin')")
public ResponseEntity<?> updateSettings(@RequestBody Map<String, String> settings) {
try {
Map<String, String> updated = settingsService.updateSettings(settings);
return ResponseEntity.ok(Map.of(
"message", "Settings saved successfully",
"settings", updated
));
} catch (IllegalArgumentException e) {
return ResponseEntity.badRequest().body(
Map.of("message", e.getMessage())
);
} catch (Exception e) {
return ResponseEntity.status(500).body(
Map.of("message", "Failed to save settings: " + e.getMessage())
);
}
}
// ════════════════════════════════════════════════════════════════
// SYSTEM HEALTH (public)
// ════════════════════════════════════════════════════════════════
/**
* Get system health
* GET /api/admin/health
*/
@GetMapping("/health")
public ResponseEntity<?> getSystemHealth() {
return ResponseEntity.ok(Map.of(
"status", "UP",
"database", "Connected",
"timestamp", java.time.LocalDateTime.now().toString()
));
}
}