forked from finos/architecture-as-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthService.tsx
More file actions
96 lines (85 loc) · 2.45 KB
/
authService.tsx
File metadata and controls
96 lines (85 loc) · 2.45 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
import { UserManager, Log, User } from 'oidc-client';
const config = {
authority: 'https://localhost:9443/realms/calm-hub-realm',
client_id: 'calm-hub-authz-code',
redirect_uri: window.location.origin,
response_type: 'code',
scope: 'openid profile architectures:read adrs:all',
post_logout_redirect_uri: window.location.origin,
automaticSilentRenew: true,
filterProtocolClaims: true,
loadUserInfo: true,
};
let userManager: UserManager | null = null;
const isHttps = window.location.protocol === 'https:';
if (isHttps) {
userManager = new UserManager(config);
Log.logger = console;
Log.level = Log.INFO;
}
export async function getUser(): Promise<User | null> {
return (await userManager?.getUser()) || null;
}
export async function login(): Promise<void> {
await userManager?.signinRedirect();
}
export async function processRedirect(): Promise<User | null> {
try {
await userManager?.signinRedirectCallback();
return await getUser();
} catch (error) {
console.error('Redirect Processing Error:', error);
return null;
}
}
export async function logout(): Promise<void> {
try {
await userManager?.signoutRedirect();
} catch (error) {
console.error('Logout Error:', error);
}
}
export async function clearSession(): Promise<void> {
try {
await userManager?.removeUser();
console.log('Session cleared successfully.');
} catch (error) {
console.error('Error clearing session:', error);
}
}
export async function getToken(): Promise<string> {
if (!isHttps) {
return '';
}
const user = await userManager?.getUser();
if (user && !user.expired) {
return user.access_token;
}
if (user && user.expired) {
try {
const refreshedUser = await userManager?.signinSilent();
return refreshedUser?.access_token || '';
} catch (error) {
console.error('Error refreshing token:', error);
return '';
}
}
return '';
}
export async function checkAuthorityService(): Promise<boolean> {
try {
const response = await fetch(config.authority, { method: 'HEAD' });
return response.ok;
} catch (error) {
console.error('Authority Service Check Error:', error);
return false;
}
}
export const authService = {
getUser,
login,
processRedirect,
logout,
clearSession,
getToken,
};