summary refs log tree commit diff
path: root/src/api/middlewares/authMiddleware.js
blob: 13d0d279fa4d880566356cd01aebe85f7584b125 (plain) (blame)
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import { validateJwtToken } from '#util/jwtUtils.js';
import { DbUser, UserType } from '#db/schemas/index.js';
import { SafeNSoundError } from '#util/error.js';

const shouldLogAuth = !!process.env['LOG_AUTH'];
function logAuth(...params) {
    if (shouldLogAuth) {
        console.log('[AUTH]', ...params);
    }
}

function getTokenFromHeader(authHeader) {
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
        return null;
    }
    const parts = authHeader.split(' ');
    return {
        scheme: parts[0],
        token: parts[1]
    };
}

export async function useAuthentication(req, res, next) {
    if (!req.headers.authorization) {
        logAuth('Request to', req.path, 'without auth');
        next();
        return;
    }

    const auth = (req.auth = await validateJwtToken(
        getTokenFromHeader(req.headers.authorization).token
    ));
    logAuth('Token data:', auth);

    // req.user = auth;
    next();
}

export async function requireAuth(req, res, next) {
    if (!req.auth) {
        logAuth('Unauthorized request to', req.path);
        res.status(401).send(
            new SafeNSoundError({
                errCode: 'UNAUTHORIZED',
                message: 'Unauthorized'
            })
        );
        return;
    }

    next();
}

/**
 * @param options {AuthValidationOptions}
 * @returns {(function(*, *, *): void)|*}
 */
export function requireRole(options) {
    return async function (req, res, next) {
        res.status(401).send(
            new SafeNSoundError({
                errCode: 'UNAUTHORIZED',
                message: 'Unauthorized'
            })
        );

        const user = (req.user = await DbUser.findById(auth.id).exec());

        // admin can do everything
        if (user.type == UserType.ADMIN) {
            next();
            return;
        }

        if (options.roles && !options.roles.includes(user.type)) {
            res.status(401).send(
                new SafeNSoundError({
                    errCode: 'UNAUTHORIZED',
                    message: 'Unauthorized'
                })
            );
            return;
        }

        next();
    };
}

export const requireAdmin = requireRole({ roles: [UserType.ADMIN] });
export const requireMonitor = requireRole({ roles: [UserType.MONITOR] });
export const requireUser = requireRole({ roles: [UserType.USER] });
export const requireUserOrMonitor = requireRole({
    roles: [UserType.USER, UserType.MONITOR]
});

class AuthValidationOptions {
    roles;
}