-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthProvider.tsx
More file actions
225 lines (199 loc) · 5.37 KB
/
AuthProvider.tsx
File metadata and controls
225 lines (199 loc) · 5.37 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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import { InternalAuthProvider } from '@/context/InternalAuthContext';
import React, {
createContext,
ReactNode,
useCallback,
useContext,
useEffect,
useState,
} from 'react';
import { AuthMode, createFetchWithAuth } from './fetchWithAuth';
import { usePreviousSignIn } from './hooks/usePreviousSignIn';
import {
AuthenticatorTransportFuture,
CredentialDeviceType,
} from '@simplewebauthn/browser';
export interface User {
id: string;
email: string;
phone: string;
roles?: string[];
}
type AuthToken = {
oneTimeToken: string;
expiresAt: string;
};
export interface AuthContextType {
user: User | null;
logout: () => void;
deleteUser: () => void;
isAuthenticated: boolean;
hasRole: (role: string) => boolean | undefined;
apiHost: string;
token: AuthToken | null;
markSignedIn: () => void;
hasSignedInBefore: boolean;
mode: AuthMode;
credentials: Credential[];
updateCredential: (credential: Credential) => Promise<Credential>;
deleteCredential: (credentialId: string) => Promise<void>;
loading: boolean;
}
export interface Credential {
id: string;
counter: number;
transports?: AuthenticatorTransportFuture[];
deviceType: CredentialDeviceType;
backedup: boolean;
friendlyName: string | null;
lastUsedAt: Date | null;
platform: string | null;
browser: string | null;
deviceInfo: string | null;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
/**
* Returns the current context
* @returns {AuthContextType} AuthContext
*/
export const useAuth = (): AuthContextType => {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
};
interface AuthProviderProps {
children: ReactNode;
apiHost: string;
autoDetectPreviousSignin?: boolean;
mode?: AuthMode;
}
export const AuthProvider: React.FC<AuthProviderProps> = ({
children,
apiHost,
autoDetectPreviousSignin = true,
mode = 'web',
}) => {
const [user, setUser] = useState<User | null>(null);
const [credentials, setCredentials] = useState<Credential[]>([]);
const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);
const [loading, setLoading] = useState<boolean>(true);
const [token, setToken] = useState<AuthToken | null>(null);
const { hasSignedInBefore, markSignedIn } = usePreviousSignIn();
const [authMode] = useState<AuthMode>(mode);
const fetchWithAuth = createFetchWithAuth({
authMode,
authHost: apiHost,
});
const logout = useCallback(async () => {
if (user) {
try {
await fetchWithAuth(`/logout`, {
method: 'GET',
});
} catch {
console.error('Error during logout');
} finally {
setIsAuthenticated(false);
setUser(null);
setToken(null);
}
}
}, [fetchWithAuth, user]);
const deleteUser = async () => {
try {
const response = await fetchWithAuth(`/users/delete`, {
method: 'delete',
});
if (response.ok) {
setUser(null);
setIsAuthenticated(false);
setToken(null);
return;
} else {
throw new Error('Could not delete user.');
}
} catch (error) {
console.error('Something went wrong deleting user:', error);
throw new Error('Could not delete user.');
}
};
const hasRole = (role: string) => user?.roles?.includes(role);
const validateToken = async () => {
setLoading(true);
try {
const response = await fetchWithAuth(`users/me`, {
method: 'GET',
});
if (response.ok) {
const { user, credentials } = await response.json();
setUser(user);
setCredentials(credentials);
setIsAuthenticated(true);
} else {
logout();
}
} catch {
logout();
} finally {
setLoading(false);
}
};
const updateCredential = async (credential: Credential) => {
const response = await fetchWithAuth(`users/credentials`, {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ friendlyName: credential.friendlyName, id: credential.id }),
});
if (response.ok) {
return response.json();
}
throw new Error('Failed to update credential');
};
const deleteCredential = async (credentialId: string) => {
const response = await fetchWithAuth(`users/credentials`, {
method: 'DELETE',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id: credentialId }),
});
if (response.ok) {
return response.json();
}
throw new Error('Failed to update credential');
};
useEffect(() => {
validateToken();
}, []);
useEffect(() => {
if (user && isAuthenticated) {
markSignedIn();
}
}, [user, isAuthenticated, markSignedIn]);
return (
<AuthContext.Provider
value={{
user,
logout,
loading,
deleteUser,
isAuthenticated,
hasRole,
apiHost,
token,
markSignedIn,
hasSignedInBefore: autoDetectPreviousSignin ? hasSignedInBefore : false,
mode,
credentials,
updateCredential,
deleteCredential,
}}
>
<InternalAuthProvider value={{ validateToken, setLoading }}>
{children}
</InternalAuthProvider>
</AuthContext.Provider>
);
};