╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
848 } 849 850 // mint a new session for user_id, returning the token hex to set as the 851 // cookie value. 852 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 853 var token: [evt.event_id_size]u8 = undefined; 854 self.io.random(&token); 855 const token_hex = std.fmt.bytesToHex(token, .lower); 856 const file = try self.dir.createFile(self.io, &token_hex, .{}); 857 defer file.close(self.io); 858 try file.writeStreamingAll(self.io, user_id); 859 return token_hex; 860 } 861 862 // resolve a cookie's token to its user_id. returns false (logged out) for a 863 // missing, malformed, or unknown token. 864 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 865 if (!isToken(token_hex)) return false; 866 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 867 defer file.close(self.io); 868 var storage: [evt.event_id_size]u8 = undefined; 869 var file_reader = file.reader(self.io, &storage); 870 file_reader.interface.readSliceAll(out) catch return false; 871 return true; 872 } 873 874 // revoke a session. a no-op for a missing or malformed token. 875 pub fn remove(self: SessionStore, token_hex: []const u8) void { 876 if (!isToken(token_hex)) return; 877 self.dir.deleteFile(self.io, token_hex) catch {}; 878 } 879 880 // a token is exactly token_hex_len hex chars. validating before using the 881 // value as a path keeps attacker-supplied cookies from escaping the 882 // sessions dir (e.g. via "/" or ".." bytes). 883 fn isToken(token_hex: []const u8) bool { 884 if (token_hex.len != token_hex_len) return false; 885 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 886 return true; 887 } 888 }; 889