Skip to content

Commit

Permalink
Cookie implementation in signup and signin
Browse files Browse the repository at this point in the history
  • Loading branch information
akshit-bhutani-19 committed May 24, 2024
1 parent 473aa1b commit ee7c218
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
1 change: 1 addition & 0 deletions services/Auth/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"license": "MIT",
"dependencies": {
"bcryptjs": "^2.4.3",
"cookie": "^0.6.0",
"cookie-parser": "^1.4.6",
"dotenv": "^16.4.5",
"express": "^4.19.2",
Expand Down
36 changes: 34 additions & 2 deletions services/Auth/src/controllers/auth.controller.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const jwt = require("jsonwebtoken");
const bcrypt = require("bcryptjs");
const User = require("../models/user.model");
const { errorHadnler } = require("../utils/error");
const cookie = require('cookie'); // Import the 'cookie' library

async function signup(req, res) {
try {
Expand Down Expand Up @@ -36,8 +36,24 @@ async function signup(req, res) {

const token = user.generateAuthToken();

// getting user data format {name:"example", email:"dogeshdog@cheems.com"}
// Set Cookie in Header
res.setHeader(
'Set-Cookie',
cookie.serialize(
'token',
token,
{
httpOnly : true,
maxAge: 60 * 60 * 24,
sameSite: 'None', // Restrict when the cookie is sent with cross-origin requests
secure: false, // Send the cookie only over HTTPS in production
path: '/',
}
)
);

// getting user data format {name:"example", email:"dogeshdog@cheems.com"}

const userResponse = user.getUserData();

return res.status(200).json({ ...userResponse, token });
Expand Down Expand Up @@ -79,6 +95,22 @@ async function signin(req, res, next) {

const token = user.generateAuthToken();

// Set Cookie in Header
res.setHeader(
'Set-Cookie',
cookie.serialize(
'token',
token,
{
httpOnly : true,
maxAge: 60 * 60 * 24,
sameSite: 'None', // Restrict when the cookie is sent with cross-origin requests
secure: false, // Send the cookie only over HTTPS in production
path: '/',
}
)
);

const userResposne = user.getUserData();

return res.status(200).json({ token, userResposne });
Expand Down

0 comments on commit ee7c218

Please sign in to comment.