feat(app): added better auth for better auth stuff vs my home written broken one

This commit is contained in:
2025-09-18 21:46:01 -05:00
parent 21608b0171
commit caf2315191
16 changed files with 648 additions and 25 deletions

View File

@@ -0,0 +1,15 @@
import { Router } from "express";
import { auth } from "../../../pkg/auth/auth.js";
import { fromNodeHeaders } from "better-auth/node";
const router = Router();
// GET /health
router.get("/", async (req, res) => {
const session = await auth.api.getSession({
headers: fromNodeHeaders(req.headers),
});
return res.json(session);
});
export default router;

View File

@@ -0,0 +1,44 @@
import { Router } from "express";
import type { Request, Response } from "express";
import z from "zod";
import { auth } from "../../../pkg/auth/auth.js";
const router = Router();
const registerSchema = z.object({
email: z.email(),
name: z.string().min(2).max(100),
password: z.string().min(8, "Password must be at least 8 characters"),
username: z
.string()
.min(3)
.max(32)
.regex(/^[a-zA-Z0-9_]+$/, "Only alphanumeric + underscores"),
displayUsername: z.string().min(2).max(100).optional(), // optional in your API, but supported
});
router.post("/", async (req: Request, res: Response) => {
try {
// Parse + validate incoming JSON against Zod schema
const validated = registerSchema.parse(req.body);
// Call Better Auth signUp
const user = await auth.api.signUpEmail({
body: validated,
});
return res.status(201).json(user);
} catch (err) {
if (err instanceof z.ZodError) {
const flattened = z.flattenError(err);
return res.status(400).json({
error: "Validation failed",
details: flattened,
});
}
console.error(err);
return res.status(500).json({ error: "Internal server error" });
}
});
export default router;

View File

@@ -0,0 +1,8 @@
import type { Express, Request, Response } from "express";
import me from "./me.js";
import register from "./register.js";
export const setupAuthRoutes = (app: Express, basePath: string) => {
app.use(basePath + "/api/me", me);
app.use(basePath + "/api/auth/register", register);
};

View File

@@ -1,10 +1,14 @@
import type { Express, Request, Response } from "express";
import healthRoutes from "./routes/healthRoutes.js";
import { setupAuthRoutes } from "../auth/routes/routes.js";
export const setupRoutes = (app: Express, basePath: string) => {
// Root / health check
app.use(basePath + "/health", healthRoutes);
app.use(basePath + "/api/system/health", healthRoutes);
// all routes
setupAuthRoutes(app, basePath);
// always try to go to the app weather we are in dev or in production.
app.get(basePath + "/", (req: Request, res: Response) => {