This commit is contained in:
user
2026-03-27 20:06:38 +02:00
commit 8c45efc92e
544 changed files with 33060 additions and 0 deletions

View File

@@ -0,0 +1,250 @@
import { FlowExecCtx } from "@/core/flow.execution.context";
import { traceResultAsync } from "@core/observability";
import { ERROR_CODES, type Err } from "@pkg/result";
import { getError, logDomainEvent } from "@pkg/logger";
import { auth } from "../auth/config.base";
import { account } from "@pkg/db/schema";
import { ResultAsync, errAsync, okAsync } from "neverthrow";
import { Database, eq } from "@pkg/db";
import { nanoid } from "nanoid";
export class AccountRepository {
constructor(private db: Database) {}
private dbError(fctx: FlowExecCtx, detail: string): Err {
return getError({
flowId: fctx.flowId,
code: ERROR_CODES.DATABASE_ERROR,
message: "Database operation failed",
description: "Please try again later",
detail,
});
}
private accountNotFound(fctx: FlowExecCtx): Err {
return getError({
flowId: fctx.flowId,
code: ERROR_CODES.NOT_FOUND,
message: "Account not found",
description: "Please try again later",
detail: "Account not found for user",
});
}
ensureAccountExists(
fctx: FlowExecCtx,
userId: string,
): ResultAsync<boolean, Err> {
return traceResultAsync({
name: "logic.user.repository.ensureAccountExists",
fctx,
attributes: { "app.user.id": userId },
fn: () => {
const startedAt = Date.now();
logDomainEvent({
event: "account.ensure_exists.started",
fctx,
meta: { userId },
});
return ResultAsync.fromPromise(
this.db.query.account.findFirst({
where: eq(account.userId, userId),
}),
(error) => {
logDomainEvent({
level: "error",
event: "account.ensure_exists.failed",
fctx,
durationMs: Date.now() - startedAt,
error,
meta: { userId },
});
return this.dbError(
fctx,
error instanceof Error ? error.message : String(error),
);
},
).andThen((existingAccount) => {
if (existingAccount) {
logDomainEvent({
event: "account.ensure_exists.succeeded",
fctx,
durationMs: Date.now() - startedAt,
meta: { userId, existed: true },
});
return okAsync(true);
}
return ResultAsync.fromPromise(
auth.$context.then((ctx) => ctx.password.hash(nanoid())),
(error) => {
logDomainEvent({
level: "error",
event: "account.ensure_exists.failed",
fctx,
durationMs: Date.now() - startedAt,
error,
meta: { userId, stage: "hash_password" },
});
return this.dbError(
fctx,
error instanceof Error
? error.message
: String(error),
);
},
).andThen((password) => {
const aid = nanoid();
return ResultAsync.fromPromise(
this.db
.insert(account)
.values({
id: aid,
accountId: userId,
providerId: "credential",
userId,
password,
createdAt: new Date(),
updatedAt: new Date(),
})
.execute(),
(error) => {
logDomainEvent({
level: "error",
event: "account.ensure_exists.failed",
fctx,
durationMs: Date.now() - startedAt,
error,
meta: { userId, stage: "create_account" },
});
return this.dbError(
fctx,
error instanceof Error
? error.message
: String(error),
);
},
).map(() => {
logDomainEvent({
event: "account.ensure_exists.succeeded",
fctx,
durationMs: Date.now() - startedAt,
meta: { userId, existed: false },
});
return false;
});
});
});
},
});
}
rotatePassword(
fctx: FlowExecCtx,
userId: string,
password: string,
): ResultAsync<string, Err> {
return traceResultAsync({
name: "logic.user.repository.rotatePassword",
fctx,
attributes: { "app.user.id": userId },
fn: () => {
const startedAt = Date.now();
logDomainEvent({
event: "account.rotate_password.started",
fctx,
meta: { userId },
});
return ResultAsync.fromPromise(
this.db.query.account.findFirst({
where: eq(account.userId, userId),
}),
(error) => {
logDomainEvent({
level: "error",
event: "account.rotate_password.failed",
fctx,
durationMs: Date.now() - startedAt,
error,
meta: { userId, stage: "check_exists" },
});
return this.dbError(
fctx,
error instanceof Error
? error.message
: String(error),
);
},
).andThen((existingAccount) => {
if (!existingAccount) {
logDomainEvent({
level: "warn",
event: "account.rotate_password.failed",
fctx,
durationMs: Date.now() - startedAt,
error: { code: "NOT_FOUND", message: "Account not found" },
meta: { userId },
});
return errAsync(this.accountNotFound(fctx));
}
return ResultAsync.fromPromise(
auth.$context.then((ctx) => ctx.password.hash(password)),
(error) => {
logDomainEvent({
level: "error",
event: "account.rotate_password.failed",
fctx,
durationMs: Date.now() - startedAt,
error,
meta: { userId, stage: "hash_password" },
});
return this.dbError(
fctx,
error instanceof Error
? error.message
: String(error),
);
},
).andThen((hashed) => {
return ResultAsync.fromPromise(
this.db
.update(account)
.set({ password: hashed })
.where(eq(account.userId, userId))
.returning()
.execute(),
(error) => {
logDomainEvent({
level: "error",
event: "account.rotate_password.failed",
fctx,
durationMs: Date.now() - startedAt,
error,
meta: { userId, stage: "update_password" },
});
return this.dbError(
fctx,
error instanceof Error
? error.message
: String(error),
);
},
).map(() => {
logDomainEvent({
event: "account.rotate_password.succeeded",
fctx,
durationMs: Date.now() - startedAt,
meta: { userId },
});
return password;
});
});
});
},
});
}
}

