-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_sample.diff
More file actions
44 lines (44 loc) · 1.14 KB
/
test_sample.diff
File metadata and controls
44 lines (44 loc) · 1.14 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
diff --git a/src/auth/LoginService.ts b/src/auth/LoginService.ts
new file mode 100644
index 0000000..a1b2c3d
--- /dev/null
+++ b/src/auth/LoginService.ts
@@ -0,0 +1,35 @@
+import jwt from 'jsonwebtoken';
+import bcrypt from 'bcrypt';
+
+export class LoginService {
+ private secretKey: string;
+
+ constructor(secretKey: string) {
+ this.secretKey = secretKey;
+ }
+
+ async login(username: string, password: string): Promise<string> {
+ // Validate credentials
+ const user = await this.validateCredentials(username, password);
+
+ if (!user) {
+ throw new Error('Invalid credentials');
+ }
+
+ // Generate JWT token
+ const token = jwt.sign(
+ { userId: user.id, username: user.username, role: user.role },
+ this.secretKey,
+ { expiresIn: '24h' }
+ );
+
+ return token;
+ }
+
+ private async validateCredentials(username: string, password: string) {
+ // Query user from database
+ const user = await db.users.findOne({ username });
+ if (!user) return null;
+
+ // Verify password
+ const isValid = await bcrypt.compare(password, user.passwordHash);
+ return isValid ? user : null;
+ }
+}