1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
|
const std = @import("std");
const lmdb = @import("lmdb");
const http = @import("http");
// db {{{
const Prng = struct {
var prng: std.Random.DefaultPrng = std.Random.DefaultPrng.init(0);
fn IdType(comptime T: type) type {
const ti = @typeInfo(@TypeOf(T.get));
return ti.Fn.params[1].type.?;
}
pub fn gen_id(dbi: anytype) IdType(@TypeOf(dbi)) {
var id: IdType(@TypeOf(dbi)) = @enumFromInt(Prng.prng.next());
while (dbi.has(id)) {
id = @enumFromInt(Prng.prng.next());
}
return id;
}
pub fn gen_str(dbi: anytype, comptime len: usize) [len]u8 {
var buf: [len / 2]u8 = undefined;
var res: [len]u8 = undefined;
Prng.prng.fill(&buf);
for (0..len / 2) |i| {
res[i * 2 + 0] = 'a' + (buf[i] % 16);
res[i * 2 + 1] = 'a' + (buf[i] >> 4 % 16);
}
while (dbi.has(res)) {
Prng.prng.fill(&buf);
for (0..len / 2) |i| {
res[i * 2 + 0] = 'a' + (buf[i] % 16);
res[i * 2 + 1] = 'a' + (buf[i] >> 4 % 16);
}
}
return res;
}
};
const Db = struct {
fn Key(types: anytype) type {
return std.meta.Tuple(&types);
}
fn users(txn: *const lmdb.Txn) !lmdb.Dbi(UserId, User) {
return try txn.dbi("users", UserId, User);
}
fn user_ids(txn: *const lmdb.Txn) !lmdb.Dbi(Username, UserId) {
return try txn.dbi("user_ids", Username, UserId);
}
fn sessions(txn: *const lmdb.Txn) !lmdb.Dbi(SessionToken, UserId) {
return try txn.dbi("sessions", SessionToken, UserId);
}
fn posts(txn: *const lmdb.Txn) !lmdb.Dbi(PostId, Post) {
return try txn.dbi("posts", PostId, Post);
}
fn lists(txn: *const lmdb.Txn, comptime T: type) !lmdb.Dbi(ListId, ListNode(T)) {
return try txn.dbi("lists", ListId, ListNode(T));
}
fn sets(txn: *const lmdb.Txn, comptime T: type) !lmdb.Dbi(Key(.{ SetId, T }), u0) {
return try txn.dbi("sets", Key(.{ SetId, T }), u0);
}
const ListId = enum(u64) { _ };
pub fn ListNode(comptime T: type) type {
return struct {
next: ?ListId,
prev: ?ListId,
data: T,
};
}
pub fn List(comptime T: type) type {
return struct {
const Self = @This();
first: ListId = undefined,
last: ListId = undefined,
len: usize = 0,
pub const Iterator = struct {
dbi: lmdb.Dbi(ListId, ListNode(T)),
id_maybe: ?ListId,
pub fn next(self: *Iterator) ?T {
const id = self.id_maybe orelse return null;
// TODO: how to handle this?
const ln = self.dbi.get(id) orelse return null;
self.id_maybe = ln.next;
return ln.data;
}
};
pub fn it(self: *const Self, txn: *const lmdb.Txn) !Iterator {
const list = try Db.lists(txn, T);
return .{ .dbi = list, .id_maybe = if (self.len > 0) self.first else null };
}
pub fn append(self: *Self, txn: *const lmdb.Txn, t: T) !void {
const list = try Db.lists(txn, T);
const new_id = Prng.gen_id(list);
if (self.len == 0) {
self.first = new_id;
self.last = new_id;
self.len = 1;
list.put(new_id, .{
.next = null,
.prev = null,
.data = t,
});
} else {
const prev_id = self.last;
var last = list.get(prev_id).?;
last.next = new_id;
list.put(prev_id, last);
list.put(new_id, .{
.next = null,
.prev = prev_id,
.data = t,
});
self.last = new_id;
self.len += 1;
}
}
};
}
const SetId = enum(u64) { _ };
pub fn Set(comptime T: type) type {
return struct {
const Self = @This();
const SetKey = Key(.{ SetId, T });
len: usize = 0,
set_id: ?SetId = null,
pub fn init(self: *Self) void {
self.set_id = @enumFromInt(Prng.prng.next());
}
pub fn has(self: Self, txn: *const lmdb.Txn, t: T) !bool {
if (self.set_id == null) return false;
const set = try Db.sets(txn, T);
const key = SetKey{ self.set_id.?, t };
return set.has(key);
}
pub fn add(self: *Self, txn: *const lmdb.Txn, t: T) !void {
if (self.set_id == null) self.init();
const set = try Db.sets(txn, T);
const key = SetKey{ self.set_id.?, t };
if (!set.has(key)) {
set.put(key, 0);
if (set.has(key)) {
self.len += 1;
}
}
}
pub fn del(self: *Self, txn: *const lmdb.Txn, t: T) !void {
if (self.set_id == null) self.init();
const set = try Db.sets(txn, T);
const key = SetKey{ self.set_id.?, t };
if (set.has(key)) {
set.del(key);
if (!set.has(key)) {
self.len -= 1;
}
}
}
};
}
};
// }}}
// content {{{
const User = struct {
// TODO: choose sizes
id: UserId,
username: Username,
password_hash: PasswordHash,
posts: PostList = PostList{},
};
const Post = struct {
id: PostId,
user_id: UserId,
time: Timestamp,
upvotes: UserList = UserList{},
downvotes: UserList = UserList{},
comments: PostList = PostList{},
// reposts
text: PostText,
};
const SessionTokenLen = 16;
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 = [SessionTokenLen]u8;
const CookieValue = std.BoundedArray(u8, 128);
const PostText = std.BoundedArray(u8, 1024);
const PostList = Db.List(PostId);
const UserList = Db.Set(UserId);
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();
env.sync();
}
const users = try Db.users(&txn);
const user_ids = try Db.user_ids(&txn);
if (user_ids.has(username_array)) {
return false;
} else {
const user_id = Prng.gen_id(users);
users.put(user_id, User{
.id = user_id,
.username = username_array,
.password_hash = try hash_password(password),
});
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();
env.sync();
}
const user_ids = try Db.user_ids(&txn);
const user_id = user_ids.get(username_array) orelse return error.UnknownUsername;
std.debug.print("id: {}\n", .{user_id});
const users = try Db.users(&txn);
if (users.get(user_id)) |user| {
if (verify_password(password, user.password_hash)) {
const sessions = try Db.sessions(&txn);
const session_token = Prng.gen_str(sessions, SessionTokenLen);
sessions.put(session_token, user_id);
return session_token;
} else {
return error.IncorrectPassword;
}
} else {
return error.UserNotFound;
}
}
fn logout_user(env: *lmdb.Env, session_token: SessionToken) !void {
const txn = try env.txn();
defer {
txn.commit();
env.sync();
}
const sessions = try Db.sessions(&txn);
sessions.del(session_token);
}
fn post(env: *lmdb.Env, user_id: UserId, text: []const u8) !void {
var post_id: PostId = undefined;
var txn = try env.txn();
{
const posts = try Db.posts(&txn);
post_id = Prng.gen_id(posts);
posts.put(post_id, Post{
.id = post_id,
.user_id = user_id,
.time = std.time.timestamp(),
.text = try PostText.fromSlice(text),
});
txn.commit();
env.sync();
}
txn = try env.txn();
{
const users = try Db.users(&txn);
var user = users.get(user_id) orelse return error.UserNotFound;
try user.posts.append(&txn, post_id);
users.put(user_id, user);
txn.commit();
env.sync();
}
}
fn vote(env: *lmdb.Env, post_id: PostId, user_id: UserId, dir: enum { Up, Down }) !void {
const txn = try env.txn();
defer {
txn.commit();
env.sync();
}
const posts = try Db.posts(&txn);
var p = posts.get(post_id) orelse return error.PostNotFound;
if (dir == .Up) {
try p.upvotes.add(&txn, user_id);
} else {
try p.downvotes.add(&txn, user_id);
}
posts.put(post_id, p);
}
fn unvote(env: *lmdb.Env, post_id: PostId, user_id: UserId, dir: enum { Up, Down }) !void {
const txn = try env.txn();
defer {
txn.commit();
env.sync();
}
const posts = try Db.posts(&txn);
var p = posts.get(post_id) orelse return error.PostNotFound;
if (dir == .Up) {
try p.upvotes.del(&txn, user_id);
} else {
try p.downvotes.del(&txn, user_id);
}
posts.put(post_id, p);
}
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);
if (sessions.get(session_token)) |user_id| {
return user_id;
} else {
return error.SessionNotFound;
}
}
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 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("<form style=\"display: inline-block!important;\" action=\"", .{});
try res.write(fmt_action, args_action);
try res.write("\" method=\"post\">", .{});
inline for (inputs) |input| {
switch (@typeInfo(@TypeOf(input))) {
.Struct => {
try res.write("<input ", .{});
try res.write(input[0], input[1]);
try res.write(" />", .{});
},
else => {
try res.write("<input ", .{});
try res.write(input, .{});
try res.write(" />", .{});
},
}
}
try res.write("</form>", .{});
}
// }}}
// write {{{
fn write_header(res: *http.Response, logged_in: ?Login) !void {
if (logged_in) |login| {
try res.write(
\\<a href="/user/{s}">Home</a><br />
, .{login.user.username.constSlice()});
try html_form(res, "/logout", .{}, .{
\\type="submit" value="Logout"
});
try html_form(res, "/quit", .{}, .{
\\type="submit" value="Quit"
});
try res.write("<br />", .{});
try html_form(res, "/post", .{}, .{
\\type="text" name="text"
,
\\type="submit" value="Post"
});
} else {
try res.write(
\\<a href="/">Home</a><br />
\\<a href="/register">Register</a>
\\<a href="/login">Login</a><br />
, .{});
try html_form(res, "/quit", .{}, .{
\\type="submit" value="Quit"
});
}
}
fn write_posts(res: *http.Response, txn: *const lmdb.Txn, user: User, login: ?Login) !void {
const posts = try Db.posts(txn);
var it = try user.posts.it(txn);
while (it.next()) |post_id| {
const p = posts.get(post_id) orelse break;
try res.write(
\\<div>
\\<p>{s}</p>
, .{p.text.constSlice()});
if (login != null and try p.upvotes.has(txn, login.?.user_id)) {
try html_form(res, "/unupvote/{}", .{@intFromEnum(post_id)}, .{
.{ "type=\"submit\" value=\"⬆ {}\"", .{p.upvotes.len} },
});
} else {
try html_form(res, "/upvote/{}", .{@intFromEnum(post_id)}, .{
.{ "type=\"submit\" value=\"⬆ {}\"", .{p.upvotes.len} },
});
}
if (login != null and try p.downvotes.has(txn, login.?.user_id)) {
try html_form(res, "/undownvote/{}", .{@intFromEnum(post_id)}, .{
.{ "type=\"submit\" value=\"⬇ {}\"", .{p.downvotes.len} },
});
} else {
try html_form(res, "/downvote/{}", .{@intFromEnum(post_id)}, .{
.{ "type=\"submit\" value=\"⬇ {}\"", .{p.downvotes.len} },
});
}
try res.write(
\\<span>💭 {}</span>
\\</div>
, .{p.comments.len});
}
}
// }}}
fn list_users(env: lmdb.Env) !void {
const txn = try env.txn();
defer txn.abort();
// const users = try Db.users(&txn);
const users = try txn.dbi("users", UserId, User);
var cursor = try users.cursor();
var key: UserId = undefined;
var user_maybe = cursor.get(&key, .First);
while (user_maybe) |*user| {
std.debug.print("[{}] {s}\n", .{ key, user.username.constSlice() });
user_maybe = cursor.get(&key, .Next);
}
}
fn list_user_ids(env: lmdb.Env) !void {
const txn = try env.txn();
defer txn.abort();
const user_ids = try Db.user_ids(&txn);
var cursor = try user_ids.cursor();
var key: Username = undefined;
var user_id_maybe = cursor.get(&key, .First);
while (user_id_maybe) |user_id| {
std.debug.print("[{s}] {}\n", .{ key.constSlice(), user_id });
user_id_maybe = cursor.get(&key, .Next);
}
}
fn list_sessions(env: lmdb.Env) !void {
const txn = try env.txn();
defer txn.abort();
const sessions = try Db.sessions(&txn);
var cursor = try sessions.cursor();
var key: SessionToken = undefined;
var user_id_maybe = cursor.get(&key, .First);
while (user_id_maybe) |user_id| {
std.debug.print("[{s}] {}\n", .{ key, user_id });
user_id_maybe = cursor.get(&key, .Next);
}
}
fn list_posts(env: lmdb.Env) !void {
const txn = try env.txn();
defer txn.abort();
const posts = try Db.posts(&txn);
var cursor = try posts.cursor();
var key: PostId = undefined;
var post_maybe = cursor.get(&key, .First);
while (post_maybe) |p| {
std.debug.print("[{}] {s}\n", .{ key, p.text.constSlice() });
post_maybe = cursor.get(&key, .Next);
}
}
const ReqBufferSize = 4096;
const ResHeadBufferSize = 1024 * 16;
const ResBodyBufferSize = 1024 * 16;
pub fn main() !void {
// server
var server = try http.Server.init("::", 8080);
defer server.deinit();
// lmdb
var env = try lmdb.Env.open("db", 1024 * 1024 * 10);
defer env.close();
std.debug.print("Users:\n", .{});
try list_users(env);
std.debug.print("User IDs:\n", .{});
try list_user_ids(env);
std.debug.print("Sessions:\n", .{});
try list_sessions(env);
std.debug.print("Posts:\n", .{});
try list_posts(env);
try handle_connection(&server, &env);
// const ThreadCount = 1;
// var ts: [ThreadCount]std.Thread = undefined;
// for (0..ThreadCount) |i| {
// ts[i] = try std.Thread.spawn(.{}, handle_connection, .{ &server, &env });
// }
// for (0..ThreadCount) |i| {
// ts[i].join();
// }
std.debug.print("done\n", .{});
}
fn handle_connection(server: *http.Server, env: *lmdb.Env) !void {
// TODO: static?
var req_buffer: [ReqBufferSize]u8 = undefined;
var res_head_buffer: [ResHeadBufferSize]u8 = undefined;
var res_body_buffer: [ResBodyBufferSize]u8 = undefined;
accept: while (true) {
server.wait();
while (try server.next_request(&req_buffer)) |req| {
// std.debug.print("[{}]: {s}\n", .{ req.method, req.target });
// reponse
var res = http.Response.init(req.fd, &res_head_buffer, &res_body_buffer);
// check session token
var logged_in: ?Login = null;
if (req.get_cookie("session_token")) |session_token_str| {
var session_token: SessionToken = undefined;
std.mem.copyForwards(u8, &session_token, session_token_str);
// const session_token = try std.fmt.parseUnsigned(SessionToken, session_token_str, 10);
// const session_token = std.mem.bytesToValue(SessionToken, session_token_str);
if (get_session_user_id(env, session_token)) |user_id| {
const txn = try env.txn();
defer txn.abort();
const users = try Db.users(&txn);
logged_in = .{
.user = users.get(user_id) orelse return error.UserNotFound,
.user_id = user_id,
.session_token = session_token,
};
} else |err| {
std.debug.print("get_session_user err: {}\n", .{err});
try res.add_header(
"Set-Cookie",
.{"session_token=deleted; Expires=Thu, 01 Jan 1970 00:00:00 GMT"},
);
}
}
// html
if (req.method == .GET) {
try write_header(&res, logged_in);
if (std.mem.eql(u8, req.target, "/register")) {
try res.write(
\\<form action="/register" method="post">
\\<input type="text" name="username" />
\\<input type="password" name="password" />
\\<input type="submit" value="Register" />
\\</form>
, .{});
try res.send();
} else if (std.mem.eql(u8, req.target, "/login")) {
try res.write(
\\<form action="/login" method="post">
\\<input type="text" name="username" />
\\<input type="password" name="password" />
\\<input type="submit" value="Login" />
\\</form>
, .{});
try res.send();
} else if (std.mem.startsWith(u8, req.target, "/user/")) {
const username = req.target[6..req.target.len];
const txn = try env.txn();
defer txn.abort();
const user_ids = try Db.user_ids(&txn);
if (user_ids.get(try Username.fromSlice(username))) |user_id| {
const users = try Db.users(&txn);
const user = users.get(user_id).?;
try write_posts(&res, &txn, user, logged_in);
} else {
try res.write(
\\<p>User not found</pvo>
, .{});
}
try res.send();
} else {
if (logged_in) |login| {
const user = (try 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 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 (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={s}; 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 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 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 vote(env, post_id, login.user_id, .Up);
try unvote(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, "/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 vote(env, post_id, login.user_id, .Down);
try unvote(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, "/unupvote/")) {
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 unvote(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, "/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 unvote(env, post_id, login.user_id, .Down);
if (req.get_header("Referer")) |ref| {
try res.redirect(ref);
}
try res.send();
} else {
// try req.respond(
// \\<p>POST</p>
// , .{});
try res.write("<p>[POST] {s}</p>", .{req.target});
try res.send();
}
}
}
}
}
|