Source

adminjs-fastify/src/buildAuthenticatedRouter.ts

  1. import AdminJS from 'adminjs';
  2. import { withLogout } from './authentication/logout.handler';
  3. import { buildRouter } from './buildRouter';
  4. import { AuthenticationOptions } from './types';
  5. import { withLogin } from './authentication/login.handler';
  6. import { withProtectedRoutesHandler } from './authentication/protected-routes.handler';
  7. import { FastifyInstance } from 'fastify';
  8. import fastifyCookie from 'fastify-cookie';
  9. import fastifySession from 'fastify-session';
  10. import fastifyFormBody from 'fastify-formbody';
  11. import FastifySessionPlugin from 'fastify-session';
  12. import Options = FastifySessionPlugin.Options;
  13. /**
  14. * @typedef {Function} Authenticate
  15. * @memberof module:@adminjs/fastify
  16. * @description
  17. * function taking 2 arguments email and password
  18. * @param {string} [email] email given in the form
  19. * @param {string} [password] password given in the form
  20. * @return {CurrentAdmin | null} returns current admin or null
  21. */
  22. /**
  23. * Builds the Express Router which is protected by a session auth
  24. *
  25. * Normally fastify-session holds session in memory, which is
  26. * not optimized for production usage and, in development, it causes
  27. * logging out after every page refresh (if you use nodemon).
  28. * @static
  29. * @memberof module:@adminjs/fastify
  30. * @example
  31. * const ADMIN = {
  32. * email: 'test@example.com',
  33. * password: 'password',
  34. * }
  35. *
  36. * AdminJSFastify.buildAuthenticatedRouter(adminJs, {
  37. * authenticate: async (email, password) => {
  38. * if (ADMIN.password === password && ADMIN.email === email) {
  39. * return ADMIN
  40. * }
  41. * return null
  42. * },
  43. * cookieName: 'adminjs',
  44. * cookiePassword: 'somePassword',
  45. * }, [router])
  46. */
  47. export const buildAuthenticatedRouter = (
  48. admin: AdminJS,
  49. auth: AuthenticationOptions,
  50. fastifyApp: FastifyInstance,
  51. sessionOptions?: Options
  52. ): void => {
  53. fastifyApp.register(fastifyCookie);
  54. fastifyApp.register(fastifySession, {
  55. secret: auth.cookiePassword,
  56. cookieName: auth.cookieName ?? 'adminjs',
  57. cookie: {
  58. secure: false,
  59. },
  60. ...(sessionOptions ?? {}),
  61. });
  62. fastifyApp.register(fastifyFormBody);
  63. buildRouter(admin, fastifyApp);
  64. withProtectedRoutesHandler(fastifyApp, admin);
  65. withLogin(fastifyApp, admin, auth);
  66. withLogout(fastifyApp, admin);
  67. };