feat: auth client middleware

This commit is contained in:
Nicolas Meienberger
2025-10-02 21:28:08 +02:00
parent 0120641e3a
commit 2be7e18ab5
15 changed files with 368 additions and 46 deletions

View File

@@ -1,7 +1,16 @@
import { arktypeValidator } from "@hono/arktype-validator";
import { validator } from "hono-openapi";
import { Hono } from "hono";
import { deleteCookie, getCookie, setCookie } from "hono/cookie";
import { getMeDto, loginBodySchema, loginDto, logoutDto, registerBodySchema, registerDto } from "./auth.dto";
import {
getMeDto,
getStatusDto,
loginBodySchema,
loginDto,
logoutDto,
registerBodySchema,
registerDto,
} from "./auth.dto";
import { authService } from "./auth.service";
const COOKIE_NAME = "session_id";
@@ -13,24 +22,23 @@ const COOKIE_OPTIONS = {
};
export const authController = new Hono()
.post("/register", registerDto, arktypeValidator("json", registerBodySchema), async (c) => {
.post("/register", registerDto, validator("json", registerBodySchema), async (c) => {
const body = c.req.valid("json");
try {
const { user } = await authService.register(body.username, body.password);
const { user, sessionId } = await authService.register(body.username, body.password);
return c.json(
{
message: "User registered successfully",
user: { id: user.id, username: user.username },
},
201,
);
setCookie(c, COOKIE_NAME, sessionId, {
...COOKIE_OPTIONS,
expires: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // 7 days
});
return c.json({ message: "User registered successfully", user: { id: user.id, username: user.username } }, 201);
} catch (error) {
return c.json({ message: error instanceof Error ? error.message : "Registration failed" }, 400);
}
})
.post("/login", loginDto, arktypeValidator("json", loginBodySchema), async (c) => {
.post("/login", loginDto, validator("json", loginBodySchema), async (c) => {
const body = c.req.valid("json");
try {
@@ -76,4 +84,8 @@ export const authController = new Hono()
return c.json({
user: session.user,
});
})
.get("/status", getStatusDto, async (c) => {
const hasUsers = await authService.hasUsers();
return c.json({ hasUsers });
});