forked from Schroedinger-Hat/certo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth-client.ts
More file actions
188 lines (166 loc) · 3.71 KB
/
Copy pathauth-client.ts
File metadata and controls
188 lines (166 loc) · 3.71 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
import { apiClient } from './api-client'
interface LoginResponse {
jwt: string
user: {
id: number
username: string
email: string
provider: string
confirmed: boolean
blocked: boolean
createdAt: string
updatedAt: string
role: {
id: number
name: string
type: string
}
}
}
interface RegisterResponse extends LoginResponse {}
interface RegisterData {
username: string
email: string
password: string
}
interface LoginData {
identifier: string
password: string
}
/**
* Authentication client for user management
*/
export class AuthClient {
/**
* Fetch and save the fully populated user (with role)
*/
private async fetchAndSaveFullUser() {
try {
const fullUser = await apiClient.get<any>('/api/users/me', { populate: '*' })
if (fullUser) {
this.saveUser(fullUser)
return fullUser
}
}
catch (error) {
console.error('Failed to fetch full user:', error)
}
return null
}
/**
* Register a new user
*/
async register(data: RegisterData): Promise<RegisterResponse> {
try {
const response = await apiClient.post<RegisterResponse>('/api/auth/local/register', data)
// Store auth data
if (response.jwt) {
this.saveToken(response.jwt)
this.saveUser(response.user)
apiClient.setToken(response.jwt)
// Fetch and save the full user with role
await this.fetchAndSaveFullUser()
}
return response
}
catch (error) {
console.error('Registration failed:', error)
throw error
}
}
/**
* Login a user
*/
async login(data: LoginData): Promise<LoginResponse> {
try {
const response = await apiClient.post<LoginResponse>('/api/auth/local', data)
// Set the token for future API calls
if (response.jwt) {
this.saveToken(response.jwt)
this.saveUser(response.user)
apiClient.setToken(response.jwt)
// Fetch and save the full user with role
await this.fetchAndSaveFullUser()
}
return response
}
catch (error) {
console.error('Login failed:', error)
throw error
}
}
/**
* Logout the current user
*/
logout(): void {
this.clearStorage()
apiClient.clearToken()
}
/**
* Check if a user is logged in
*/
isAuthenticated(): boolean {
if (!import.meta.client) {
return false
}
const token = this.getToken()
const user = this.getCurrentUser()
return !!(token && user)
}
/**
* Get current authenticated user
*/
getCurrentUser() {
if (!import.meta.client) {
return null
}
try {
const userJson = localStorage.getItem('user')
if (!userJson) {
return null
}
return JSON.parse(userJson)
}
catch (error) {
console.error('Error parsing user from localStorage:', error)
return null
}
}
/**
* Get the stored authentication token
*/
getToken(): string | null {
if (!import.meta.client) {
return null
}
return localStorage.getItem('token')
}
/**
* Save token to localStorage
*/
private saveToken(token: string): void {
if (import.meta.client) {
localStorage.setItem('token', token)
}
}
/**
* Save user to localStorage
*/
private saveUser(user: any): void {
if (import.meta.client) {
localStorage.setItem('user', JSON.stringify(user))
}
}
/**
* Clear storage (token and user)
*/
private clearStorage(): void {
if (import.meta.client) {
localStorage.removeItem('token')
localStorage.removeItem('user')
}
}
}
// Export a singleton instance
export const authClient = new AuthClient()
export default authClient