-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathauthService.ts
More file actions
155 lines (134 loc) · 5.11 KB
/
authService.ts
File metadata and controls
155 lines (134 loc) · 5.11 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
import {
AuthorizationNotifier,
AuthorizationRequest,
AuthorizationResponse,
AuthorizationServiceConfiguration,
BaseTokenRequestHandler,
BasicQueryStringUtils,
DefaultCrypto,
FetchRequestor,
GRANT_TYPE_AUTHORIZATION_CODE,
LocalStorageBackend,
LocationLike,
RedirectRequestHandler,
TokenRequest,
TokenResponse
} from "@openid/appauth";
import { FetchParams, RequestContext } from "generated-api";
import jwt from "jwt-decode";
import moment from "moment";
class NoHashQueryStringUtils extends BasicQueryStringUtils {
parse(input: LocationLike, useHash: boolean) {
return super.parse(input, false /* never use hash */);
}
}
const getAuthorizationHandler = () => new RedirectRequestHandler(
new LocalStorageBackend(),
new NoHashQueryStringUtils(),
window.location,
new DefaultCrypto()
);
const fetchToken =
async (request: AuthorizationRequest, response: AuthorizationResponse): Promise<TokenResponse> => {
const tokenHandler = new BaseTokenRequestHandler(new FetchRequestor());
let extras: any = {};
if (request && request.internal) {
extras.code_verifier = request.internal.code_verifier;
}
const tokenRequest = new TokenRequest({
client_id: process.env.REACT_APP_AUTH_CLIENT_ID!,
redirect_uri: `${window.location.origin}/callback`,
grant_type: GRANT_TYPE_AUTHORIZATION_CODE,
code: response.code,
refresh_token: undefined,
extras,
});
try {
const authServiceConfig: AuthorizationServiceConfiguration = await AuthorizationServiceConfiguration.fetchFromIssuer(
process.env.REACT_APP_OPENID_ISSUER!,
new FetchRequestor()
);
const tokenResponse: TokenResponse = await tokenHandler.performTokenRequest(
authServiceConfig,
tokenRequest
);
localStorage.setItem('access_token', tokenResponse.accessToken);
if (!!tokenResponse.idToken) {
localStorage.setItem("id_token", tokenResponse.idToken);
localStorage.setItem(
"email",
(jwt(tokenResponse.idToken) as any).email
);
}
localStorage.setItem(
"expiresAt",
moment().add(tokenResponse.expiresIn || 0, 's').toISOString()
);
return Promise.resolve(tokenResponse);
} catch (err) {
return Promise.reject(err)
}
}
const getAuthorizationListener = (onSuccess: (token: TokenResponse) => void, onError: (error: any) => void) =>
(request: AuthorizationRequest, response: AuthorizationResponse | null, error: any) => {
if (error) {
onError(error)
}
if (!response) {
onError('No auth response received');
}
fetchToken(request, response!)
.then(token => onSuccess(token))
.catch(err => onError(err));
}
export const login = async (): Promise<void> => {
const authServiceConfiguration: AuthorizationServiceConfiguration =
await
AuthorizationServiceConfiguration.fetchFromIssuer(
process.env.REACT_APP_OPENID_ISSUER!,
new FetchRequestor()
);
const authorizationHandler = getAuthorizationHandler();
const authRequest = new AuthorizationRequest(
{
client_id: process.env.REACT_APP_AUTH_CLIENT_ID!,
redirect_uri: `${window.location.origin}/callback`,
scope: `openid profile email ${process.env.REACT_APP_AUTH_SCOPE!}`,
response_type: AuthorizationRequest.RESPONSE_TYPE_CODE,
state: undefined,
extras: { audience: "node-api" },
// extras: environment.extra
},
undefined,
true
);
authorizationHandler.performAuthorizationRequest(authServiceConfiguration, authRequest);
}
export const logout = () => {
localStorage.removeItem("access_token");
localStorage.removeItem("id_token");
localStorage.removeItem("email");
localStorage.removeItem("expiresAt");
};
export const isAuthenticated = () => localStorage.getItem('access_token') !== null && moment(localStorage.getItem('expiresAt')).isAfter(moment());
export const handleCallback = (onSuccess: (response: TokenResponse) => void, onError: (error: any) => void) => {
const authorizationHandler = getAuthorizationHandler();
const notifier = new AuthorizationNotifier();
authorizationHandler.setAuthorizationNotifier(notifier);
notifier.setAuthorizationListener(getAuthorizationListener(onSuccess, onError));
authorizationHandler.completeAuthorizationRequestIfPossible();
}
export const authHeaderMiddleware = async (
req: RequestContext
): Promise<FetchParams> => {
return Promise.resolve({
...req,
init: {
...req.init,
headers: {
...(req.init.headers || {}),
Authorization: `Bearer ${localStorage.getItem("access_token")}`,
},
},
});
};