View File

@@ -0,0 +1,96 @@
import { FlowExecCtx } from "@/core/flow.execution.context";
import { traceResultAsync } from "@core/observability";
import { AccountRepository } from "./account.repository";
import { UserRepository } from "./repository";
import { db } from "@pkg/db";
export class UserController {
constructor(
private userRepository: UserRepository,
private accountRepo: AccountRepository,
) {}
getUserInfo(fctx: FlowExecCtx, userId: string) {
return traceResultAsync({
name: "logic.user.controller.getUserInfo",
fctx,
attributes: { "app.user.id": userId },
fn: () => this.userRepository.getUserInfo(fctx, userId),
});
}
ensureAccountExists(fctx: FlowExecCtx, userId: string) {
return traceResultAsync({
name: "logic.user.controller.ensureAccountExists",
fctx,
attributes: { "app.user.id": userId },
fn: () => this.accountRepo.ensureAccountExists(fctx, userId),
});
}
isUsernameAvailable(fctx: FlowExecCtx, username: string) {
return traceResultAsync({
name: "logic.user.controller.isUsernameAvailable",
fctx,
attributes: { "app.user.username": username },
fn: () => this.userRepository.isUsernameAvailable(fctx, username),
});
}
updateLastVerified2FaAtToNow(fctx: FlowExecCtx, userId: string) {
return traceResultAsync({
name: "logic.user.controller.updateLastVerified2FaAtToNow",
fctx,
attributes: { "app.user.id": userId },
fn: () => this.userRepository.updateLastVerified2FaAtToNow(fctx, userId),
});
}
banUser(
fctx: FlowExecCtx,
userId: string,
reason: string,
banExpiresAt: Date,
) {
return traceResultAsync({
name: "logic.user.controller.banUser",
fctx,
attributes: { "app.user.id": userId },
fn: () => this.userRepository.banUser(fctx, userId, reason, banExpiresAt),
});
}
isUserBanned(fctx: FlowExecCtx, userId: string) {
return traceResultAsync({
name: "logic.user.controller.isUserBanned",
fctx,
attributes: { "app.user.id": userId },
fn: () => this.userRepository.isUserBanned(fctx, userId),
});
}
getBanInfo(fctx: FlowExecCtx, userId: string) {
return traceResultAsync({
name: "logic.user.controller.getBanInfo",
fctx,
attributes: { "app.user.id": userId },
fn: () => this.userRepository.getBanInfo(fctx, userId),
});
}
rotatePassword(fctx: FlowExecCtx, userId: string, password: string) {
return traceResultAsync({
name: "logic.user.controller.rotatePassword",
fctx,
attributes: { "app.user.id": userId },
fn: () => this.accountRepo.rotatePassword(fctx, userId, password),
});
}
}
export function getUserController(): UserController {
return new UserController(
new UserRepository(db),
new AccountRepository(db),
);
}

