In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Editor to share with you how to achieve password hashing in express+mongodb+middleware in nodejs, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
Hash1 the password before saving it
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifteen
UserSchema.pre ('save', function (next) {
Var user = this
If (user.isModified ('password')) {
Bcrypt.genSalt (10, (err, salt) = > {
Bcrypt.hash (user.password, salt, (err, hash) = > {
User.password = hash
Next ()
});
});
} else {
Next ()
}
});
Complete Code 1
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifteen
sixteen
seventeen
eighteen
nineteen
twenty
twenty-one
twenty-two
twenty-three
twenty-four
twenty-five
twenty-six
twenty-seven
twenty-eight
twenty-nine
thirty
thirty-one
thirty-two
thirty-three
thirty-four
thirty-five
thirty-six
thirty-seven
thirty-eight
thirty-nine
forty
forty-one
forty-two
forty-three
forty-four
forty-five
forty-six
forty-seven
forty-eight
forty-nine
fifty
fifty-one
fifty-two
fifty-three
fifty-four
fifty-five
fifty-six
fifty-seven
fifty-eight
fifty-nine
sixty
sixty-one
sixty-two
sixty-three
sixty-four
sixty-five
sixty-six
sixty-seven
sixty-eight
sixty-nine
seventy
seventy-one
seventy-two
seventy-three
seventy-four
seventy-five
seventy-six
seventy-seven
seventy-eight
seventy-nine
eighty
eighty-one
eighty-two
eighty-three
eighty-four
eighty-five
eighty-six
eighty-seven
eighty-eight
eighty-nine
ninety
ninety-one
ninety-two
ninety-three
ninety-four
ninety-five
ninety-six
ninety-seven
ninety-eight
ninety-nine
one hundred
one hundred and one
one hundred and two
one hundred and three
one hundred and four
one hundred and five
one hundred and six
one hundred and seven
one hundred and eight
one hundred and nine
one hundred and ten
one hundred and eleven
one hundred and twelve
one hundred and thirteen
one hundred and fourteen
one hundred and fifteen
one hundred and sixteen
one hundred and seventeen
one hundred and eighteen
one hundred and nineteen
one hundred and twenty
one hundred and twenty one
one hundred and twenty two
one hundred and twenty three
one hundred and twenty four
one hundred and twenty five
one hundred and twenty six
one hundred and twenty seven
one hundred and twenty eight
one hundred and twenty nine
one hundred and thirty
one hundred and thirty one
one hundred and thirty two
one hundred and thirty three
one hundred and thirty four
one hundred and thirty five
one hundred and thirty six
one hundred and thirty seven
one hundred and thirty eight
one hundred and thirty nine
one hundred and forty
one hundred and forty one
one hundred and forty two
one hundred and forty three
one hundred and forty four
one hundred and forty five
one hundred and forty six
one hundred and forty seven
one hundred and forty eight
one hundred and forty nine
one hundred and fifty
one hundred and fifty one
one hundred and fifty two
one hundred and fifty three
one hundred and fifty four
one hundred and fifty five
one hundred and fifty six
one hundred and fifty seven
one hundred and fifty eight
one hundred and fifty nine
one hundred and sixty
one hundred and sixty one
one hundred and sixty two
one hundred and sixty three
one hundred and sixty four
one hundred and sixty five
one hundred and sixty six
one hundred and sixty seven
one hundred and sixty eight
one hundred and sixty nine
one hundred and seventy
one hundred and seventy one
one hundred and seventy two
one hundred and seventy three
one hundred and seventy four
one hundred and seventy five
one hundred and seventy six
one hundred and seventy seven
one hundred and seventy eight
one hundred and seventy nine
one hundred and eighty
one hundred and eighty one
one hundred and eighty two
one hundred and eighty three
one hundred and eighty four
one hundred and eighty five
one hundred and eighty six
one hundred and eighty seven
one hundred and eighty eight
one hundred and eighty nine
one hundred and ninety
one hundred and ninety one
one hundred and ninety two
one hundred and ninety three
one hundred and ninety four
one hundred and ninety five
one hundred and ninety six
one hundred and ninety seven
one hundred and ninety eight
one hundred and ninety nine
two hundred
two hundred and one
two hundred and two
two hundred and three
two hundred and four
two hundred and five
two hundred and six
two hundred and seven
two hundred and eight
two hundred and nine
two hundred and ten
two hundred and eleven
two hundred and twelve
two hundred and thirteen
two hundred and fourteen
two hundred and fifteen
two hundred and sixteen
two hundred and seventeen
two hundred and eighteen
two hundred and nineteen
two hundred and twenty
two hundred and twenty one
two hundred and twenty two
two hundred and twenty three
two hundred and twenty four
two hundred and twenty five
two hundred and twenty six
two hundred and twenty seven
two hundred and twenty eight
two hundred and twenty nine
two hundred and thirty
two hundred and thirty one
two hundred and thirty two
two hundred and thirty three
two hundred and thirty four
two hundred and thirty five
two hundred and thirty six
two hundred and thirty seven
two hundred and thirty eight
two hundred and thirty nine
two hundred and forty
two hundred and forty one
two hundred and forty two
two hundred and forty three
two hundred and forty four
two hundred and forty five
two hundred and forty six
two hundred and forty seven
two hundred and forty eight
two hundred and forty nine
two hundred and fifty
two hundred and fifty one
two hundred and fifty two
two hundred and fifty three
two hundred and fifty four
two hundred and fifty five
two hundred and fifty six
two hundred and fifty seven
two hundred and fifty eight
two hundred and fifty nine
two hundred and sixty
two hundred and sixty one
two hundred and sixty two
two hundred and sixty three
two hundred and sixty four
two hundred and sixty five
two hundred and sixty six
two hundred and sixty seven
two hundred and sixty eight
two hundred and sixty nine
two hundred and seventy
two hundred and seventy one
two hundred and seventy two
two hundred and seventy three
two hundred and seventy four
two hundred and seventy five
two hundred and seventy six
two hundred and seventy seven
two hundred and seventy eight
two hundred and seventy nine
two hundred and eighty
two hundred and eighty one
Var mongoose = require ('mongoose')
Var express = require ('express')
Var bodyParser = require ('body-parser')
Const {ObjectID} = require ('mongodb')
Var _ = require ('lodash')
Const validator = require ('validator')
Const jwt = require ('jsonwebtoken')
Const bcrypt = require ('bcryptjs')
/ / app
Var app = express ()
Const port = process.env.PORT | | 3000
/ / express middleware Jonson object and string conversion.
App.use (bodyParser.json ())
/ /
Mongoose.Promise = global.Promise
/ / Connect to mogodb
Mongoose.connect (process.env.MONGODB_URI | | 'mongodb://localhost:27017/TodoApp')
/ / template
Var Todo = mongoose.model ('Todo', {
Text: {
Type:String, / / Type
Required:true, / / must have
Minlength:1, / / minimum length
Trim:true / / remove whitespace
}
Completed: {
Type:Boolean
Default:false / / default
}
CompletedAt: {
Type:Number
Default:null
}
});
Var UserSchema = new mongoose.Schema ({
Email: {
Type: String
Required: true
Trim: true
Minlength: 1
Unique: true
Validate: {
Validator: validator.isEmail
Message:'{VALUE} is not a valid email'
}
}
Password: {
Type: String
Require: true
Minlength: 6
}
Tokens: [{
Access: {
Type: String
Required: true
}
Token: {
Type: String
Required: true
}
}]
});
UserSchema.methods.toJSON = function () {
Var user = this
Var userObject = user.toObject ()
Return _ .pick (userObject, ['_ id', 'email'])
}
UserSchema.methods.generateAuthToken = function () {
Var user = this
Var access = 'auth'
Var token = jwt.sign ({_ id: user._id.toHexString (), access}, 'abc123') .toString ()
User.tokens = user.tokens.concat ([{access,token}])
Return user.save () .then (() = > {
Return token; / / returns token
});
}
UserSchema.statics.findByToken = function (token) {
Var User = this
Var decoded
Try {
Decoded = jwt.verify (token, 'abc123')
} catch (e) {
Return Promise.reject ()
}
Return User.findOne ({
'_ id': decoded._id
'tokens.token': token
'tokens.access': 'auth'
});
}
/ / perform the operation before saving.
UserSchema.pre ('save', function (next) {
Var user = this
/ / Update the password when saving
If (user.isModified ('password')) {
Bcrypt.genSalt (10, (err, salt) = > {
/ / password changed to hash
Bcrypt.hash (user.password, salt, (err, hash) = > {
User.password = hash
Next ()
});
});
} else {
Next ()
}
});
Var User = mongoose.model ('User', UserSchema)
/ / auth middlewire
Var authenticate = (req, res, next) = > {
Var token = req.header ('xMuiauth')
User.findByToken (token) .then ((user) = > {
If (! user) {
Return Promise.reject ()
}
Req.user = user
Req.token = token
Next ()
}) .catch ((e) = > {
Res.status. Send ()
});
}
App.get ('/ users/me', authenticate, (req, res) = > {
Res.send (req.user)
});
/ / express route
App.post ('/ todos', (req,res) = > {
/ / console.log (req.body)
/ / create object document
Var todo = new Todo ({
Text:req.body.text
});
/ / Save
Todo.save () .then ((doc) = > {
Res.send (doc)
}, (e) = > {
Res.status (400) .send (e)
});
})
/ / get all attributes
App.get ('/ todos', (req, res) = > {
Todo.find () .then ((todos) = > {
Res.send ({todos})
}, (e) = > {
Res.status (400) .send (e)
})
});
/ / query id
App.get ('/ todos/:id', (req, res) = > {
Var id = req.params.id
If (! ObjectID.isValid (id)) {
Return res.status. Send ()
}
Todo.findById (id) .then ((todo) = > {
If (! todo) {
Return res.status. Send ()
}
Res.send ({todo})
}) .catch ((e) = > {
Res.status (400). Send ()
});
});
/ / Delete
App.delete ('/ todos/:id', (req, res) = > {
Var id = req.params.id
If (! ObjectID.isValid (id)) {
Return res.status. Send ()
}
Todo.findByIdAndRemove (id) .then ((todo) = > {
If (! todo) {
Return res.status. Send ()
}
Res.send ({todo})
}) .catch ((e) = > {
Res.status (400). Send ()
});
});
/ / Update
App.patch ('/ todos/:id', (req, res) = > {
Var id = req.params.id
Var body = _ .pick (req.body, ['text',' completed'])
If (! ObjectID.isValid (id)) {
Return res.status. Send ()
}
If (_ .isBoolean (body.completed) & & body.completed) {
Body.completedAt = new Date () .getTime ()
} else {
Body.completed = false
Body.completedAt = null
}
Todo.findByIdAndUpdate (id, {$set: body}, {new: true}) .then ((todo) = > {
If (! todo) {
Return res.status. Send ()
}
Res.send ({todo})
}) .catch ((e) = > {
Res.status (400). Send ()
})
});
/ / POST / users
App.post ('/ users', (req, res) = > {
Var body = _ .pick (req.body, ['email',' password'])
Var user = new User (body)
User.save () .then (() = > {
Return user.generateAuthToken (); / / calls the method to generate the auth token and save it.
}) .then ((token) = > {
Res.header ('xMaiauthored, token) .send (user); / / set the response header
}) .catch ((e) = > {
Res.status (400) .send (e)
})
});
/ / Monitoring
App.listen (port, () = > {
Console.log (`Start on port ${port} `)
});
Module.exports = {
App
Todo
}
Test 1
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifteen
sixteen
seventeen
eighteen
1. Open mongoDB >. / mongod-dbpath / Users/jackson/Downloads/mongodb-data
2. Run > node postman.js
3. Open postman and select post input > localhost:3000/users.
Enter the following in Body:
{
"email": "zhuimengshaonian07@gmail.com"
"password": "123abc!"
}
Return:
{
"_ id": "5bfe716591e78c6a4ad8c164"
"email": "zhuimengshaonian07@gmail.com"
}
Header:
X-auth → eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1YmZlNzE2NTkxZTc4YzZhNGFkOGMxNjQiLCJhY2Nlc3MiOiJhdXRoIiwiaWF0IjoxNTQzNDAxODI5fQ.wOKNzkls_w_jA5YVkCo0r9gFZ4-KtD6GarRiCDpAPr8
4. Look at studio 3T and find that the password has changed to the number after hash.
The above is all the contents of the article "how to implement password hashing in express+mongodb+middleware in nodejs". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.