authenzify
Version:
server to manage authentication authorization of users and more
75 lines (68 loc) • 2.04 kB
JavaScript
import { v4 } from 'uuid'
import fastify from 'fastify'
import cookie from '@fastify/cookie'
import { fastifyRequestContext } from '@fastify/request-context'
import { factory } from './adapters/factories/index.js'
import { ConfigService } from './services/config.service.js'
import { initUsersRoutes } from './app-routes/users-routes.js'
import { getAuthenticatedInterceptor } from './interceptors.js'
/**
* Loads and returns the full configuration object used by the users management module.
*
* @param {Partial<UsersManagementServerConfig>} config - Optional overrides for base config
* @returns {Promise<UsersManagementServer>}
*/
export const usersManagementServer = async (config) => {
const webServer = fastify({
logger: config.logger
? {
level: 'info',
serializers: {
req(req) {
return {
url: req.url,
method: req.method,
correlationId: req.headers['x-correlation-id'] || v4(),
}
},
},
}
: false,
})
const configService = new ConfigService(config)
const usersManagement = await factory(configService)
await webServer.register(cookie)
await webServer.register(fastifyRequestContext, {
defaultStoreValues: {
userInfo: { id: 'system' },
},
})
const { publicKey, jwtOptions, authorizationCookieKey } = config
const { tryToExtractUserAuthenticated } = getAuthenticatedInterceptor({
publicKey,
jwtOptions,
authorizationCookieKey,
})
webServer.register(
initUsersRoutes({
configService,
usersManagement,
tryToExtractUserAuthenticated,
}),
{ prefix: configService.usersRoutesPrefix },
)
webServer.listen(
{ port: configService.port, host: configService.host },
(err, address) => {
if (err) {
console.error(err)
process.exit(1)
}
console.log(`Server listening at ${address}`)
},
)
return {
server: webServer,
usersManagement,
}
}