feat(auth): finally better auth working as i wanted it to

This commit is contained in:
2025-09-22 22:40:44 -05:00
parent 4ab43d91b9
commit 8f1375ab7b
50 changed files with 7939 additions and 5909 deletions

View File

@@ -2,6 +2,11 @@ import { Router } from "express";
import type { Request, Response } from "express";
import z from "zod";
import { auth } from "../../../pkg/auth/auth.js";
import { db } from "../../../pkg/db/db.js";
import { count } from "drizzle-orm";
import { user } from "../../../pkg/db/schema/auth-schema.js";
import { APIError, betterAuth } from "better-auth";
import { systemAdminRole } from "../../admin/controller/systemAdminRole.js";
const router = Router();
@@ -18,6 +23,9 @@ const registerSchema = z.object({
});
router.post("/", async (req: Request, res: Response) => {
// check if we are the first user so we can add as system admin to all modules
const totalUsers = await db.select({ count: count() }).from(user);
console.log(totalUsers[0].count);
try {
// Parse + validate incoming JSON against Zod schema
const validated = registerSchema.parse(req.body);
@@ -27,6 +35,9 @@ router.post("/", async (req: Request, res: Response) => {
body: validated,
});
if (totalUsers[0].count === 0) {
systemAdminRole(user.user.id);
}
return res.status(201).json(user);
} catch (err) {
if (err instanceof z.ZodError) {
@@ -36,8 +47,14 @@ router.post("/", async (req: Request, res: Response) => {
details: flattened,
});
}
console.error(err);
return res.status(500).json({ error: "Internal server error" });
if (err instanceof APIError) {
return res.status(400).json({
success: false,
message: err.message,
error: err.status,
});
}
}
});