-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add authenticate and authorize plugins
- Loading branch information
1 parent
fb622f7
commit 4be4b12
Showing
4 changed files
with
73 additions
and
13 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
import fp from 'fastify-plugin' | ||
|
||
declare module 'fastify' { | ||
interface FastifyContextConfig { | ||
authenticate?: boolean | ||
} | ||
} | ||
|
||
export default fp( | ||
// eslint-disable-next-line @typescript-eslint/require-await | ||
async app => { | ||
app.addHook('onRequest', async (request, reply) => { | ||
if (!request.routeOptions.config.authenticate) { | ||
return | ||
} | ||
|
||
if (!request.user) { | ||
return reply.unauthorized() | ||
} | ||
}) | ||
}, | ||
{ | ||
name: 'authenticate', | ||
}, | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
import fp from 'fastify-plugin' | ||
import type { PlayerRole } from '../../database/models/player.model' | ||
|
||
declare module 'fastify' { | ||
interface FastifyContextConfig { | ||
authorize?: PlayerRole[] | ||
} | ||
} | ||
|
||
export default fp( | ||
// eslint-disable-next-line @typescript-eslint/require-await | ||
async app => { | ||
app.addHook('preHandler', async (request, reply) => { | ||
if (!request.routeOptions.config.authorize) { | ||
return | ||
} | ||
|
||
if (!request.user) { | ||
return reply.unauthorized() | ||
} | ||
|
||
const roles = request.routeOptions.config.authorize | ||
if (roles.some(r => request.user!.player.roles.includes(r))) { | ||
return | ||
} | ||
|
||
return reply.forbidden() | ||
}) | ||
}, | ||
{ | ||
name: 'authorize', | ||
}, | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters