diff options
author | sadbeast <sadbeast@sadbeast.com> | 2024-06-23 15:36:59 -0700 |
---|---|---|
committer | sadbeast <sadbeast@sadbeast.com> | 2024-07-13 21:58:23 -0700 |
commit | 8d018d996c1eddb882dc64ebbd228bb0135944f3 (patch) | |
tree | d01956546a77dbae33357c9a5d174f511ac9b282 /src/web/dispatcher.zig | |
download | teamdraft-8d018d996c1eddb882dc64ebbd228bb0135944f3.tar.gz teamdraft-8d018d996c1eddb882dc64ebbd228bb0135944f3.tar.bz2 |
Diffstat (limited to 'src/web/dispatcher.zig')
-rw-r--r-- | src/web/dispatcher.zig | 52 |
1 files changed, 52 insertions, 0 deletions
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; |