forked from SoftwareBrothers/adminjs-fastify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
buildAuthenticatedRouter.ts
69 lines (65 loc) · 2.28 KB
/
buildAuthenticatedRouter.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
62
63
64
65
66
67
68
69
import fastifyCookie from '@fastify/cookie';
import fastifyFormBody from '@fastify/formbody';
import FastifySessionPlugin from '@fastify/session';
import AdminJS from 'adminjs';
import { FastifyInstance } from 'fastify';
import { withLogin } from './authentication/login.handler.js';
import { withLogout } from './authentication/logout.handler.js';
import { withProtectedRoutesHandler } from './authentication/protected-routes.handler.js';
import { buildRouter } from './buildRouter.js';
import { AuthenticationOptions } from './types.js';
/**
* @typedef {Function} Authenticate
* @memberof module:@adminjs/fastify
* @description
* function taking 2 arguments email and password
* @param {string} [email] email given in the form
* @param {string} [password] password given in the form
* @return {CurrentAdmin | null} returns current admin or null
*/
/**
* Builds the Express Router which is protected by a session auth
*
* Normally fastify-session holds session in memory, which is
* not optimized for production usage and, in development, it causes
* logging out after every page refresh (if you use nodemon).
* @static
* @memberof module:@adminjs/fastify
* @example
* const ADMIN = {
* email: '[email protected]',
* password: 'password',
* }
*
* AdminJSFastify.buildAuthenticatedRouter(adminJs, {
* authenticate: async (email, password) => {
* if (ADMIN.password === password && ADMIN.email === email) {
* return ADMIN
* }
* return null
* },
* cookieName: 'adminjs',
* cookiePassword: 'somePassword',
* }, [router])
*/
export const buildAuthenticatedRouter = async (
admin: AdminJS,
auth: AuthenticationOptions,
fastifyApp: FastifyInstance,
sessionOptions?: FastifySessionPlugin.FastifySessionOptions
): Promise<void> => {
await fastifyApp.register(fastifyCookie, {
secret: auth.cookiePassword,
});
await fastifyApp.register(FastifySessionPlugin, {
secret: auth.cookiePassword,
cookieName: auth.cookieName ?? 'adminjs',
cookie: sessionOptions?.cookie ?? { secure: false },
...(sessionOptions ?? {}),
});
await fastifyApp.register(fastifyFormBody);
await buildRouter(admin, fastifyApp);
withProtectedRoutesHandler(fastifyApp, admin);
withLogin(fastifyApp, admin, auth);
withLogout(fastifyApp, admin);
};