Skip to content

Commit fd5f1a3

Browse files
author
sourabh
committed
Add - Jsonwebtoken
1 parent 202be01 commit fd5f1a3

File tree

3 files changed

+28
-1
lines changed

3 files changed

+28
-1
lines changed

.env

+3-1
Original file line numberDiff line numberDiff line change
@@ -1 +1,3 @@
1-
PORT = 4000
1+
PORT = 4000
2+
JWT_SECRET = thisismyjwtpersonalsecret
3+
JWT_EXPIRY = 7d

map_project.js

+18
Original file line numberDiff line numberDiff line change
@@ -72,4 +72,22 @@ REF: ✈️🔗https://mongoosejs.com/docs/api/document.html#Document.prototype.
7272
IN this we'r discussing about methods for VALIDATING the password that were pass by him;
7373
-It just return true & false value weather you login or not !!
7474
75+
-----------------NEW--------------------
76+
@SECTION: USER MODEL & SIGNUP
77+
@TITLE: CREATING JWT TOKEN
78+
@LOCATION: 🗃️models/user.js
79+
@OVERVIEW:
80+
-🎯first Need to go in .env file
81+
-🎯Need to mention JWT_SECRET & JWT_EXPIRY
82+
-🎯NEED to require 'jsonwebtoken' with Id which easy querry to DB
83+
-🎯then define methode "getJwtToken" with optionaly Asynchronously but don't use
84+
-🎯create function into it
85+
-🎯generate token via 'sign'
86+
-🎯pass id REMEMBER {id:this._id} first id(we'created) & : + this._id(generated via mongoose & we'r accessing);
87+
-🎯By the term it mean: whenever save data in mongodb + automatically generate (._id(field- This is not JSON it's BSON Field)) + Access via only only _id underscore ID O.w NOT
88+
-🎯OPTIONAlY YOU Can PASS LIKE THAT ALSO : email:this.email
89+
---------
90+
-🎯Then provide secrete Come from .env
91+
-🎯Then pass expiry time
92+
7593
*/

models/user.js

+7
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
const mongoose = require("mongoose");
22
const validator = require("validator");
33
const bcrypt = require("bcryptjs");
4+
const jwt = require("jsonwebtoken");
45

56
const userSchema = new mongoose.Schema({
67
name: {
@@ -55,6 +56,12 @@ userSchema.methods.isValidatedPassword = async function (userSendPassword) {
5556
return await bcrypt.compare(userSendPassword, this.password);
5657
};
5758

59+
//CREATE AND RETURN JWT TOKEN
60+
userSchema.methods.getJwtToken = function () {
61+
jwt.sign({ id: this._id }, process.env.JWT_SECRET, {
62+
expiresIn: process.env.JWT_EXPIRY,
63+
});
64+
};
5865

5966

6067
module.exports = mongoose.model("User", userSchema);

0 commit comments

Comments
 (0)