-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathrefresh.handler.ts
61 lines (50 loc) · 1.53 KB
/
refresh.handler.ts
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
import AdminJS, { CurrentAdmin } from "adminjs";
import { Router } from "express";
import { AuthenticationOptions } from "../types.js";
import { WrongArgumentError } from "../errors.js";
const getRefreshTokenPath = (admin: AdminJS) => {
const { refreshTokenPath, rootPath } = admin.options;
const normalizedRefreshTokenPath = refreshTokenPath.replace(rootPath, "");
return normalizedRefreshTokenPath.startsWith("/")
? normalizedRefreshTokenPath
: `/${normalizedRefreshTokenPath}`;
};
const MISSING_PROVIDER_ERROR =
'"provider" has to be configured to use refresh token mechanism';
export const withRefresh = (
router: Router,
admin: AdminJS,
auth: AuthenticationOptions
): void => {
const refreshTokenPath = getRefreshTokenPath(admin);
const { provider } = auth;
router.post(refreshTokenPath, async (request, response) => {
if (!provider) {
throw new WrongArgumentError(MISSING_PROVIDER_ERROR);
}
const updatedAuthInfo = await provider.handleRefreshToken(
{
data: request.fields ?? {},
query: request.query,
params: request.params,
headers: request.headers,
},
{ req: request, res: response }
);
let admin = request.session.adminUser as Partial<CurrentAdmin> | null;
if (!admin) {
admin = {};
}
if (!admin._auth) {
admin._auth = {};
}
admin._auth = {
...admin._auth,
...updatedAuthInfo,
};
request.session.adminUser = admin;
request.session.save(() => {
response.send(admin);
});
});
};