Elffuss BraidHub

kikocis/continue public

main · 19.4 KiBRawPermalink
1// User management system refactored with SOLID principles
2// Original difficulty: 4/5
3
4// Types
5type UserStatus = "active" | "inactive" | "suspended" | "deleted";
6type LogLevel = "debug" | "info" | "warn" | "error";
7
8interface User {
9 id?: number;
10 firstName: string;
11 lastName: string;
12 email: string;
13 status?: UserStatus;
14}
15
16interface Logger {
17 log(message: string, level?: LogLevel): void;
18}
19
20interface Database {
21 query(sql: string, params?: any[]): Promise<any>;
22 close(): void;
23}
24
25interface StorageService {
26 getItem(key: string): string | null;
27 setItem(key: string, value: string): void;
28}
29
30// Configuration interfaces
31interface SystemConfig {
32 debugMode: boolean;
33 apiToken: string;
34}
35
36// Logger implementation - Single Responsibility
37class ConsoleLogger implements Logger {
38 constructor(private notificationService?: NotificationService) {}
39
40 log(message: string, level: LogLevel = "info"): void {
41 const timestamp = new Date().toISOString();
42 console.log(`[${level.toUpperCase()}] ${timestamp}: ${message}`);
43
44 // If error, send notification
45 if (level === "error" && this.notificationService) {
46 this.notificationService.sendNotification(message);
47 }
48 }
49}
50
51// Storage service implementation
52class LocalStorageService implements StorageService {
53 getItem(key: string): string | null {
54 return localStorage.getItem(key);
55 }
56
57 setItem(key: string, value: string): void {
58 localStorage.setItem(key, value);
59 }
60}
61
62// Logger decorator to add persistent storage
63class PersistentLogger implements Logger {
64 constructor(
65 private baseLogger: Logger,
66 private storageService: StorageService,
67 ) {}
68
69 log(message: string, level: LogLevel = "info"): void {
70 // First use the base logger
71 this.baseLogger.log(message, level);
72
73 // Then persist the log
74 const timestamp = new Date().toISOString();
75 try {
76 const logs = JSON.parse(
77 this.storageService.getItem("system_logs") || "[]",
78 );
79 logs.push({ timestamp, level, message });
80 this.storageService.setItem("system_logs", JSON.stringify(logs));
81 } catch (e) {
82 this.baseLogger.log("Failed to persist log", "error");
83 }
84 }
85}
86
87// Notification service - Single Responsibility
88class NotificationService {
89 sendNotification(message: string): void {
90 console.log(`Sending notification: ${message}`);
91 // Simulate email sending
92 setTimeout(() => {
93 console.log("Notification sent!");
94 }, 1000);
95 }
96}
97
98// Database service - Single Responsibility
99class DatabaseService implements Database {
100 private logger: Logger;
101
102 constructor(logger: Logger) {
103 this.logger = logger;
104 this.logger.log("Database service initialized", "debug");
105 }
106
107 query(sql: string, params: any[] = []): Promise<any> {
108 this.logger.log(`Executing query: ${sql}`, "debug");
109 // Simulate database query
110 return Promise.resolve({ rows: [], success: true });
111 }
112
113 close(): void {
114 this.logger.log("Closing database connection", "debug");
115 }
116}
117
118// Config service - Single Responsibility
119class ConfigService {
120 private config: SystemConfig;
121 private storageService: StorageService;
122 private logger: Logger;
123
124 constructor(storageService: StorageService, logger: Logger) {
125 this.storageService = storageService;
126 this.logger = logger;
127 this.config = this.loadConfig();
128 }
129
130 private loadConfig(): SystemConfig {
131 try {
132 return JSON.parse(
133 this.storageService.getItem("user_system_config") || "{}",
134 ) as SystemConfig;
135 } catch (e) {
136 this.logger.log("Failed to load configuration", "error");
137 return { debugMode: false, apiToken: "" };
138 }
139 }
140
141 getConfig(): SystemConfig {
142 return { ...this.config }; // Return a copy to prevent direct modification
143 }
144}
145
146// Authentication service - Single Responsibility
147class AuthService {
148 private db: Database;
149 private logger: Logger;
150 private storageService: StorageService;
151 private currentUserId: number | null = null;
152 private loggedInUsers: User[] = [];
153
154 constructor(db: Database, logger: Logger, storageService: StorageService) {
155 this.db = db;
156 this.logger = logger;
157 this.storageService = storageService;
158 }
159
160 async login(email: string, password: string): Promise<boolean> {
161 try {
162 const result = await this.db.query(
163 "SELECT * FROM users WHERE email = ? AND password_hash = ?",
164 [email, this.hashPassword(password)],
165 );
166
167 if (result.rows.length === 0) {
168 this.logger.log(`Failed login attempt: ${email}`, "warn");
169 return false;
170 }
171
172 const user = result.rows[0];
173 if (user.status !== "active") {
174 this.logger.log(
175 `Login attempt from inactive account: ${email}`,
176 "warn",
177 );
178 return false;
179 }
180
181 // Update state
182 this.currentUserId = user.id;
183 this.loggedInUsers.push(user);
184 this.storageService.setItem("current_user", JSON.stringify(user));
185
186 return true;
187 } catch (err: any) {
188 this.logger.log(`Login error: ${err.message}`, "error");
189 return false;
190 }
191 }
192
193 logout(): void {
194 this.currentUserId = null;
195 this.storageService.setItem("current_user", "");
196 }
197
198 getCurrentUserId(): number | null {
199 return this.currentUserId;
200 }
201
202 private hashPassword(password: string): string {
203 // Not a real hash, just base64 encoding - in a real app, use a proper hashing library
204 return btoa(password);
205 }
206}
207
208// User repository - Data access layer
209class UserRepository {
210 private db: Database;
211 private logger: Logger;
212
213 constructor(db: Database, logger: Logger) {
214 this.db = db;
215 this.logger = logger;
216 }
217
218 async getAllActiveUsers(): Promise<User[]> {
219 try {
220 const result = await this.db.query(
221 'SELECT * FROM users WHERE status != "deleted"',
222 );
223 return result.rows;
224 } catch (err: any) {
225 this.logger.log(`Failed to fetch users: ${err.message}`, "error");
226 throw err;
227 }
228 }
229
230 async createUser(userData: User): Promise<boolean> {
231 try {
232 await this.db.query(
233 "INSERT INTO users (firstName, lastName, email, status) VALUES (?, ?, ?, ?)",
234 [userData.firstName, userData.lastName, userData.email, "active"],
235 );
236 this.logger.log(`User created: ${userData.email}`, "info");
237 return true;
238 } catch (err: any) {
239 this.logger.log(`Failed to create user: ${err.message}`, "error");
240 throw err;
241 }
242 }
243
244 async updateUser(userId: number, userData: User): Promise<boolean> {
245 try {
246 await this.db.query(
247 "UPDATE users SET firstName = ?, lastName = ?, email = ? WHERE id = ?",
248 [userData.firstName, userData.lastName, userData.email, userId],
249 );
250 this.logger.log(`User updated: ${userId}`, "info");
251 return true;
252 } catch (err: any) {
253 this.logger.log(`Failed to update user: ${err.message}`, "error");
254 throw err;
255 }
256 }
257
258 async updateUserStatus(userId: number, status: UserStatus): Promise<boolean> {
259 try {
260 await this.db.query("UPDATE users SET status = ? WHERE id = ?", [
261 status,
262 userId,
263 ]);
264 this.logger.log(`User status updated to ${status}: ${userId}`, "info");
265 return true;
266 } catch (err: any) {
267 this.logger.log(`Failed to update user status: ${err.message}`, "error");
268 throw err;
269 }
270 }
271}
272
273// UI rendering service - Single Responsibility
274class UserUIService {
275 private userRepository: UserRepository;
276 private logger: Logger;
277
278 constructor(userRepository: UserRepository, logger: Logger) {
279 this.userRepository = userRepository;
280 this.logger = logger;
281 }
282
283 async renderUserList(containerId: string): Promise<void> {
284 const container = document.getElementById(containerId);
285 if (!container) {
286 this.logger.log(`Container ${containerId} not found`, "error");
287 return;
288 }
289
290 // Clear container
291 container.innerHTML = "";
292
293 try {
294 // Get users from repository
295 const users = await this.userRepository.getAllActiveUsers();
296
297 // Generate HTML
298 let html = '<ul class="user-list">';
299 users.forEach((user) => {
300 // User status determines CSS class
301 const statusClass = this.getStatusClass(user.status || "active");
302
303 html += `
304 <li class="user-item ${statusClass}" data-id="${user.id}">
305 <div class="user-name">${user.firstName} ${user.lastName}</div>
306 <div class="user-email">${user.email}</div>
307 <div class="user-actions">
308 <button onclick="userController.editUser(${user.id})">Edit</button>
309 <button onclick="userController.deleteUser(${user.id})">Delete</button>
310 ${
311 user.status === "active"
312 ? `<button onclick="userController.suspendUser(${user.id})">Suspend</button>`
313 : `<button onclick="userController.activateUser(${user.id})">Activate</button>`
314 }
315 </div>
316 </li>
317 `;
318 });
319 html += "</ul>";
320
321 container.innerHTML = html;
322 } catch (err: any) {
323 this.logger.log(`Failed to render users: ${err.message}`, "error");
324 container.innerHTML =
325 "<p>Failed to load users. Please try again later.</p>";
326 }
327 }
328
329 private getStatusClass(status: UserStatus): string {
330 switch (status) {
331 case "active":
332 return "user-active";
333 case "inactive":
334 return "user-inactive";
335 case "suspended":
336 return "user-suspended";
337 default:
338 return "";
339 }
340 }
341
342 populateEditForm(form: HTMLFormElement, user: User): void {
343 if (!form) return;
344
345 (form.elements.namedItem("firstName") as HTMLInputElement).value =
346 user.firstName;
347 (form.elements.namedItem("lastName") as HTMLInputElement).value =
348 user.lastName;
349 (form.elements.namedItem("email") as HTMLInputElement).value = user.email;
350 (form.elements.namedItem("userId") as HTMLInputElement).value = String(
351 user.id,
352 );
353
354 // Scroll to form
355 form.scrollIntoView({ behavior: "smooth" });
356 }
357
358 resetForm(formId: string): void {
359 const form = document.getElementById(formId) as HTMLFormElement;
360 if (form) {
361 form.reset();
362 (form.elements.namedItem("userId") as HTMLInputElement).value = "";
363 }
364 }
365}
366
367// User Controller - Handles UI interactions and coordinates services
368class UserController {
369 private userRepository: UserRepository;
370 private userUIService: UserUIService;
371 private logger: Logger;
372 private lastOperation: string = "";
373
374 constructor(
375 userRepository: UserRepository,
376 userUIService: UserUIService,
377 logger: Logger,
378 ) {
379 this.userRepository = userRepository;
380 this.userUIService = userUIService;
381 this.logger = logger;
382 }
383
384 async createUser(userData: User): Promise<void> {
385 try {
386 await this.userRepository.createUser(userData);
387 this.lastOperation = "create";
388 await this.userUIService.renderUserList("user-container");
389 this.userUIService.resetForm("user-form");
390 alert("User created successfully!");
391 } catch (err: any) {
392 alert(`Failed to create user: ${err.message}`);
393 }
394 }
395
396 async updateUser(userId: number, userData: User): Promise<void> {
397 try {
398 await this.userRepository.updateUser(userId, userData);
399 this.lastOperation = "update";
400 await this.userUIService.renderUserList("user-container");
401 this.userUIService.resetForm("user-form");
402 alert("User updated successfully!");
403 } catch (err: any) {
404 alert(`Failed to update user: ${err.message}`);
405 }
406 }
407
408 async editUser(userId: number): Promise<void> {
409 try {
410 const users = await this.userRepository.getAllActiveUsers();
411 const user = users.find((u) => u.id === userId);
412
413 if (!user) {
414 this.logger.log(`User not found: ${userId}`, "error");
415 return;
416 }
417
418 const form = document.getElementById("user-form") as HTMLFormElement;
419 this.userUIService.populateEditForm(form, user);
420 this.lastOperation = "edit";
421 } catch (err: any) {
422 this.logger.log(`Failed to edit user: ${err.message}`, "error");
423 }
424 }
425
426 async suspendUser(userId: number): Promise<void> {
427 if (!confirm("Are you sure you want to suspend this user?")) {
428 return;
429 }
430
431 try {
432 await this.userRepository.updateUserStatus(userId, "suspended");
433 this.lastOperation = "suspend";
434 await this.userUIService.renderUserList("user-container");
435 alert("User suspended successfully!");
436 } catch (err: any) {
437 alert(`Failed to suspend user: ${err.message}`);
438 }
439 }
440
441 async activateUser(userId: number): Promise<void> {
442 try {
443 await this.userRepository.updateUserStatus(userId, "active");
444 this.lastOperation = "activate";
445 await this.userUIService.renderUserList("user-container");
446 alert("User activated successfully!");
447 } catch (err: any) {
448 alert(`Failed to activate user: ${err.message}`);
449 }
450 }
451
452 async deleteUser(userId: number): Promise<void> {
453 if (!confirm("Are you sure you want to delete this user?")) {
454 return;
455 }
456
457 try {
458 await this.userRepository.updateUserStatus(userId, "deleted");
459 this.lastOperation = "delete";
460 await this.userUIService.renderUserList("user-container");
461 alert("User deleted successfully!");
462 } catch (err: any) {
463 alert(`Failed to delete user: ${err.message}`);
464 }
465 }
466
467 getLastOperation(): string {
468 return this.lastOperation;
469 }
470}
471
472// Application class - Manages services and their lifecycle
473class UserManagementApp {
474 private logger: Logger;
475 private db: Database;
476 private userRepository: UserRepository;
477 private userUIService: UserUIService;
478 private userController: UserController;
479 private authService: AuthService;
480 private configService: ConfigService;
481 private storageService: StorageService;
482
483 constructor() {
484 // Initialize services
485 this.storageService = new LocalStorageService();
486 const notificationService = new NotificationService();
487 const baseLogger = new ConsoleLogger(notificationService);
488 this.logger = new PersistentLogger(baseLogger, this.storageService);
489 this.configService = new ConfigService(this.storageService, this.logger);
490
491 // Initialize database
492 this.db = new DatabaseService(this.logger);
493
494 // Initialize user repository
495 this.userRepository = new UserRepository(this.db, this.logger);
496
497 // Initialize UI service
498 this.userUIService = new UserUIService(this.userRepository, this.logger);
499
500 // Initialize controller
501 this.userController = new UserController(
502 this.userRepository,
503 this.userUIService,
504 this.logger,
505 );
506
507 // Initialize auth service
508 this.authService = new AuthService(
509 this.db,
510 this.logger,
511 this.storageService,
512 );
513
514 // Expose controller to global scope
515 (window as any).userController = this.userController;
516
517 this.setupEventListeners();
518 this.setupErrorHandlers();
519 }
520
521 private setupEventListeners(): void {
522 window.addEventListener("load", () => {
523 const userForm = document.getElementById("user-form");
524 if (userForm) {
525 userForm.addEventListener(
526 "submit",
527 this.handleUserFormSubmit.bind(this),
528 );
529 }
530
531 // Initialize user list
532 this.userUIService.renderUserList("user-container");
533 });
534 }
535
536 private setupErrorHandlers(): void {
537 window.onerror = (msg, url, line) => {
538 this.logger.log(`Global error: ${msg} at ${url}:${line}`, "error");
539 return false;
540 };
541 }
542
543 private handleUserFormSubmit(event: Event): void {
544 event.preventDefault();
545 const form = event.target as HTMLFormElement;
546
547 const userData: User = {
548 firstName: (form.elements.namedItem("firstName") as HTMLInputElement)
549 .value,
550 lastName: (form.elements.namedItem("lastName") as HTMLInputElement).value,
551 email: (form.elements.namedItem("email") as HTMLInputElement).value,
552 };
553
554 const userId = (form.elements.namedItem("userId") as HTMLInputElement)
555 .value;
556
557 if (userId) {
558 this.userController.updateUser(parseInt(userId), userData);
559 } else {
560 this.userController.createUser(userData);
561 }
562 }
563
564 async login(email: string, password: string): Promise<boolean> {
565 const success = await this.authService.login(email, password);
566 if (success) {
567 // Redirect to dashboard
568 window.location.href = "/dashboard.html";
569 } else {
570 alert("Invalid email or password");
571 }
572 return success;
573 }
574
575 cleanup(): void {
576 this.logger.log("Cleaning up resources", "debug");
577 this.db.close();
578 }
579}
580
581// Initialize the application
582const app = new UserManagementApp();
583
584/*
585Code Smells in the Original Code
586
587Violation of Single Responsibility Principle:
588
589UserManager was a "God class" handling database connection, UI rendering, user CRUD operations, authentication, and logging
590Logger mixed logging with email notifications
591User operations contained both business logic and UI manipulation
592
593Violation of Open/Closed Principle:
594
595Hardcoded dependencies that couldn't be extended without modifying code
596Direct UI manipulations embedded in business logic
597
598High Coupling:
599
600Direct references to the DOM throughout the codebase
601Global state used across different operations
602Direct database access from UI-related methods
603
604Code Duplication:
605
606Similar code repeated in suspendUser, activateUser, and deleteUser methods
607Repetitive UI update logic
608
609Poor Security Practices:
610
611API tokens exposed in console logs
612Weak password handling (just base64 encoding)
613Direct SQL queries vulnerable to injection
614
615
616Global Variables and Side Effects:
617
618Multiple global variables (currentUserID, loggedInUsers, etc.)
619Global DOM event handlers
620
621
622Improvements Made
623
624Applied Single Responsibility Principle:
625
626Created specialized classes for each concern:
627
628Logger and PersistentLogger for logging
629NotificationService for alerts/notifications
630DatabaseService for database operations
631UserRepository for user data access
632UserUIService for rendering UI
633UserController for handling user actions
634AuthService for authentication
635ConfigService for configuration management
636
637
638Applied Open/Closed Principle:
639
640Used interfaces (Logger, Database, StorageService) to define contracts
641Implemented dependency injection to allow for extensions without modifications
642Created the decorator pattern for logging (base logger + persistent storage)
643
644
645Applied Interface Segregation Principle:
646
647Created focused interfaces (e.g., Logger only handles logging)
648Split large interfaces into smaller, more specific ones
649
650
651Applied Dependency Inversion Principle:
652
653High-level modules depend on abstractions, not concrete implementations
654Dependencies are injected through constructors
655Centralized service initialization in the UserManagementApp class
656
657
658Applied Liskov Substitution Principle:
659
660Classes implementing interfaces fully satisfy their contracts
661Derived classes (like PersistentLogger) maintain the behavior expected from the base interface
662
663
664Reduced Duplication:
665
666Consolidated common user operations in the repository
667Created reusable UI methods
668Extracted common logic into shared methods
669
670
671Improved Security:
672
673Removed sensitive information from console logs
674Added proper encapsulation of sensitive data
675Note: The password hashing is still weak (commented as such) but is separated for easy replacement
676
677
678Better State Management:
679
680Eliminated global state
681Encapsulated state within appropriate classes
682Provided proper methods for state access
683
684
685Improved Error Handling:
686
687Consistent error handling approach
688Proper propagation of errors
689Clear error messages
690
691
692Proper Separation of Concerns:
693
694UI logic separated from business logic
695Data access separated from business rules
696Authentication separated from user management
697*/