View File

@@ -0,0 +1,159 @@
import { Session } from "better-auth";
import * as v from "valibot";
export type { Session } from "better-auth";
export type ModifiedSession = Session & { isCurrent?: boolean };
// User role enum
export enum UserRoleMap {
user = "user",
admin = "admin",
}
// User role schema
export const userRoleSchema = v.picklist(["user", "admin"]);
export type UserRole = v.InferOutput<typeof userRoleSchema>;
// User schema
export const userSchema = v.object({
id: v.string(),
name: v.string(),
email: v.string(),
emailVerified: v.boolean(),
image: v.optional(v.string()),
createdAt: v.date(),
updatedAt: v.date(),
username: v.optional(v.string()),
displayUsername: v.optional(v.string()),
role: v.optional(v.string()),
banned: v.optional(v.boolean()),
banReason: v.optional(v.string()),
banExpires: v.optional(v.date()),
onboardingDone: v.optional(v.boolean()),
last2FAVerifiedAt: v.optional(v.date()),
parentId: v.optional(v.string()),
});
export type User = v.InferOutput<typeof userSchema>;
// Account schema
export const accountSchema = v.object({
id: v.string(),
accountId: v.string(),
providerId: v.string(),
userId: v.string(),
accessToken: v.string(),
refreshToken: v.string(),
idToken: v.string(),
accessTokenExpiresAt: v.date(),
refreshTokenExpiresAt: v.date(),
scope: v.string(),
password: v.string(),
createdAt: v.date(),
updatedAt: v.date(),
});
export type Account = v.InferOutput<typeof accountSchema>;
// Ensure account exists schema
export const ensureAccountExistsSchema = v.object({
userId: v.string(),
});
export type EnsureAccountExists = v.InferOutput<
typeof ensureAccountExistsSchema
>;
// Ban info schema
export const banInfoSchema = v.object({
banned: v.boolean(),
reason: v.optional(v.string()),
expires: v.optional(v.date()),
});
export type BanInfo = v.InferOutput<typeof banInfoSchema>;
// Ban user schema
export const banUserSchema = v.object({
userId: v.string(),
reason: v.string(),
banExpiresAt: v.date(),
});
export type BanUser = v.InferOutput<typeof banUserSchema>;
// Check username availability schema
export const checkUsernameSchema = v.object({
username: v.string(),
});
export type CheckUsername = v.InferOutput<typeof checkUsernameSchema>;
// Rotate password schema
export const rotatePasswordSchema = v.object({
userId: v.string(),
password: v.string(),
});
export type RotatePassword = v.InferOutput<typeof rotatePasswordSchema>;
// View Model specific types
// Search and filter types
export const searchFieldSchema = v.picklist(["email", "name", "username"]);
export type SearchField = v.InferOutput<typeof searchFieldSchema>;
export const searchOperatorSchema = v.picklist([
"contains",
"starts_with",
"ends_with",
]);
export type SearchOperator = v.InferOutput<typeof searchOperatorSchema>;
export const filterOperatorSchema = v.picklist([
"eq",
"ne",
"lt",
"lte",
"gt",
"gte",
]);
export type FilterOperator = v.InferOutput<typeof filterOperatorSchema>;
export const sortDirectionSchema = v.picklist(["asc", "desc"]);
export type SortDirection = v.InferOutput<typeof sortDirectionSchema>;
// Users query state
export const usersQueryStateSchema = v.object({
// searching
searchValue: v.optional(v.string()),
searchField: v.optional(searchFieldSchema),
searchOperator: v.optional(searchOperatorSchema),
// pagination
limit: v.pipe(v.number(), v.integer()),
offset: v.pipe(v.number(), v.integer()),
// sorting
sortBy: v.optional(v.string()),
sortDirection: v.optional(sortDirectionSchema),
// filtering
filterField: v.optional(v.string()),
filterValue: v.optional(v.union([v.string(), v.number(), v.boolean()])),
filterOperator: v.optional(filterOperatorSchema),
});
export type UsersQueryState = v.InferOutput<typeof usersQueryStateSchema>;
// UI View Model types
export const banExpiryModeSchema = v.picklist([
"never",
"1d",
"7d",
"30d",
"custom",
]);
export type BanExpiryMode = v.InferOutput<typeof banExpiryModeSchema>;
export const createUserFormSchema = v.object({
email: v.string(),
password: v.string(),
name: v.string(),
role: v.union([userRoleSchema, v.array(userRoleSchema)]),
});
export type CreateUserForm = v.InferOutput<typeof createUserFormSchema>;

