Skip to content

Commit b8b24bc

Browse files
committed
sending jwt token in cookie
1 parent 33667d9 commit b8b24bc

File tree

2 files changed

+24
-11
lines changed

2 files changed

+24
-11
lines changed

Controllers/userAuthController.js

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ const mongoose = require('mongoose');
22
const User = require('../Modals/userModels');
33
const ErrrorHandler = require('../Utils/errorHandler');
44
const catchAsyncErrors = require('../Middlewares/catchAsyncErrors');
5+
const sendToken = require('../Utils/JwtToken');
56

67
// Register a user => /api/v1/register
78
exports.registerUser = catchAsyncErrors(async (req, res, next) => {
@@ -17,11 +18,7 @@ exports.registerUser = catchAsyncErrors(async (req, res, next) => {
1718
},
1819
});
1920

20-
const token = user.getJwtToken();
21-
res.status(201).json({
22-
success: true,
23-
token,
24-
});
21+
sendToken(user, 200, res);
2522
});
2623

2724
// Login user => /api/v1/login
@@ -47,10 +44,5 @@ exports.loginUser = catchAsyncErrors(async (req, res, next) => {
4744
return next(new ErrrorHandler('Invalid Email or Password', 401));
4845
}
4946

50-
const token = user.getJwtToken();
51-
52-
res.status(200).json({
53-
success: true,
54-
token,
55-
});
47+
sendToken(user, 200, res);
5648
});

Utils/JwtToken.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// create and send token and save in the cookie.
2+
3+
const sendToken = (user, statusCode, res) => {
4+
//create token
5+
const token = user.getJwtToken();
6+
7+
//options for cookie
8+
const options = {
9+
expires: new Date(
10+
Date.now() + process.env.COOKIE_EXPIRES_TIME * 24 * 60 * 60 * 1000
11+
),
12+
httpOnly: true,
13+
};
14+
res.status(statusCode).cookie('token', token, options).json({
15+
success: true,
16+
token,
17+
user,
18+
});
19+
};
20+
21+
module.exports = sendToken;

0 commit comments

Comments
 (0)