feat(auth): finally better auth working as i wanted it to
This commit is contained in:
@@ -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,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user