View File

@@ -0,0 +1,77 @@
import { FlowExecCtx } from "@/core/flow.execution.context";
import { ERROR_CODES, type Err } from "@pkg/result";
import { getError } from "@pkg/logger";
export const userErrors = {
dbError: (fctx: FlowExecCtx, detail: string): Err =>
getError({
flowId: fctx.flowId,
code: ERROR_CODES.DATABASE_ERROR,
message: "Database operation failed",
description: "Please try again later",
detail,
}),
userNotFound: (fctx: FlowExecCtx): Err =>
getError({
flowId: fctx.flowId,
code: ERROR_CODES.NOT_FOUND,
message: "User not found",
description: "Try with a different user id",
detail: "User not found in database",
}),
usernameCheckFailed: (fctx: FlowExecCtx, detail: string): Err =>
getError({
flowId: fctx.flowId,
code: ERROR_CODES.DATABASE_ERROR,
message: "An error occurred while checking username availability",
description: "Try again later",
detail,
}),
banOperationFailed: (fctx: FlowExecCtx, detail: string): Err =>
getError({
flowId: fctx.flowId,
code: ERROR_CODES.DATABASE_ERROR,
message: "Failed to perform ban operation",
description: "Please try again later",
detail,
}),
unbanFailed: (fctx: FlowExecCtx, detail: string): Err =>
getError({
flowId: fctx.flowId,
code: ERROR_CODES.DATABASE_ERROR,
message: "Failed to unban user",
description: "Please try again later",
detail,
}),
updateFailed: (fctx: FlowExecCtx, detail: string): Err =>
getError({
flowId: fctx.flowId,
code: ERROR_CODES.DATABASE_ERROR,
message: "Failed to update user",
description: "Please try again later",
detail,
}),
getUserInfoFailed: (fctx: FlowExecCtx, detail: string): Err =>
getError({
flowId: fctx.flowId,
code: ERROR_CODES.DATABASE_ERROR,
message: "An error occurred while getting user info",
description: "Try again later",
detail,
}),
getBanInfoFailed: (fctx: FlowExecCtx, detail: string): Err =>
getError({
flowId: fctx.flowId,
code: ERROR_CODES.DATABASE_ERROR,
message: "An error occurred while getting ban info",
description: "Try again later",
detail,
}),
};

View File

