mirror of
https://github.com/hex248/sprint.git
synced 2026-02-08 10:33:01 +00:00
backend routes with zod schemas
This commit is contained in:
@@ -1,45 +1,32 @@
|
||||
import { LoginRequestSchema } from "@issue/shared";
|
||||
import type { BunRequest } from "bun";
|
||||
import { buildAuthCookie, generateToken, verifyPassword } from "../../auth/utils";
|
||||
import { createSession, getUserByUsername } from "../../db/queries";
|
||||
|
||||
const isNonEmptyString = (value: unknown): value is string =>
|
||||
typeof value === "string" && value.trim().length > 0;
|
||||
import { errorResponse, parseJsonBody } from "../../validation";
|
||||
|
||||
export default async function login(req: BunRequest) {
|
||||
if (req.method !== "POST") {
|
||||
return new Response("method not allowed", { status: 405 });
|
||||
return errorResponse("method not allowed", "METHOD_NOT_ALLOWED", 405);
|
||||
}
|
||||
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return new Response("invalid JSON", { status: 400 });
|
||||
}
|
||||
const parsed = await parseJsonBody(req, LoginRequestSchema);
|
||||
if ("error" in parsed) return parsed.error;
|
||||
|
||||
if (!body || typeof body !== "object") {
|
||||
return new Response("invalid request body", { status: 400 });
|
||||
}
|
||||
|
||||
const { username, password } = body as Record<string, unknown>;
|
||||
|
||||
if (!isNonEmptyString(username) || !isNonEmptyString(password)) {
|
||||
return new Response("username and password are required", { status: 400 });
|
||||
}
|
||||
const { username, password } = parsed.data;
|
||||
|
||||
const user = await getUserByUsername(username);
|
||||
if (!user) {
|
||||
return new Response("invalid credentials", { status: 401 });
|
||||
return errorResponse("invalid credentials", "INVALID_CREDENTIALS", 401);
|
||||
}
|
||||
|
||||
const ok = await verifyPassword(password, user.passwordHash);
|
||||
if (!ok) {
|
||||
return new Response("invalid credentials", { status: 401 });
|
||||
return errorResponse("invalid credentials", "INVALID_CREDENTIALS", 401);
|
||||
}
|
||||
|
||||
const session = await createSession(user.id);
|
||||
if (!session) {
|
||||
return new Response("failed to create session", { status: 500 });
|
||||
return errorResponse("failed to create session", "SESSION_ERROR", 500);
|
||||
}
|
||||
|
||||
const token = generateToken(session.id, user.id);
|
||||
|
||||
Reference in New Issue
Block a user