forked from Dhanushsai0407/Vi-Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthService.ts
More file actions
50 lines (41 loc) · 1.48 KB
/
AuthService.ts
File metadata and controls
50 lines (41 loc) · 1.48 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
export interface User {
id: string;
email: string;
}
export class AuthService {
private static USERS_KEY = 'vi_notes_users';
private static CURRENT_USER_KEY = 'vi_notes_current_user';
static getUsers(): Record<string, string> {
const users = localStorage.getItem(this.USERS_KEY);
return users ? JSON.parse(users) : {};
}
static register(email: string, password: string): User {
const users = this.getUsers();
if (users[email]) {
throw new Error('User already exists. Please log in.');
}
// Extremely simple simulation: store cleartext password for demo purposes only
users[email] = password;
localStorage.setItem(this.USERS_KEY, JSON.stringify(users));
return this.login(email, password);
}
static login(email: string, password: string): User {
const users = this.getUsers();
if (!users[email]) {
throw new Error('User not found. Please sign up.');
}
if (users[email] !== password) {
throw new Error('Incorrect password.');
}
const user = { id: email, email };
localStorage.setItem(this.CURRENT_USER_KEY, JSON.stringify(user));
return user;
}
static logout() {
localStorage.removeItem(this.CURRENT_USER_KEY);
}
static getCurrentUser(): User | null {
const user = localStorage.getItem(this.CURRENT_USER_KEY);
return user ? JSON.parse(user) : null;
}
}