fediglam/src/main/controllers/web.zig

112 lines
3.1 KiB
Zig

const std = @import("std");
const util = @import("util");
const controllers = @import("../controllers.zig");
pub const routes = .{
controllers.apiEndpoint(index),
controllers.apiEndpoint(about),
controllers.apiEndpoint(login),
controllers.apiEndpoint(global_timeline),
controllers.apiEndpoint(cluster.overview),
controllers.apiEndpoint(media),
};
const index = struct {
pub const path = "/";
pub const method = .GET;
pub fn handler(_: anytype, res: anytype, srv: anytype) !void {
if (srv.user_id == null) {
try res.headers.put("Location", about.path);
return res.status(.see_other);
}
try res.template(.ok, "Hello", .{});
}
};
const about = struct {
pub const path = "/about";
pub const method = .GET;
pub fn handler(_: anytype, res: anytype, srv: anytype) !void {
try res.template(.ok, tmpl, .{
.community = srv.community,
});
}
const tmpl = @embedFile("./web/index.tmpl.html");
};
const login = struct {
pub const path = "/login";
pub const method = .POST;
pub const Body = struct {
username: []const u8,
password: []const u8,
};
pub fn handler(req: anytype, res: anytype, srv: anytype) !void {
const token = try srv.login(req.body.username, req.body.password);
try res.headers.put("Location", index.path);
var buf: [64]u8 = undefined;
const cookie_name = try std.fmt.bufPrint(&buf, "token.{s}", .{req.body.username});
try res.headers.setCookie(cookie_name, token.token, .{});
try res.headers.setCookie("active_account", req.body.username, .{ .HttpOnly = false });
try res.status(.see_other);
}
};
const global_timeline = struct {
pub const path = "/timelines/global";
pub const method = .GET;
pub fn handler(req: anytype, res: anytype, srv: anytype) !void {
_ = req;
const timeline = try srv.globalTimeline(.{});
try res.template(.ok, @embedFile("./web/timelines/global.tmpl.html"), .{
.notes = timeline.items,
.community = srv.community,
});
}
};
const cluster = struct {
const overview = struct {
pub const path = "/cluster/overview";
pub const method = .GET;
pub fn handler(_: anytype, res: anytype, srv: anytype) !void {
const meta = try srv.getClusterMeta();
try res.template(.ok, @embedFile("./web/cluster/overview.tmpl.html"), .{
.community = srv.community,
.meta = meta,
});
}
};
};
const media = struct {
pub const path = "/media/:id";
pub const method = .GET;
pub const Args = struct {
id: util.Uuid,
};
pub fn handler(req: anytype, res: anytype, srv: anytype) !void {
const result = try srv.fileDereference(req.args.id);
defer util.deepFree(srv.allocator, result);
try res.headers.put("Content-Type", result.meta.content_type orelse "application/octet-stream");
var stream = try res.open(.ok);
defer stream.close();
try stream.writer().writeAll(result.data);
try stream.finish();
}
};