-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth-module.js
More file actions
47 lines (42 loc) · 1.48 KB
/
Copy pathauth-module.js
File metadata and controls
47 lines (42 loc) · 1.48 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
const express = require('express');
const { configure, getConfig, resetConfig } = require('./utils/config');
const database = require('./utils/database');
const initDatabase = require('./utils/initDatabase');
const validateConfig = require('./utils/validateConfig');
const authenticate = require('./middleware/authenticate');
const authorize = require('./middleware/authorize');
const validateApiKey = require('./middleware/validateApiKey');
const authRouter = require('./routes/auth/router');
const adminRouter = require('./routes/admin');
/**
* Creates an embeddable authentication module for an existing Express app.
* The returned router owns no HTTP server and can be mounted at any path.
*/
const createAuthModule = (options = {}) => {
const {
database: externalDatabase,
authPath = '/auth',
adminPath = '/admin',
exposeAdminApi = true,
...authConfig
} = options;
configure(authConfig);
if (externalDatabase) database.usePool(externalDatabase);
const router = express.Router();
router.use(authPath, authRouter);
if (exposeAdminApi) router.use(adminPath, adminRouter);
return Object.freeze({
router,
config: getConfig(),
initialize: async () => {
validateConfig({ requireDatabaseEnv: !externalDatabase });
await initDatabase();
},
middleware: Object.freeze({ authenticate, authorize, validateApiKey }),
close: async () => {
await database.close();
resetConfig();
},
});
};
module.exports = { createAuthModule };