edit:module:user | add middlewware for unauthenticated only

This commit is contained in:
rafiarrafif
2025-06-22 09:45:06 +07:00
parent fbd5b68b10
commit 48946be6b7
3 changed files with 11 additions and 23 deletions

View File

@ -3,13 +3,12 @@ import { getCookie } from "../../helpers/http/userHeader/cookies/getCookies";
import { returnErrorResponse } from "../../helpers/callback/httpResponse";
export const unautenticatedMiddleware = (ctx: Context) => {
// Check if the user is already logged in by checking the auth token in cookies. If the user is logged in, return an error response
try {
const cookies = getCookie(ctx);
if (cookies.auth_token)
return returnErrorResponse(ctx.set, 403, "User already aunthenticated");
// pass
} catch (error) {
// pass
const cookie = getCookie(ctx);
if (cookie && cookie.auth_token)
return returnErrorResponse(ctx.set, 401, "You are already logged in. ");
} catch (_) {
// Pass
}
};

View File

@ -7,7 +7,6 @@ import { Context } from "elysia";
import { createUserService } from "../services/createUser.service";
import { mainErrorHandler } from "../../../helpers/error/handler";
import { createUserSchema } from "../schemas/createUser.schema";
import { getCookie } from "../../../helpers/http/userHeader/cookies/getCookies";
/**
* @function createUser
@ -31,19 +30,6 @@ import { getCookie } from "../../../helpers/http/userHeader/cookies/getCookies";
export const createUserController = async (
ctx: Context & { body: Prisma.UserCreateInput }
) => {
// Check if the user is already logged in by checking the auth token in cookies. If the user is logged in, return an error response
try {
const cookie = getCookie(ctx);
if (cookie && cookie.auth_token)
return returnErrorResponse(
ctx.set,
401,
"You are already logged in. Please log out first if you want to create a new account."
);
} catch (_) {
// Pass
}
// Validate the user input using a validation schema
const { error } = createUserSchema.validate(ctx.body);
if (error)

View File

@ -2,8 +2,11 @@ import Elysia from "elysia";
import { getAllUserController } from "./controller/getAllUser.controller";
import { createUserController } from "./controller/createUser.controller";
import { editUserController } from "./controller/editUser.controller";
import { unautenticatedMiddleware } from "../../middleware/auth/unauthenticated.middleware";
export const userModule = new Elysia({ prefix: "/users" })
.get("/", getAllUserController)
.post("/", createUserController)
.put("/", editUserController);
.put("/", editUserController)
.group("", (app) =>
app.onBeforeHandle(unautenticatedMiddleware).post("/", createUserController)
);