Skip to content

Context Utilities

Skitsanos edited this page Jan 2, 2023 · 2 revisions

JWT-based authorization

The following example demonstrates how to implement route authorization with JWT context utils. All the routes except the /login and /signup will require the user to be authenticated first.

module.context.use((req, res, next) =>
{
    if (req.path.match(/\/(login|signup)/igu))
    {
        next();
    }
    else
    {
        const {authorization} = req.headers;

        if (!authorization)
        {
            res.throw(404, 'Missing authorization header');
        }

        const token = authorization && authorization.split(' ')[1];

        try
        {
            const {auth} = module.context;

            if (auth.isExpired(token))
            {
                res.throw(403, 'The token is expired');
            }

            next();
        }
        catch (e)
        {
            res.throw(403, e.message);
        }
    }
});
Clone this wiki locally