Elffuss BraidHub

kikocis/continue public

main · 12.5 KiBRawPermalink
1// User management system with mixed concerns and entangled logic
2// Difficulty: 4/5
3
4type UserStatus = "active" | "inactive" | "suspended" | "deleted";
5type LogLevel = "debug" | "info" | "warn" | "error";
6
7// Global variables
8let currentUserID: number | null = null;
9let loggedInUsers: any[] = [];
10let systemStatus = "online";
11let DEBUG_MODE = true;
12
13// Main user class that handles everything
14class UserManager {
15 private users: any[] = [];
16 private db: any = null;
17 private logger: any = null;
18 private apiToken: string = "secret-token-1234";
19 public lastOperation: string = "";
20
21 constructor() {
22 this.initializeSystem();
23 // Connect to database directly in constructor
24 this.connectToDatabase();
25 console.log("UserManager initialized!");
26 }
27
28 // Mixed responsibility - initialization, logging, and notification
29 private initializeSystem() {
30 // Set up logging
31 this.logger = {
32 log: function (message: string, level: LogLevel = "info") {
33 const timestamp = new Date().toISOString();
34 console.log(`[${level.toUpperCase()}] ${timestamp}: ${message}`);
35
36 // Store logs in localStorage too
37 const logs = JSON.parse(localStorage.getItem("system_logs") || "[]");
38 logs.push({ timestamp, level, message });
39 localStorage.setItem("system_logs", JSON.stringify(logs));
40
41 // If error, send notification
42 if (level === "error") {
43 // Send email notification
44 this.sendEmailAlert(message);
45 }
46 },
47
48 sendEmailAlert: function (message: string) {
49 console.log(`Sending email alert: ${message}`);
50 // Simulate email sending
51 setTimeout(() => {
52 console.log("Email sent!");
53 }, 1000);
54 },
55 };
56
57 // Load configuration
58 let config;
59 try {
60 config = JSON.parse(localStorage.getItem("user_system_config") || "{}");
61 DEBUG_MODE = config.debugMode || DEBUG_MODE;
62 this.apiToken = config.apiToken || this.apiToken;
63 } catch (e) {
64 this.logger.log("Failed to load configuration", "error");
65 }
66 }
67
68 // Database connection hardcoded
69 private connectToDatabase() {
70 this.logger.log("Connecting to database...", "debug");
71
72 // Simulate database connection
73 this.db = {
74 query: function (sql: string, params: any[] = []) {
75 console.log(`Executing query: ${sql}`);
76 console.log("Params:", params);
77 return Promise.resolve({ rows: [], success: true });
78 },
79
80 close: function () {
81 console.log("Closing database connection");
82 },
83 };
84
85 // Log connection info to console in plain text
86 console.log(`Connected to database with token: ${this.apiToken}`);
87
88 // Save connection timestamp
89 localStorage.setItem("last_db_connection", new Date().toISOString());
90 }
91
92 // UI generation mixed with business logic
93 public renderUserList(containerId: string) {
94 const container = document.getElementById(containerId);
95 if (!container) {
96 this.logger.log(`Container ${containerId} not found`, "error");
97 return;
98 }
99
100 // Clear container
101 container.innerHTML = "";
102
103 // Get users - mixing data fetching and rendering
104 this.db
105 .query('SELECT * FROM users WHERE status != "deleted"')
106 .then((result: any) => {
107 this.users = result.rows;
108
109 // Generate HTML - UI logic mixed with business logic
110 let html = '<ul class="user-list">';
111 this.users.forEach((user) => {
112 // User status determines CSS class
113 let statusClass = "";
114 switch (user.status) {
115 case "active":
116 statusClass = "user-active";
117 break;
118 case "inactive":
119 statusClass = "user-inactive";
120 break;
121 case "suspended":
122 statusClass = "user-suspended";
123 break;
124 }
125
126 html += `
127 <li class="user-item ${statusClass}" data-id="${user.id}">
128 <div class="user-name">${user.firstName} ${user.lastName}</div>
129 <div class="user-email">${user.email}</div>
130 <div class="user-actions">
131 <button onclick="userManager.editUser(${user.id})">Edit</button>
132 <button onclick="userManager.deleteUser(${user.id})">Delete</button>
133 ${
134 user.status === "active"
135 ? `<button onclick="userManager.suspendUser(${user.id})">Suspend</button>`
136 : `<button onclick="userManager.activateUser(${user.id})">Activate</button>`
137 }
138 </div>
139 </li>
140 `;
141 });
142 html += "</ul>";
143
144 container.innerHTML = html;
145 })
146 .catch((err: any) => {
147 this.logger.log(`Failed to fetch users: ${err.message}`, "error");
148 container.innerHTML =
149 "<p>Failed to load users. Please try again later.</p>";
150 });
151 }
152
153 // No validation, directly manipulating UI and data
154 public createUser(userData: any) {
155 // Directly create user without validation
156 this.db
157 .query(
158 "INSERT INTO users (firstName, lastName, email, status) VALUES (?, ?, ?, ?)",
159 [userData.firstName, userData.lastName, userData.email, "active"],
160 )
161 .then((result: any) => {
162 this.logger.log(`User created: ${userData.email}`, "info");
163
164 // Update UI directly here
165 this.renderUserList("user-container");
166
167 // Update global state
168 this.lastOperation = "create";
169
170 // Clear form - direct DOM manipulation
171 document.getElementById("user-form")?.reset();
172
173 // Show success message
174 alert("User created successfully!");
175 })
176 .catch((err: any) => {
177 this.logger.log(`Failed to create user: ${err.message}`, "error");
178 alert("Failed to create user! " + err.message);
179 });
180 }
181
182 // Logic duplicated for similar operations
183 public editUser(userId: number) {
184 // Directly edit UI elements based on user ID
185 const userElement = document.querySelector(`li[data-id="${userId}"]`);
186 if (!userElement) {
187 this.logger.log(`User element not found: ${userId}`, "error");
188 return;
189 }
190
191 // Find user data
192 const user = this.users.find((u) => u.id === userId);
193 if (!user) {
194 this.logger.log(`User not found: ${userId}`, "error");
195 return;
196 }
197
198 // Populate form - direct DOM manipulation
199 const form = document.getElementById("user-form") as HTMLFormElement;
200 if (form) {
201 (form.elements.namedItem("firstName") as HTMLInputElement).value =
202 user.firstName;
203 (form.elements.namedItem("lastName") as HTMLInputElement).value =
204 user.lastName;
205 (form.elements.namedItem("email") as HTMLInputElement).value = user.email;
206 (form.elements.namedItem("userId") as HTMLInputElement).value =
207 String(userId);
208
209 // Scroll to form
210 form.scrollIntoView({ behavior: "smooth" });
211 }
212
213 // Update global state
214 currentUserID = userId;
215 this.lastOperation = "edit";
216 }
217
218 // Logic duplicated, similar to deleteUser
219 public suspendUser(userId: number) {
220 if (!confirm("Are you sure you want to suspend this user?")) {
221 return;
222 }
223
224 this.db
225 .query("UPDATE users SET status = ? WHERE id = ?", ["suspended", userId])
226 .then((result: any) => {
227 this.logger.log(`User suspended: ${userId}`, "info");
228
229 // Update UI directly
230 this.renderUserList("user-container");
231
232 // Update global state
233 this.lastOperation = "suspend";
234
235 // Show success message
236 alert("User suspended successfully!");
237 })
238 .catch((err: any) => {
239 this.logger.log(`Failed to suspend user: ${err.message}`, "error");
240 alert("Failed to suspend user! " + err.message);
241 });
242 }
243
244 // Nearly identical to suspendUser
245 public activateUser(userId: number) {
246 this.db
247 .query("UPDATE users SET status = ? WHERE id = ?", ["active", userId])
248 .then((result: any) => {
249 this.logger.log(`User activated: ${userId}`, "info");
250
251 // Update UI directly
252 this.renderUserList("user-container");
253
254 // Update global state
255 this.lastOperation = "activate";
256
257 // Show success message
258 alert("User activated successfully!");
259 })
260 .catch((err: any) => {
261 this.logger.log(`Failed to activate user: ${err.message}`, "error");
262 alert("Failed to activate user! " + err.message);
263 });
264 }
265
266 // Logic duplicated again
267 public deleteUser(userId: number) {
268 if (!confirm("Are you sure you want to delete this user?")) {
269 return;
270 }
271
272 // Actually just updating status to 'deleted'
273 this.db
274 .query("UPDATE users SET status = ? WHERE id = ?", ["deleted", userId])
275 .then((result: any) => {
276 this.logger.log(`User deleted: ${userId}`, "info");
277
278 // Update UI directly
279 this.renderUserList("user-container");
280
281 // Update global state
282 this.lastOperation = "delete";
283
284 // Show success message
285 alert("User deleted successfully!");
286 })
287 .catch((err: any) => {
288 this.logger.log(`Failed to delete user: ${err.message}`, "error");
289 alert("Failed to delete user! " + err.message);
290 });
291 }
292
293 // Authentication mixed with user management
294 public login(email: string, password: string) {
295 // Directly query with credentials
296 this.db
297 .query("SELECT * FROM users WHERE email = ? AND password_hash = ?", [
298 email,
299 this.hashPassword(password),
300 ])
301 .then((result: any) => {
302 if (result.rows.length === 0) {
303 this.logger.log(`Failed login attempt: ${email}`, "warn");
304 alert("Invalid email or password");
305 return;
306 }
307
308 const user = result.rows[0];
309 if (user.status !== "active") {
310 this.logger.log(
311 `Login attempt from inactive account: ${email}`,
312 "warn",
313 );
314 alert("Your account is not active");
315 return;
316 }
317
318 // Update global state
319 currentUserID = user.id;
320 loggedInUsers.push(user);
321 this.lastOperation = "login";
322
323 // Store in localStorage
324 localStorage.setItem("current_user", JSON.stringify(user));
325
326 // Redirect to dashboard
327 window.location.href = "/dashboard.html";
328 })
329 .catch((err: any) => {
330 this.logger.log(`Login error: ${err.message}`, "error");
331 alert("Login failed! " + err.message);
332 });
333 }
334
335 // Utility function with security implications
336 private hashPassword(password: string): string {
337 // Not a real hash, just base64 encoding
338 return btoa(password);
339 }
340
341 // Cleanup that's never called
342 public cleanup() {
343 this.logger.log("Cleaning up resources", "debug");
344 this.db.close();
345 this.users = [];
346 currentUserID = null;
347 }
348}
349
350// Instantiate globally
351const userManager = new UserManager();
352
353// Event handlers directly in global scope
354function handleUserFormSubmit(event: Event) {
355 event.preventDefault();
356 const form = event.target as HTMLFormElement;
357
358 const userData = {
359 firstName: (form.elements.namedItem("firstName") as HTMLInputElement).value,
360 lastName: (form.elements.namedItem("lastName") as HTMLInputElement).value,
361 email: (form.elements.namedItem("email") as HTMLInputElement).value,
362 };
363
364 const userId = (form.elements.namedItem("userId") as HTMLInputElement).value;
365
366 if (userId) {
367 // Should call an update method, but directly calls the database
368 userManager.db
369 .query(
370 "UPDATE users SET firstName = ?, lastName = ?, email = ? WHERE id = ?",
371 [userData.firstName, userData.lastName, userData.email, userId],
372 )
373 .then(() => {
374 alert("User updated successfully!");
375 userManager.renderUserList("user-container");
376 form.reset();
377 (form.elements.namedItem("userId") as HTMLInputElement).value = "";
378 })
379 .catch((err: any) => {
380 alert("Failed to update user: " + err.message);
381 });
382 } else {
383 userManager.createUser(userData);
384 }
385}
386
387// Global initialization
388window.onload = function () {
389 console.log("Window loaded!");
390
391 // Set up event listeners
392 const userForm = document.getElementById("user-form");
393 if (userForm) {
394 userForm.addEventListener("submit", handleUserFormSubmit);
395 }
396
397 // Initialize user list
398 userManager.renderUserList("user-container");
399
400 // Set up some global error handlers
401 window.onerror = function (msg, url, line) {
402 userManager.logger.log(`Global error: ${msg} at ${url}:${line}`, "error");
403 return false;
404 };
405};
406
407// Global exports
408(window as any).userManager = userManager;
409(window as any).handleUserFormSubmit = handleUserFormSubmit;