recator placement of code

This commit is contained in:
2026-02-17 11:46:57 -06:00
parent 31f8c368d9
commit 23c000fa7f
77 changed files with 4528 additions and 2697 deletions

View File

@@ -0,0 +1,9 @@
import type { Express } from "express";
import login from "./login.route.js";
import register from "./register.route.js";
export const setupAuthRoutes = (baseUrl: string, app: Express) => {
//setup all the routes
app.use(`${baseUrl}/api/authentication/login`, login);
app.use(`${baseUrl}/api/authentication/register`, register);
};

163
backend/auth/login.route.ts Normal file
View File

@@ -0,0 +1,163 @@
import { APIError } from "better-auth/api";
import { fromNodeHeaders } from "better-auth/node";
import { eq } from "drizzle-orm";
import { Router } from "express";
import z from "zod";
import { db } from "../db/db.controller.js";
import { user } from "../db/schema/auth.schema.js";
import { auth } from "../utils/auth.utils.js";
import { apiReturn } from "../utils/returnHelper.utils.js";
// interface EmailLoginRequest {
// email: string;
// password: string;
// }
// interface LoginResponse {
// redirect: boolean;
// token: string;
// user: {
// name: string;
// email: string;
// emailVerified: boolean;
// image: string | null;
// createdAt: string;
// updatedAt: string;
// role: string;
// banned: boolean;
// banReason: string | null;
// banExpires: string | null;
// username: string;
// displayUsername: string;
// lastLogin: string;
// id: string;
// };
// }
const base = {
password: z.string().min(8, "Password must be at least 8 characters"),
};
const signin = z.union([
z.object({
...base,
email: z.email(),
username: z.undefined(),
}),
z.object({
...base,
username: z.string(),
email: z.undefined(),
}),
]);
const r = Router();
r.post("/", async (req, res) => {
let login: unknown;
try {
const validated = signin.parse(req.body);
if ("email" in validated) {
login = await auth.api.signInEmail({
body: {
email: validated.email as string,
password: validated.password,
},
headers: fromNodeHeaders(req.headers),
});
}
if ("username" in validated) {
const getEmail = await db
.select({ email: user.email })
.from(user)
.where(eq(user.username, validated.username as string));
if (getEmail.length === 0) {
return apiReturn(res, {
success: false,
level: "error", //connect.success ? "info" : "error",
module: "routes",
subModule: "auth",
message: `${validated.username} dose not appear to be a valid username please try again`,
data: [],
status: 401, //connect.success ? 200 : 400,
});
}
// do the login with email
login = await auth.api.signInEmail({
body: {
email: getEmail[0]?.email as string,
password: validated.password,
},
headers: fromNodeHeaders(req.headers),
});
}
// make sure we update the lastLogin
// if (login?.user?.id) {
// const updated = await db
// .update(user)
// .set({ lastLogin: sql`NOW()` })
// .where(eq(user.id, login.user.id))
// .returning({ lastLogin: user.lastLogin });
// const lastLoginTimestamp = updated[0]?.lastLogin;
// console.log("Updated lastLogin:", lastLoginTimestamp);
// } else
// console.warn("User ID unavailable — skipping lastLogin update");
return apiReturn(res, {
success: true,
level: "info", //connect.success ? "info" : "error",
module: "routes",
subModule: "auth",
message: `Welcome back ${validated.username}`,
data: [login],
status: 200, //connect.success ? 200 : 400,
});
} catch (err) {
if (err instanceof z.ZodError) {
const flattened = z.flattenError(err);
// return res.status(400).json({
// error: "Validation failed",
// details: flattened,
// });
return apiReturn(res, {
success: false,
level: "error", //connect.success ? "info" : "error",
module: "routes",
subModule: "auth",
message: "Validation failed",
data: [flattened.fieldErrors],
status: 400, //connect.success ? 200 : 400,
});
}
if (err instanceof APIError) {
return apiReturn(res, {
success: false,
level: "error", //connect.success ? "info" : "error",
module: "routes",
subModule: "auth",
message: err.message,
data: [err.status],
status: 400, //connect.success ? 200 : 400,
});
}
return apiReturn(res, {
success: false,
level: "error",
module: "routes",
subModule: "auth",
message: "System Error",
data: [err],
status: 400,
});
}
});
export default r;

View File

@@ -0,0 +1,125 @@
import { APIError } from "better-auth";
import { count, sql } from "drizzle-orm";
import { Router } from "express";
import z from "zod";
import { db } from "../db/db.controller.js";
import { user } from "../db/schema/auth.schema.js";
import { auth } from "../utils/auth.utils.js";
import { apiReturn } from "../utils/returnHelper.utils.js";
const r = 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, _, and ."),
displayUsername: z
.string()
.min(2)
.max(100)
.optional()
.describe("if you leave blank it will be the same as your username"),
role: z
.enum(["user"])
.optional()
.describe("What roles are available to use."),
data: z
.record(z.string(), z.unknown())
.optional()
.describe(
"This allows us to add extra fields to the data to parse against",
),
});
r.post("/", async (req, res) => {
// 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);
const userCount = totalUsers[0]?.count ?? 0;
try {
// validate the body is correct before accepting it
let validated = registerSchema.parse(req.body);
validated = {
...validated,
data: { lastLogin: new Date(Date.now()) },
username: validated.username,
};
// Call Better Auth signUp
const newUser = await auth.api.signUpEmail({
body: validated,
});
// if we have no users yet lets make this new one the admin
if (userCount === 0) {
// make this user an admin
await db.update(user).set({ role: "admin", updatedAt: sql`NOW()` });
}
apiReturn(res, {
success: true,
level: "info", //connect.success ? "info" : "error",
module: "routes",
subModule: "auth",
message: `${validated.username} was just created`,
data: [newUser],
status: 200, //connect.success ? 200 : 400,
});
} catch (err) {
if (err instanceof z.ZodError) {
const flattened = z.flattenError(err);
// return res.status(400).json({
// error: "Validation failed",
// details: flattened,
// });
apiReturn(res, {
success: false,
level: "error", //connect.success ? "info" : "error",
module: "routes",
subModule: "auth",
message: "Validation failed",
data: [flattened.fieldErrors],
status: 400, //connect.success ? 200 : 400,
});
}
if (err instanceof APIError) {
apiReturn(res, {
success: false,
level: "error", //connect.success ? "info" : "error",
module: "routes",
subModule: "auth",
message: err.message,
data: [err.status],
status: 400, //connect.success ? 200 : 400,
});
}
apiReturn(res, {
success: false,
level: "error", //connect.success ? "info" : "error",
module: "routes",
subModule: "auth",
message: "Internal Server Error creating user",
data: [err],
status: 400, //connect.success ? 200 : 400,
});
}
// apiReturn(res, {
// success: true,
// level: "info", //connect.success ? "info" : "error",
// module: "routes",
// subModule: "auth",
// message: "Testing route",
// data: [],
// status: 200, //connect.success ? 200 : 400,
// });
});
export default r;