summary refs log tree commit diff
path: root/src/api/middlewares/authMiddleware.js
blob: 34a96f4f722fc6d3ac494acac8ede2029c680ce3 (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
99
100
101
102
103
104
105
106
107
108
109
110
import { validateJwtToken } from '#util/jwtUtils.js';
import { DbUser, UserType } from '#db/schemas/index.js';
import { SafeNSoundError } from '#util/error.js';
import { getUserById } from '#db/dbAccess/index.js';

const shouldLogAuth = process.env['LOG_AUTH'] === 'true';
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);

    if (auth) {
        req.user = await getUserById(auth.sub);
        logAuth('User data:', req.user);

        if (req.user) {
            req.device = req.user.devices.find(
                device => device.id === auth.deviceId
            );
            logAuth('Device data:', req.device);

            if (req.device) {
                if (req.device.lastSeen < Date.now() - 1000) {
                    logAuth('Updating device last seen for', req.device.id);
                    req.device.lastSeen = Date.now();
                    await req.user.save();
                }
            }
        }
    }

    next();
}

export async function requireAuth(req, res, next) {
    if (!req.auth || !req.user || !req.device) {
        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) {
        // admin can do everything
        if (req.user.type === UserType.ADMIN) {
            next();
            return;
        }

        if (options.roles && !options.roles.includes(req.user.type)) {
            logAuth('User is missing roles', options.roles);
            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;
}