aboutsummaryrefslogtreecommitdiff
path: root/backend/src/services/handler.zig
diff options
context:
space:
mode:
Diffstat (limited to 'backend/src/services/handler.zig')
-rw-r--r--backend/src/services/handler.zig69
1 files changed, 69 insertions, 0 deletions
diff --git a/backend/src/services/handler.zig b/backend/src/services/handler.zig
new file mode 100644
index 0000000..e8c92d4
--- /dev/null
+++ b/backend/src/services/handler.zig
@@ -0,0 +1,69 @@
+const httpz = @import("httpz");
+const std = @import("std");
+const zqlite = @import("zqlite");
+
+const common = @import("common.zig");
+const static = @import("static.zig");
+const users_repo = @import("../repos/users_repo.zig");
+
+pub const RouteData = struct {
+ is_public: bool,
+};
+
+pub const Handler = struct {
+ conn: zqlite.Conn,
+ secure_tokens: bool,
+
+ pub fn dispatch(self: *Handler, action: httpz.Action(*common.Env), req: *httpz.Request, res: *httpz.Response) !void {
+ var user: ?users_repo.User = null;
+ if (!is_route_public(req)) {
+ const cookies = req.cookies();
+
+ const login_token = cookies.get("token") orelse return common.ServiceError.Forbidden;
+ user = try users_repo.get_user(res.arena, self.conn, login_token) orelse return common.ServiceError.Forbidden;
+ }
+
+ var env = common.Env{ .conn = self.conn, .secure_tokens = self.secure_tokens, .user = user };
+
+ try action(&env, req, res);
+ }
+
+ pub fn notFound(handler: *Handler, req: *httpz.Request, res: *httpz.Response) !void {
+ const path = req.url.path;
+ if (path.len >= 5 and std.mem.eql(u8, path[0..5], "/api/")) {
+ return common.ServiceError.NotFound;
+ } else {
+ // non API route, let client router take care of that
+ var env = common.Env{ .conn = handler.conn, .secure_tokens = handler.secure_tokens, .user = null };
+ try static.index(&env, req, res);
+ }
+ }
+
+ pub fn uncaughtError(_: *Handler, req: *httpz.Request, res: *httpz.Response, err: anyerror) void {
+ switch (err) {
+ common.ServiceError.BadRequest => error_response(res, 400, "Bad Request"),
+ common.ServiceError.NotFound => error_response(res, 404, "Not Found"),
+ common.ServiceError.Forbidden => error_response(res, 403, "Forbidden"),
+ else => {
+ std.debug.print("Internal Server Error at {s}: {}\n", .{ req.url.path, err });
+ error_response(res, 500, "Internal Server Error");
+ },
+ }
+ }
+};
+
+fn is_route_public(req: *httpz.Request) bool {
+ if (req.route_data) |rd| {
+ const route_data: *const RouteData = @ptrCast(@alignCast(rd));
+ return route_data.is_public;
+ } else {
+ return false;
+ }
+}
+
+fn error_response(res: *httpz.Response, code: u16, message: []const u8) void {
+ res.status = code;
+ res.json(.{ .message = message }, .{}) catch {
+ res.body = message;
+ };
+}