Skip to content

Commit

Permalink
craeted token and sending cookie
Browse files Browse the repository at this point in the history
  • Loading branch information
ayush7801 committed May 5, 2024
1 parent dff5e52 commit b49562f
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 3 deletions.
3 changes: 2 additions & 1 deletion backend/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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);
Expand Down
51 changes: 49 additions & 2 deletions backend/src/controller/userController.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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',
Expand Down Expand Up @@ -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()
});
}
}
Expand Down
16 changes: 16 additions & 0 deletions backend/src/utils/constants.ts
Original file line number Diff line number Diff line change
@@ -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();
5 changes: 5 additions & 0 deletions backend/src/utils/token-manager.ts
Original file line number Diff line number Diff line change
@@ -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 });
}

0 comments on commit b49562f

Please sign in to comment.