@@ -0,0 +1,420 @@
import { ResultAsync, errAsync, okAsync } from "neverthrow";
import { FlowExecCtx } from "@core/flow.execution.context";
import { traceResultAsync } from "@core/observability";
import { type Err } from "@pkg/result";
import { Database, eq } from "@pkg/db";
import { BanInfo, User } from "./data";
import { user } from "@pkg/db/schema";
import { userErrors } from "./errors";
import { logDomainEvent } from "@pkg/logger";
export class UserRepository {
constructor(private db: Database) {}
getUserInfo(fctx: FlowExecCtx, userId: string): ResultAsync<User, Err> {
return traceResultAsync({
name: "logic.user.repository.getUserInfo",
fctx,
attributes: { "app.user.id": userId },
fn: () => {
const startedAt = Date.now();
logDomainEvent({
event: "user.get_info.started",
fctx,
meta: { userId },
});
return ResultAsync.fromPromise(
this.db.query.user.findFirst({
where: eq(user.id, userId),
}),
(error) => {
logDomainEvent({
level: "error",
event: "user.get_info.failed",
fctx,
durationMs: Date.now() - startedAt,
error,
meta: { userId },
});
return userErrors.getUserInfoFailed(
fctx,
error instanceof Error ? error.message : String(error),
);
},
).andThen((userData) => {
if (!userData) {
logDomainEvent({
level: "warn",
event: "user.get_info.failed",
fctx,
durationMs: Date.now() - startedAt,
error: { code: "NOT_FOUND", message: "User not found" },
meta: { userId },
});
return errAsync(userErrors.userNotFound(fctx));
}
logDomainEvent({
event: "user.get_info.succeeded",
fctx,
durationMs: Date.now() - startedAt,
meta: { userId },
});
return okAsync(userData as User);
});
},
});
}
isUsernameAvailable(
fctx: FlowExecCtx,
username: string,
): ResultAsync<boolean, Err> {
return traceResultAsync({
name: "logic.user.repository.isUsernameAvailable",
fctx,
attributes: { "app.user.username": username },
fn: () => {
const startedAt = Date.now();
logDomainEvent({
event: "user.username_check.started",
fctx,
});
return ResultAsync.fromPromise(
this.db.query.user.findFirst({
where: eq(user.username, username),
}),
(error) => {
logDomainEvent({
level: "error",
event: "user.username_check.failed",
fctx,
durationMs: Date.now() - startedAt,
error,
});
return userErrors.usernameCheckFailed(
fctx,
error instanceof Error ? error.message : String(error),
);
},
).map((existingUser) => {
const isAvailable = !existingUser?.id;
logDomainEvent({
event: "user.username_check.succeeded",
fctx,
durationMs: Date.now() - startedAt,
meta: { isAvailable },
});
return isAvailable;
});
},
});
}
updateLastVerified2FaAtToNow(
fctx: FlowExecCtx,
userId: string,
): ResultAsync<boolean, Err> {
return traceResultAsync({
name: "logic.user.repository.updateLastVerified2FaAtToNow",
fctx,
attributes: { "app.user.id": userId },
fn: () => {
const startedAt = Date.now();
logDomainEvent({
event: "user.update_last_2fa.started",
fctx,
meta: { userId },
});
return ResultAsync.fromPromise(
this.db
.update(user)
.set({ last2FAVerifiedAt: new Date() })
.where(eq(user.id, userId))
.execute(),
(error) => {
logDomainEvent({
level: "error",
event: "user.update_last_2fa.failed",
fctx,
durationMs: Date.now() - startedAt,
error,
meta: { userId },
});
return userErrors.updateFailed(
fctx,
error instanceof Error ? error.message : String(error),
);
},
).map(() => {
logDomainEvent({
event: "user.update_last_2fa.succeeded",
fctx,
durationMs: Date.now() - startedAt,
meta: { userId },
});
return true;
});
},
});
}
banUser(
fctx: FlowExecCtx,
userId: string,
reason: string,
banExpiresAt: Date,
): ResultAsync<boolean, Err> {
return traceResultAsync({
name: "logic.user.repository.banUser",
fctx,
attributes: { "app.user.id": userId },
fn: () => {
const startedAt = Date.now();
logDomainEvent({
event: "user.ban.started",
fctx,
meta: {
userId,
reasonLength: reason.length,
banExpiresAt: banExpiresAt.toISOString(),
},
});
return ResultAsync.fromPromise(
this.db
.update(user)
.set({
banned: true,
banReason: reason,
banExpires: banExpiresAt,
})
.where(eq(user.id, userId))
.execute(),
(error) => {
logDomainEvent({
level: "error",
event: "user.ban.failed",
fctx,
durationMs: Date.now() - startedAt,
error,
meta: { userId },
});
return userErrors.banOperationFailed(
fctx,
error instanceof Error ? error.message : String(error),
);
},
).map(() => {
logDomainEvent({
event: "user.ban.succeeded",
fctx,
durationMs: Date.now() - startedAt,
meta: { userId },
});
return true;
});
},
});
}
isUserBanned(fctx: FlowExecCtx, userId: string): ResultAsync<boolean, Err> {
return traceResultAsync({
name: "logic.user.repository.isUserBanned",
fctx,
attributes: { "app.user.id": userId },
fn: () => {
const startedAt = Date.now();
logDomainEvent({
event: "user.is_banned.started",
fctx,
meta: { userId },
});
return ResultAsync.fromPromise(
this.db.query.user.findFirst({
where: eq(user.id, userId),
columns: {
banned: true,
banExpires: true,
},
}),
(error) => {
logDomainEvent({
level: "error",
event: "user.is_banned.failed",
fctx,
durationMs: Date.now() - startedAt,
error,
meta: { userId },
});
return userErrors.dbError(
fctx,
error instanceof Error ? error.message : String(error),
);
},
).andThen((userData) => {
if (!userData) {
logDomainEvent({
level: "warn",
event: "user.is_banned.failed",
fctx,
durationMs: Date.now() - startedAt,
error: { code: "NOT_FOUND", message: "User not found" },
meta: { userId },
});
return errAsync(userErrors.userNotFound(fctx));
}
if (!userData.banned) {
logDomainEvent({
event: "user.is_banned.succeeded",
fctx,
durationMs: Date.now() - startedAt,
meta: { userId, isBanned: false },
});
return okAsync(false);
}
if (!userData.banExpires) {
logDomainEvent({
event: "user.is_banned.succeeded",
fctx,
durationMs: Date.now() - startedAt,
meta: { userId, isBanned: true, isPermanent: true },
});
return okAsync(true);
}
const now = new Date();
if (userData.banExpires <= now) {
return ResultAsync.fromPromise(
this.db
.update(user)
.set({
banned: false,
banReason: null,
banExpires: null,
})
.where(eq(user.id, userId))
.execute(),
(error) => {
logDomainEvent({
level: "error",
event: "user.unban_after_expiry.failed",
fctx,
durationMs: Date.now() - startedAt,
error,
meta: { userId },
});
return userErrors.unbanFailed(
fctx,
error instanceof Error
? error.message
: String(error),
);
},
)
.map(() => {
logDomainEvent({
event: "user.unban_after_expiry.succeeded",
fctx,
durationMs: Date.now() - startedAt,
meta: { userId },
});
return false;
})
.orElse((error) => {
logDomainEvent({
level: "warn",
event: "user.is_banned.succeeded",
fctx,
durationMs: Date.now() - startedAt,
error,
meta: { userId, degraded: true, isBanned: true },
});
return okAsync(true);
});
}
logDomainEvent({
event: "user.is_banned.succeeded",
fctx,
durationMs: Date.now() - startedAt,
meta: {
userId,
isBanned: true,
banExpires: userData.banExpires.toISOString(),
},
});
return okAsync(true);
});
},
});
}
getBanInfo(fctx: FlowExecCtx, userId: string): ResultAsync<BanInfo, Err> {
return traceResultAsync({
name: "logic.user.repository.getBanInfo",
fctx,
attributes: { "app.user.id": userId },
fn: () => {
const startedAt = Date.now();
logDomainEvent({
event: "user.ban_info.started",
fctx,
meta: { userId },
});
return ResultAsync.fromPromise(
this.db.query.user.findFirst({
where: eq(user.id, userId),
columns: { banned: true, banReason: true, banExpires: true },
}),
(error) => {
logDomainEvent({
level: "error",
event: "user.ban_info.failed",
fctx,
durationMs: Date.now() - startedAt,
error,
meta: { userId },
});
return userErrors.getBanInfoFailed(
fctx,
error instanceof Error ? error.message : String(error),
);
},
).andThen((userData) => {
if (!userData) {
logDomainEvent({
level: "warn",
event: "user.ban_info.failed",
fctx,
durationMs: Date.now() - startedAt,
error: { code: "NOT_FOUND", message: "User not found" },
meta: { userId },
});
return errAsync(userErrors.userNotFound(fctx));
}
logDomainEvent({
event: "user.ban_info.succeeded",
fctx,
durationMs: Date.now() - startedAt,
meta: { userId, banned: userData.banned || false },
});
return okAsync({
banned: userData.banned || false,
reason: userData.banReason || undefined,
expires: userData.banExpires || undefined,
});
});
},
});
}
}