diff --git a/src/api/auth/auth.controller.ts b/src/api/auth/auth.controller.ts index eb91598..32d8648 100644 --- a/src/api/auth/auth.controller.ts +++ b/src/api/auth/auth.controller.ts @@ -8,6 +8,7 @@ import { eq } from "drizzle-orm"; import jwt from "jsonwebtoken"; import { checkUserInDB, createUser, storeRefreshToken } from "../../helper/auth/auth.helper"; +import { verifyAuth } from "../../middlewares/auth.middlewares"; // Initialize Clerk with your API key const clerk = createClerkClient({ secretKey: ENV.CLERK_SECRET_KEY }); @@ -64,27 +65,34 @@ export const generateToken = async (context: any) => { // generating accessToken and refreshToken const user = await checkUserInDB(userId); if (user?.found === true) { - const accessSecret = ENV.JWT_ACCESS_TOKEN_SECRET; - const refreshSecret = ENV.JWT_REFRESH_TOKEN_SECRET; // generate access token - const accessToken = jwt.sign({ userId }, accessSecret, { expiresIn: '3h' }); + const accessToken = jwt.sign({ userId }, ENV.JWT_ACCESS_TOKEN_SECRET, { expiresIn: '3h' }); // generate refresh token - const refreshToken = jwt.sign({ userId }, refreshSecret, { expiresIn: '7d' }); + const refreshToken = jwt.sign({ userId }, ENV.JWT_REFRESH_TOKEN_SECRET, { expiresIn: '7d' }); // store refresh token in db const storeRToken = await storeRefreshToken(userId, refreshToken); if (storeRToken.status === 200) { - context.cookie.access_token = { + context.cookie.access_token.set({ value: accessToken, httpOnly: true, - secure: true, - sameSite: 'none', + secure: true, // Set to true in production + sameSite: 'none', // Adjust based on your needs path: "/", - maxAge: 3 * 60 * 60 * 1000, // 3 hours - } + maxAge: 3 * 60 * 60, // 3 hours in seconds + }); + + context.cookie.refresh_token.set({ + value: refreshToken, + httpOnly: true, + secure: true, // Set to true in production + sameSite: 'none', // Adjust based on your needs + path: "/", + maxAge: 7 * 24 * 60 * 60, // 7 days in seconds + }); return { status: 200, message: "Token generated successfully", token: accessToken }; } @@ -103,35 +111,10 @@ export const generateToken = async (context: any) => { export const verifyToken = async (context: any) => { try { // if token is in cookie, verify it - const token_cookie = context.cookie.access_token.value; - if (token_cookie) { - const verify_cookie = jwt.verify(token_cookie, ENV.JWT_REFRESH_TOKEN_SECRET); - if (verify_cookie) { - return { status: 200, message: "Token verified successfully" }; - } - else { - return { status: 401, message: "Unauthorized!!!" }; - } - } - // if token is not in cookie, then check in header and verify it - else { - const token_header = context.headers.authorization.split("Bearer ")[1]; + // const token_cookie = context.cookie.access_token.value; + const verify = await verifyAuth(context.cookie); - if (token_header) { - const verify_header = jwt.decode(token_header); - - if (verify_header?.userId) { - context.params.userId = verify_header.userId; - await generateToken(context); - } - else { - return { status: 401, message: "Unauthorized!!!" }; - } - } - else { - return { status: 401, message: "Unauthorized!!!" }; - } - } + return verify; } catch (error: any) { console.log("Error in verifyToken:", error.message || error.toString()); diff --git a/src/api/index.ts b/src/api/index.ts index 4e41b50..f07a735 100644 --- a/src/api/index.ts +++ b/src/api/index.ts @@ -1,16 +1,12 @@ import Elysia from "elysia"; import { projectRoutes } from "./project/project.route"; import { uploadRoutes } from "./upload/upload.route"; -import { verifyAuth } from "../middlewares/auth.middlewares"; import { authRoute } from "./auth/auth.route"; -import cookie from "@elysiajs/cookie"; export const api = new Elysia({ prefix: "/api", }); -// api.derive(verifyAuth); -api.use(cookie()); api.use(authRoute); api.use(projectRoutes); api.use(uploadRoutes); \ No newline at end of file diff --git a/src/api/project/project.route.ts b/src/api/project/project.route.ts index cab000d..13744b3 100644 --- a/src/api/project/project.route.ts +++ b/src/api/project/project.route.ts @@ -1,5 +1,6 @@ import { Elysia } from "elysia"; import { deleteProject, getAllProjects, getEachProjects, updateProject } from "./project.controller"; +import { verifyAuth } from "../../middlewares/auth.middlewares"; export const projectRoutes = new Elysia({ prefix: "/projects", @@ -7,6 +8,10 @@ export const projectRoutes = new Elysia({ detail: { description: "Routes for managing projects", } +}).derive(({ cookie }) => { verifyAuth(cookie) }); + +projectRoutes.post("/add", (context) => { + console.log("this is from project route/add", context); }) projectRoutes.get("/:id", ({ params }) => getEachProjects(params.id)); diff --git a/src/middlewares/auth.middlewares.ts b/src/middlewares/auth.middlewares.ts index 5bcb526..6b55d04 100644 --- a/src/middlewares/auth.middlewares.ts +++ b/src/middlewares/auth.middlewares.ts @@ -1,9 +1,52 @@ +import { ENV } from "../config/env"; +// @ts-ignore +import jwt from "jsonwebtoken"; +import { users } from "../db/schema"; +import { db } from "../db"; +import { eq } from "drizzle-orm"; -export const verifyAuth = (request: Request) => { - const authHeader = request.headers.get('Authorization'); - if (!authHeader) { - return new Response('Unauthorized', { status: 401 }); +export const verifyAuth = async (cookie: any) => { + try { + const access_cookie = cookie?.access_token?.value; + + const refresh_cookie = cookie?.refresh_token?.value; + + console.log("this is access cookie", access_cookie); + console.log("this is refresh cookie", refresh_cookie); + + if (access_cookie) { + // Verify JWT token + const verify_cookie = jwt.verify(access_cookie, ENV.JWT_ACCESS_TOKEN_SECRET); + // Query the user from the database + const findUser = await db.select().from(users).where(eq(users.id, verify_cookie.userId)); + if (findUser.length > 0) { + return { status: 200, message: "Token verified successfully" }; + } + else { + throw { status: 401, message: "Unauthorized" }; + } + } + + else if (!access_cookie && refresh_cookie) { + // Verify JWT token + const verify_cookie = jwt.verify(refresh_cookie, ENV.JWT_REFRESH_TOKEN_SECRET); + + // Query the user from the database + const findUser = await db.select().from(users).where(eq(users.id, verify_cookie.userId)); + if (findUser.length === 0 || findUser[0].refresh_token !== refresh_cookie) { + throw { status: 401, message: "Unauthorized" }; + } + else { + return { status: 200, message: "Token verified successfully" }; + } + } + + else { + throw { status: 401, message: "No token provided" }; + } + + } catch (error: any) { + console.log("Error in verifyToken:", error.message || error.toString()); + return { status: 500, message: "An error occurred while verifying the token" }; } - const token = authHeader.split(' ')[1]; - // Verify the token here (e.g., using a library like `jsonwebtoken` or `jose`) -} \ No newline at end of file +};