From b49562fc960520bd92bd765ca337bac694cc6478 Mon Sep 17 00:00:00 2001 From: ayush7801 Date: Mon, 6 May 2024 03:24:48 +0530 Subject: [PATCH] craeted token and sending cookie --- backend/src/app.ts | 3 +- backend/src/controller/userController.ts | 51 +++++++++++++++++++++++- backend/src/utils/constants.ts | 16 ++++++++ backend/src/utils/token-manager.ts | 5 +++ 4 files changed, 72 insertions(+), 3 deletions(-) create mode 100644 backend/src/utils/constants.ts create mode 100644 backend/src/utils/token-manager.ts diff --git a/backend/src/app.ts b/backend/src/app.ts index 0b89df8..7115521 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -2,6 +2,7 @@ import express from 'express'; import {config} from 'dotenv'; import morgan from 'morgan'; import appRouter from './routes/index.js'; +import cookieParser from 'cookie-parser'; // Load environment variables config(); @@ -10,7 +11,7 @@ const app = express(); // Middlewares app.use(express.json()); - +app.use(cookieParser(process.env.COOKIE_SECRET)); app.use(morgan('dev')); app.use('/api/v1', appRouter); diff --git a/backend/src/controller/userController.ts b/backend/src/controller/userController.ts index f81db9d..6ea3f8e 100644 --- a/backend/src/controller/userController.ts +++ b/backend/src/controller/userController.ts @@ -1,6 +1,8 @@ import { Request, Response, NextFunction } from "express"; import { compare, hash } from "bcrypt"; import User from "../models/userModels.js"; // Import the User model +import { createToken } from "../utils/token-manager.js"; +import { Constants } from "../utils/constants.js"; const getAllUsers = async (req: Request, res: Response, next: NextFunction) => { try { @@ -34,6 +36,28 @@ const userSignup = async (req: Request, res: Response, next: NextFunction) => { const hashedPassword = await hash(password, 10); const newUser = new User({ name, email, password: hashedPassword }); await newUser.save(); + + // clear previous cookies and send new cookie with jwt token + res.clearCookie(Constants.AUTH_COOKIE_NAME, { + path: '/', + domain: 'localhost', + signed: true, + httpOnly: true + }); + // this payload will be encypted in jwt token + const payload = { + id: newUser._id, + email: newUser.email + } + const token = createToken(payload, '7d'); + res.cookie(Constants.AUTH_COOKIE_NAME, token, { + path: '/', + domain: 'localhost', + signed: true, + expires: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), + httpOnly: true + }); + res.status(201).json({ status: 'success', message: 'User created successfully', @@ -62,11 +86,34 @@ const userLogin = async (req: Request, res: Response, next: NextFunction) => { status: 'fail', message: 'Invalid password!!!' }); - }else{ + } else { + const currentUser = user[0]; + + // clear previous cookies and send new cookie with jwt token + res.clearCookie(Constants.AUTH_COOKIE_NAME, { + path: '/', + domain: 'localhost', + signed: true, + httpOnly: true + }); + const payload = { + id: currentUser._id, + email: currentUser.email + } + const token = createToken(payload, '7d'); + res.cookie(Constants.AUTH_COOKIE_NAME, token, { + path: '/', + domain: 'localhost', + signed: true, + expires: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), + httpOnly: true + }); + + // set final response res.status(200).json({ status: 'success', message: 'User logged in successfully', - userId: user[0]._id.toString() + userId: currentUser._id.toString() }); } } diff --git a/backend/src/utils/constants.ts b/backend/src/utils/constants.ts new file mode 100644 index 0000000..da37574 --- /dev/null +++ b/backend/src/utils/constants.ts @@ -0,0 +1,16 @@ +export class Constants { + public static readonly AUTH_COOKIE_NAME: string = 'auth-cookie'; + + private static instance: Constants; + + private constructor() {} + + public static getInstance(): Constants { + if (!Constants.instance) { + Constants.instance = new Constants(); + } + return Constants.instance; + } + } + + export const constants = Constants.getInstance(); \ No newline at end of file diff --git a/backend/src/utils/token-manager.ts b/backend/src/utils/token-manager.ts new file mode 100644 index 0000000..b13cac5 --- /dev/null +++ b/backend/src/utils/token-manager.ts @@ -0,0 +1,5 @@ +import jwt from 'jsonwebtoken'; + +export const createToken = (payload: Object, expiresIn: string) => { + return jwt.sign(payload, process.env.JWT_SECRET as string, { expiresIn }); +} \ No newline at end of file