MCPcopy Index your code
hub / github.com/freeCodeCamp/freeCodeCamp / plugin

Function plugin

api/src/plugins/bouncer.ts:17–70  ·  view source on GitHub ↗
(fastify, _options, done)

Source from the content-addressed store, hash-verified

15}
16
17const plugin: FastifyPluginCallback = (fastify, _options, done) => {
18 fastify.decorate(
19 'send401IfNoUser',
20 async function (req: FastifyRequest, reply: FastifyReply) {
21 if (!req.user) {
22 const logger = fastify.log.child({ req, res: reply });
23
24 logger.trace(
25 'Protected route accessed by unauthenticated user. Sent 401.'
26 );
27
28 await reply.status(401).send({
29 type: req.accessDeniedMessage?.type,
30 message: req.accessDeniedMessage?.content
31 });
32 }
33 }
34 );
35
36 fastify.decorate(
37 'redirectIfNoUser',
38 async function (req: FastifyRequest, reply: FastifyReply) {
39 const logger = fastify.log.child({ req, res: reply });
40 if (!req.user) {
41 logger.trace(
42 'Protected route accessed by unauthenticated user. Redirecting to login.'
43 );
44 const { origin } = getRedirectParams(req);
45 await reply.redirectWithMessage(origin, {
46 type: 'info',
47 content:
48 'Only authenticated users can access this route. Please sign in and try again.'
49 });
50 }
51 }
52 );
53
54 fastify.decorate(
55 'redirectIfSignedIn',
56 async function (req: FastifyRequest, reply: FastifyReply) {
57 if (req.user) {
58 const logger = fastify.log.child({ req, res: reply });
59
60 const { returnTo } = getRedirectParams(req);
61
62 logger.trace(`User ${req.user?.id} redirected to: ${returnTo}`);
63
64 await reply.redirect(returnTo);
65 }
66 }
67 );
68
69 done();
70};
71
72export default fp(plugin, {
73 dependencies: ['auth', 'redirect-with-message'],

Callers

nothing calls this directly

Calls 3

getRedirectParamsFunction · 0.85
doneFunction · 0.85
sendMethod · 0.45

Tested by

no test coverage detected