From 8d018d996c1eddb882dc64ebbd228bb0135944f3 Mon Sep 17 00:00:00 2001 From: sadbeast Date: Sun, 23 Jun 2024 15:36:59 -0700 Subject: wtf --- src/web/dispatcher.zig | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 src/web/dispatcher.zig (limited to 'src/web/dispatcher.zig') diff --git a/src/web/dispatcher.zig b/src/web/dispatcher.zig new file mode 100644 index 0000000..77ea282 --- /dev/null +++ b/src/web/dispatcher.zig @@ -0,0 +1,52 @@ +pub const Dispatcher = struct { + app: *App, + // whether to try loading the user or not, this implies requires_user = false + load_user: bool = true, + + // whether a user is required. When false, if we have a token, the user is still + // loaded (unless load_user = false). + requires_user: bool = false, + + pub fn dispatch(self: *const Dispatcher, action: httpz.Action(*Env), req: *httpz.Request, res: *httpz.Response) !void { + const app = self.app; + + var env = Env{ + .app = app, + }; + // defer env.deinit(); + // + try self.doDispatch(action, req, res, &env); + } + + fn doDispatch(_: *const Dispatcher, action: httpz.Action(*Env), req: *httpz.Request, res: *httpz.Response, env: *Env) !void { + const query = try req.query(); + const user = try loadUser(env.app, query.get("user")); + + if (user) |u| { + env.user = u; + std.debug.print("user: {}, {s}\n", .{ u.id, u.username }); + } + try action(env, req, res); + } +}; + +fn loadUser(app: *App, optional_session_id: ?[]const u8) !?User { + const session_id = optional_session_id orelse return null; + + var user: User = undefined; + const row = try app.pool.row("SELECT user_id, username FROM users WHERE user_id = $1", .{session_id}); + if (row) |r| { + user = try r.to(User, .{}); + } else { + return null; + } + + return try User.init(app.allocator, user.id, user.username); +} + +const httpz = @import("httpz"); +const std = @import("std"); + +const App = @import("../app.zig").App; +const User = @import("../User.zig"); +const Env = @import("../env.zig").Env; -- cgit v1.2.3