const std = @import("std"); const lmdb = @import("lmdb"); const db = @import("db"); const http = @import("http"); // db {{{ const Db = struct { fn users(txn: lmdb.Txn) !db.Db(UserId, User) { return try db.Db(UserId, User).init(txn, "users"); } fn user_ids(txn: lmdb.Txn) !db.Db(Username, UserId) { return try db.Db(Username, UserId).init(txn, "user_ids"); } fn sessions(txn: lmdb.Txn) !db.Db(SessionToken, UserId) { return try db.Db(SessionToken, UserId).init(txn, "sessions"); } fn posts(txn: lmdb.Txn) !db.Db(PostId, Post) { return try db.Db(PostId, Post).init(txn, "posts"); } }; // }}} // content {{{ const User = struct { // TODO: choose sizes id: UserId, name: Username, password_hash: PasswordHash, posts: PostList, }; const Post = struct { id: PostId, user_id: UserId, time: Timestamp, upvotes: u64 = 0, downvotes: u64 = 0, votes: VoteList, comments: PostList, // quote posts text: PostText, }; const Vote = struct { const Kind = enum { Up, Down }; kind: Kind, time: Timestamp, }; const Id = u64; const Login = struct { user: User, user_id: UserId, session_token: SessionToken, }; const UserId = enum(u64) { _ }; const PostId = enum(u64) { _ }; const Timestamp = i64; const Username = std.BoundedArray(u8, 16); const PasswordHash = std.BoundedArray(u8, 128); const SessionToken = u64; const CookieValue = std.BoundedArray(u8, 128); const PostText = std.BoundedArray(u8, 1024); const PostList = db.SetList(PostId, void); const UserList = db.SetList(UserId, User); const VoteList = db.SetList(UserId, Vote); const Chirp = struct { pub fn hash_password(password: []const u8) !PasswordHash { var hash_buffer = try PasswordHash.init(128); // TODO: choose buffer size // TODO: dont allocate on stack, maybe zero memory? var buffer: [1024 * 10]u8 = undefined; var alloc = std.heap.FixedBufferAllocator.init(&buffer); // TODO: choose limits const result = try std.crypto.pwhash.argon2.strHash(password, .{ .allocator = alloc.allocator(), .params = std.crypto.pwhash.argon2.Params.fromLimits(1000, 1024), }, hash_buffer.slice()); try hash_buffer.resize(result.len); return hash_buffer; } pub fn verify_password(password: []const u8, hash: PasswordHash) bool { var buffer: [1024 * 10]u8 = undefined; var alloc = std.heap.FixedBufferAllocator.init(&buffer); if (std.crypto.pwhash.argon2.strVerify(hash.constSlice(), password, .{ .allocator = alloc.allocator(), })) { return true; } else |err| { std.debug.print("verify error: {}\n", .{err}); return false; } } pub fn register_user(env: *lmdb.Env, username: []const u8, password: []const u8) !bool { const username_array = try Username.fromSlice(username); const txn = try env.txn(); defer txn.commit() catch {}; const users = try Db.users(txn); const user_ids = try Db.user_ids(txn); if (try user_ids.has(username_array)) { return false; } else { const user_id = try db.Prng.gen(users.dbi, UserId); const posts = try Db.posts(txn); try users.put(user_id, User{ .id = user_id, .name = username_array, .password_hash = try hash_password(password), .posts = try PostList.init(posts.dbi), }); try user_ids.put(username_array, user_id); return true; } } pub fn login_user( env: *lmdb.Env, username: []const u8, password: []const u8, ) !SessionToken { const username_array = try Username.fromSlice(username); const txn = try env.txn(); defer txn.commit() catch {}; const user_ids = try Db.user_ids(txn); const user_id = try user_ids.get(username_array); std.debug.print("user logging in, id: {}\n", .{user_id}); const users = try Db.users(txn); const user = try users.get(user_id); if (verify_password(password, user.password_hash)) { const sessions = try Db.sessions(txn); const session_token = try db.Prng.gen(sessions.dbi, SessionToken); try sessions.put(session_token, user_id); return session_token; } else { return error.IncorrectPassword; } } fn logout_user(env: *lmdb.Env, session_token: SessionToken) !void { const txn = try env.txn(); defer txn.commit() catch {}; const sessions = try Db.sessions(txn); try sessions.del(session_token); } fn post(env: *lmdb.Env, user_id: UserId, text: []const u8) !void { var post_id: PostId = undefined; // TODO: do this in one commit var txn: lmdb.Txn = undefined; { // create post txn = try env.txn(); defer txn.commit() catch {}; const posts = try Db.posts(txn); post_id = try db.Prng.gen(posts.dbi, PostId); const votes = try txn.dbi("votes"); try posts.put(post_id, Post{ .id = post_id, .user_id = user_id, .time = std.time.timestamp(), .votes = try VoteList.init(votes), .comments = try PostList.init(posts.dbi), .text = try PostText.fromSlice(text), }); } { // append to user's posts txn = try env.txn(); defer txn.commit() catch {}; const users = try Db.users(txn); var user = try users.get(user_id); const posts = try Db.posts(txn); var posts_view = try user.posts.open(posts.dbi); try posts_view.append(post_id, {}); } } fn vote(env: *lmdb.Env, post_id: PostId, user_id: UserId, kind: Vote.Kind) !void { const txn = try env.txn(); defer txn.commit() catch {}; const posts = try Db.posts(txn); const votes = try txn.dbi("votes"); var p = try posts.get(post_id); var votes_view = try p.votes.open(votes); if (try votes_view.has(user_id)) { const old_vote = try votes_view.get(user_id); if (old_vote.kind == kind) { return; } else { try votes_view.del(user_id); if (old_vote.kind == .Up) { p.upvotes -= 1; } else { p.downvotes -= 1; } try posts.put(post_id, p); } } try votes_view.append(user_id, Vote{ .kind = kind, .time = std.time.timestamp(), }); if (kind == .Up) { p.upvotes += 1; } else { p.downvotes += 1; } try posts.put(post_id, p); } fn unvote(env: *lmdb.Env, post_id: PostId, user_id: UserId) !void { const txn = try env.txn(); defer txn.commit() catch {}; const posts = try Db.posts(txn); const votes = try txn.dbi("votes"); var p = try posts.get(post_id); var votes_view = try p.votes.open(votes); if (try votes_view.has(user_id)) { const v = try votes_view.get(user_id); if (v.kind == .Up) { p.upvotes -= 1; } else { p.downvotes -= 1; } try posts.put(post_id, p); try votes_view.del(user_id); } } fn get_session_user_id(env: *lmdb.Env, session_token: SessionToken) !UserId { const txn = try env.txn(); defer txn.abort(); const sessions = try Db.sessions(txn); return try sessions.get(session_token); } fn get_user(env: *lmdb.Env, user_id: UserId) !User { const txn = try env.txn(); defer txn.abort(); const users = try Db.users(txn); return try users.get(user_id); } }; // }}} // html {{{ fn html_form(res: *http.Response, comptime fmt_action: []const u8, args_action: anytype, inputs: anytype) !void { try res.write("
", .{}); } // }}} // write {{{ fn write_header(res: *http.Response, logged_in: ?Login) !void { if (logged_in) |login| { try res.write( \\Home{s}
, .{post.text.constSlice()}); const votes_view = try post.votes.open(votes_dbi); const comments_view = try post.comments.open(posts.dbi); var has_voted: ?Vote.Kind = null; if (login != null and try votes_view.has(login.?.user_id)) { const vote = try votes_view.get(login.?.user_id); has_voted = vote.kind; } if (has_voted != null and has_voted.? == .Up) { try html_form(res, "/unupvote/{}", .{@intFromEnum(post_id)}, .{ .{ "type=\"submit\" value=\"⬆ {}\"", .{post.upvotes} }, }); } else { try html_form(res, "/upvote/{}", .{@intFromEnum(post_id)}, .{ .{ "type=\"submit\" value=\"⬆ {}\"", .{post.upvotes} }, }); } if (has_voted != null and has_voted.? == .Down) { try html_form(res, "/undownvote/{}", .{@intFromEnum(post_id)}, .{ .{ "type=\"submit\" value=\"⬇ {}\"", .{post.downvotes} }, }); } else { try html_form(res, "/downvote/{}", .{@intFromEnum(post_id)}, .{ .{ "type=\"submit\" value=\"⬇ {}\"", .{post.downvotes} }, }); } try res.write( \\💭 {} \\User not found [{}]
, .{err}); } try res.send(); } else { if (logged_in) |login| { const user = try Chirp.get_user(env, login.user_id); const txn = try env.txn(); defer txn.abort(); try write_posts(&res, txn, user, logged_in); try res.send(); } else { try res.write("[GET] {s}", .{req.target}); try res.send(); } } } // api else { if (std.mem.eql(u8, req.target, "/register")) { // TODO: handle args not supplied const username = req.get_value("username").?; const password = req.get_value("password").?; std.debug.print("New user: {s} {s}\n", .{ username, password }); if (try Chirp.register_user(env, username, password)) { try res.redirect("/login"); } else { try res.redirect("/register"); } try res.send(); } else if (std.mem.eql(u8, req.target, "/login")) { // TODO: handle args not supplied const username = req.get_value("username").?; const password = req.get_value("password").?; std.debug.print("New login: {s} {s}\n", .{ username, password }); if (Chirp.login_user(env, username, password)) |session_token| { res.status = .see_other; try res.add_header( "Location", .{ "/user/{s}", .{username} }, ); try res.add_header( "Set-Cookie", .{ "session_token={x}; Secure; HttpOnly", .{session_token} }, ); try res.send(); } else |err| { std.debug.print("login_user err: {}\n", .{err}); try res.redirect("/login"); try res.send(); } } else if (std.mem.eql(u8, req.target, "/logout")) { if (logged_in) |login| { try Chirp.logout_user(env, login.session_token); try res.add_header( "Set-Cookie", .{"session_token=deleted; Expires=Thu, 01 Jan 1970 00:00:00 GMT"}, ); try res.redirect("/"); try res.send(); } } else if (std.mem.eql(u8, req.target, "/post")) { if (logged_in) |login| { const text = req.get_value("text").?; try Chirp.post(env, login.user_id, text); try res.redirect("/"); try res.send(); } } else if (std.mem.eql(u8, req.target, "/quit")) { try res.redirect("/"); try res.send(); break :accept; } else if (std.mem.startsWith(u8, req.target, "/upvote/")) { const login = logged_in orelse return error.NotLoggedIn; const post_id_str = req.target[8..req.target.len]; const post_id: PostId = @enumFromInt(try std.fmt.parseUnsigned(u64, post_id_str, 10)); try Chirp.vote(env, post_id, login.user_id, .Up); if (req.get_header("Referer")) |ref| { try res.redirect(ref); } try res.send(); } else if (std.mem.startsWith(u8, req.target, "/downvote/")) { const login = logged_in orelse return error.NotLoggedIn; const post_id_str = req.target[10..req.target.len]; const post_id: PostId = @enumFromInt(try std.fmt.parseUnsigned(u64, post_id_str, 10)); try Chirp.vote(env, post_id, login.user_id, .Down); if (req.get_header("Referer")) |ref| { try res.redirect(ref); } try res.send(); } else if (std.mem.startsWith(u8, req.target, "/unupvote/")) { // TODO: maybe move to one /unvote? const login = logged_in orelse return error.NotLoggedIn; const post_id_str = req.target[10..req.target.len]; const post_id: PostId = @enumFromInt(try std.fmt.parseUnsigned(u64, post_id_str, 10)); try Chirp.unvote(env, post_id, login.user_id); if (req.get_header("Referer")) |ref| { try res.redirect(ref); } try res.send(); } else if (std.mem.startsWith(u8, req.target, "/undownvote/")) { const login = logged_in orelse return error.NotLoggedIn; const post_id_str = req.target[12..req.target.len]; const post_id: PostId = @enumFromInt(try std.fmt.parseUnsigned(u64, post_id_str, 10)); try Chirp.unvote(env, post_id, login.user_id); if (req.get_header("Referer")) |ref| { try res.redirect(ref); } try res.send(); } else { // try req.respond( // \\POST
// , .{}); try res.write("[POST] {s}
", .{req.target}); try res.send(); } } } } }