aboutsummaryrefslogtreecommitdiff
path: root/zig-comments/src/main.zig
blob: 951f5f0510a2187c15addd94fef3dcd108e50d22 (plain)
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
const std = @import("std");
const zws = @import("zws");
const pq = @import("pq.zig");
const mustache = @import("mustache");

const Params = zws.Params;

const Err = error{ Overflow, InvalidCharacter, StreamTooLong, ColumnNotFound } || pq.PqError || std.http.Server.Response.WaitError || std.http.Server.Response.DoError || std.http.Server.Response.ReadError || std.http.Server.Response.FinishError || zws.Path.ParseError;
const Ctx = struct {
    db: pq.Db,
    pub fn clone(self: @This()) Ctx {
        return Ctx{
            .db = self.db,
        };
    }
    pub fn deinit(self: @This()) void {
        _ = self;
    }
};

var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const Rtr = zws.Router(Ctx, Err);
const router = Rtr{
    .handlers = &[_]Rtr.Handler{
        .{
            .method = .GET,
            .pattern = "/api/comments",
            .handle_fn = get_comments,
        },
        .{
            .method = .POST,
            .pattern = "/api/comments",
            .handle_fn = post_comments,
        },
        .{
            .method = .GET,
            .pattern = "/api/form/*",
            .handle_fn = get_form,
        },
    },
    .notfound = notfound,
};

pub fn main() !void {
    var db = try pq.Db.init("postgresql://comments@localhost/comments");
    try db.exec(@embedFile("migrations/0_init.sql"));
    try db.exec(@embedFile("migrations/1_capcha.sql"));
    defer db.deinit();
    const server = zws.Server(Ctx, Rtr){
        .allocator = gpa.allocator(),
        .address = std.net.Address{ .in = std.net.Ip4Address.init(.{ 127, 0, 0, 1 }, 8080) },
        .context = Ctx{ .db = db },
        .handler = router,
    };

    try server.serve();
}

fn notfound(res: *std.http.Server.Response, _: Ctx) Err!void {
    const rr = @embedFile("templates/notfound.html");
    try constresponse(res, rr, .not_found);
}

fn badrequest(res: *std.http.Server.Response, _: Ctx) Err!void {
    const rr = @embedFile("templates/badrequest.html");
    try constresponse(res, rr, .bad_request);
}

fn constresponse(res: *std.http.Server.Response, rr: []const u8, status: std.http.Status) Err!void {
    res.status = status;
    res.transfer_encoding = .{ .content_length = rr.len };
    try res.headers.append("content-type", "text/html");
    try res.do();
    try res.writeAll(rr);
    try res.finish();
}

fn get_comments(res: *std.http.Server.Response, ctx: Ctx, _: Params) Err!void {
    _ = ctx;
    // Run SQL
    // Render comments template
    //zws.parse

    const rr = @embedFile("templates/comments.html");
    res.transfer_encoding = .{ .content_length = rr.len };
    try res.headers.append("content-type", "text/html");
    try res.do();
    try res.writeAll(rr);
    try res.finish();
}

fn post_comments(res: *std.http.Server.Response, ctx: Ctx, _: Params) Err!void {
    var body_aa = std.ArrayList(u8).init(res.allocator);
    try res.reader().readAllArrayList(&body_aa, 1_000_000);
    var body = try body_aa.toOwnedSlice();
    var form = try zws.Form.parse(res.allocator, body);
    const Form = struct {
        url: []const u8,
        capcha_id: []const u8,
        author: []const u8,
        comment: []const u8,
        capcha_answer: []const u8,
    };
    const form_val = form.form_to_struct(Form) catch {
        try badrequest(res, ctx);
        return;
    };

    // Validate the capcha
    {
        var stmt = try ctx.db.prepare_statement(res.allocator, "select answer from capchas where id = $1");
        defer stmt.deinit();
        try stmt.bind(0, form_val.capcha_id);
        if (!try stmt.step()) {
            std.log.err("missing capcha_id {s}", .{form_val.capcha_id});
            try badrequest(res, ctx);
            return;
        }
        const ans = try stmt.read_column(0, []const u8);
        if (!std.mem.eql(u8, ans, form_val.capcha_answer)) {
            try constresponse(res, @embedFile("templates/capchainvalid.html"), std.http.Status.unauthorized);
            return;
        }
    }

    // Add the comment...
    {
        var stmt = try ctx.db.prepare_statement(res.allocator, "insert into comments(url,author,comment) values($1, $2, $3)");
        defer stmt.deinit();
        try stmt.bind(0, form_val.url);
        try stmt.bind(1, form_val.author);
        try stmt.bind(2, form_val.comment);
        _ = try stmt.step();
    }

    // And redirect!
    res.transfer_encoding = .none;
    res.status = .found;
    try res.headers.append("location", form_val.url);
    try res.do();
    try res.finish();
}

fn get_form(res: *std.http.Server.Response, ctx: Ctx, _: Params) Err!void {
    var p = try zws.Path.parse(res.allocator, res.request.target);
    defer p.deinit();
    const url: []const u8 = try p.get_query_param("url") orelse {
        try badrequest(res, ctx);
        return;
    };

    var stmt = try ctx.db.prepare_statement(res.allocator, "select id, question from capchas order by random() limit 1");
    defer stmt.deinit();
    if (!try stmt.step()) {
        std.log.err("no capcha!", .{});
        try badrequest(res, ctx);
        return;
    }
    const Capcha = struct {
        id: []const u8,
        question: []const u8,
    };
    const capcha = try stmt.read_struct(Capcha);

    const rr = @embedFile("templates/form.html");
    const tt = comptime mustache.parseComptime(rr, .{}, .{});

    res.transfer_encoding = .chunked;
    try res.headers.append("content-type", "text/html");
    try res.do();
    // For some reason, mustache.render won't work with anonymous struct
    const data = struct {
        capcha_id: []const u8,
        capcha_question: []const u8,
        url: []const u8,
    };
    try mustache.render(tt, data{
        .capcha_id = capcha.id,
        .capcha_question = capcha.question,
        .url = url,
    }, res.writer());
    try res.finish();
}