Files
access-manage/src/modules/auth/auth.controller.ts
T
2026-06-02 12:23:00 +08:00

64 lines
1.8 KiB
TypeScript

import type { FastifyInstance } from "fastify";
import { env } from "../../config/env";
import { ok } from "../../shared/response";
import { authGuard } from "./auth.guard";
import { loginBodySchema, updateOwnPasswordBodySchema } from "./auth.schema";
import { authService } from "./auth.service";
export async function authRoutes(app: FastifyInstance): Promise<void> {
app.post("/auth/login", async (request) => {
const body = loginBodySchema.parse(request.body);
const { user, payload } = await authService.loginManagement(body);
const token = app.jwt.sign(payload);
return ok({
token,
tokenType: "Bearer",
expiresIn: env.JWT_EXPIRES_IN,
user,
});
});
app.post("/auth/admin/login", async (request) => {
const body = loginBodySchema.parse(request.body);
const { user, payload } = await authService.loginManagement(body);
const token = app.jwt.sign(payload);
return ok({
token,
tokenType: "Bearer",
expiresIn: env.JWT_EXPIRES_IN,
user,
});
});
app.post("/auth/employee/login", async (request) => {
const body = loginBodySchema.parse(request.body);
const { user, payload } = await authService.loginEmployee(body);
const token = app.jwt.sign(payload);
return ok({
token,
tokenType: "Bearer",
expiresIn: env.JWT_EXPIRES_IN,
user,
});
});
app.get("/auth/me", { preHandler: authGuard }, async (request) => {
const user = await authService.getCurrentUser(request.user);
return ok(user);
});
app.patch("/auth/me/password", { preHandler: authGuard }, async (request) => {
const body = updateOwnPasswordBodySchema.parse(request.body);
const user = await authService.updateOwnPassword(request.user, body, {
ip: request.ip,
userAgent: request.headers["user-agent"] ?? null,
});
return ok(user);
});
}