fediglam/src/api/services/accounts.zig

54 lines
1.6 KiB
Zig
Raw Normal View History

2023-01-02 00:28:36 +00:00
const std = @import("std");
const util = @import("util");
2023-01-03 01:21:08 +00:00
const types = @import("./types.zig");
2023-01-02 00:28:36 +00:00
const Uuid = util.Uuid;
const DateTime = util.DateTime;
2023-01-08 23:35:58 +00:00
const CreateArgs = types.accounts.CreateArgs;
2023-01-03 01:21:08 +00:00
const Credentials = types.accounts.Credentials;
2023-01-02 00:28:36 +00:00
/// Creates a local account with the given information
pub fn create(
db: anytype,
2023-01-08 23:35:58 +00:00
args: CreateArgs,
2023-01-02 00:28:36 +00:00
alloc: std.mem.Allocator,
) !void {
const tx = try db.beginOrSavepoint();
errdefer tx.rollback();
tx.insert("account", .{
2023-01-08 23:35:58 +00:00
.id = args.for_actor,
.invite_id = args.invite_id,
.email = args.email,
.kind = args.role,
2023-01-02 00:28:36 +00:00
}, alloc) catch return error.DatabaseFailure;
tx.insert("password", .{
2023-01-08 23:35:58 +00:00
.account_id = args.for_actor,
.hash = args.password_hash,
2023-01-02 00:28:36 +00:00
.changed_at = DateTime.now(),
}, alloc) catch return error.DatabaseFailure;
tx.commitOrRelease() catch return error.DatabaseFailure;
}
pub fn getCredentialsByUsername(db: anytype, username: []const u8, community_id: Uuid, alloc: std.mem.Allocator) !Credentials {
return db.queryRow(
Credentials,
\\SELECT account.id as account_id, password.hash as password_hash
\\FROM password
\\ JOIN account
\\ JOIN actor
\\ ON password.account_id = account.id AND account.id = actor.id
\\WHERE actor.username = $1
\\ AND actor.community_id = $2
\\LIMIT 1
,
.{ username, community_id },
alloc,
) catch |err| return switch (err) {
error.NoRows => error.InvalidLogin,
else => |e| return e,
};
}