summaryrefslogtreecommitdiff
path: root/backend/src/Handler.zig
blob: 3e40cf819be5372cc4d635146be25f46c2110dca (plain)
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
const std = @import("std");
const httpz = @import("httpz");
const userModel = @import("Models/User.zig");
const tokens = @import("Authentication/Tokens.zig");

pub const RequestData = struct {
    User: ?userModel.User,

    pub fn Init(req: *httpz.Request) !RequestData {
        return .{
            .User = try getUser(req),
        };
    }

    fn getUser(req: *httpz.Request) !?userModel.User {
        const header = req.header("authorization") orelse return null;
        const stripped = stripBearerPrefix(header);
        const parsed = tokens.GetUserFromToken(req.arena, stripped) catch |err| {
            if (err == tokens.errors.NotFound) {
                return null;
            }
            std.debug.print("Failed to parse a user: {any}\n", .{ err });
            return err;
        } orelse {
            return null;
        };

        return parsed.value;
    }

    pub fn CanUserAccess(self: RequestData, minimalRole: userModel.Role) bool {
        if (self.User == null) return false;
        return self.User.?.Role >= minimalRole;
    }
};

pub const Handler = struct {
    pub fn dispatch(_: *Handler, action: httpz.Action(*RequestData), req: *httpz.Request, res: *httpz.Response) !void {
        var data = try RequestData.Init(req);
        // std.debug.print("Data: {any}\n", .{ data });
        try action(&data, req, res);
        std.debug.print("{any} {s}: {d}\n", .{req.method, req.url.raw, res.status});
    }
};

const headerPrefix = "Bearer ";

fn stripBearerPrefix(header: []const u8) []const u8 {
    if (std.mem.startsWith(u8, header, headerPrefix)) {
        return header[headerPrefix.len..];
    }
    return header;
}