Last active
January 11, 2021 04:21
-
-
Save thevenice/3907fa5d98413c6529cb0fd7f925d0ad to your computer and use it in GitHub Desktop.
user.model.js/ mongodb/ nodejs/ user model example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const mongoose= require('mongoose'); | |
| const crypto = require('crypto'); | |
| const userSchemaObject={ | |
| user_permanent_id:{ | |
| type: String, | |
| required: true | |
| }, | |
| username:{ | |
| type:String, | |
| required: true, | |
| unique: true, | |
| trim: true, | |
| index: true, | |
| lowercase:true, | |
| max:32, | |
| }, | |
| name:{ | |
| type: String, | |
| required: true, | |
| trim: true, | |
| max: 32 | |
| }, | |
| email:{ | |
| type:String, | |
| require: true, | |
| trim: true, | |
| unique: true, | |
| lowercase: true | |
| }, | |
| hashed_password:{ | |
| type: String, | |
| required: true | |
| }, | |
| salt:String, | |
| profile:{ | |
| type: String, | |
| required: true | |
| }, | |
| about:{ | |
| type: String | |
| }, | |
| role:{ | |
| type: Number, | |
| default: 0 | |
| }, | |
| photo:{ | |
| data: Buffer, | |
| contentType: String | |
| }, | |
| resetPasswordLink:{ | |
| data: String, | |
| default: "" | |
| }, | |
| phone_no:{ | |
| type:String | |
| }, | |
| date_created:{ | |
| type: String, | |
| require: true | |
| }, | |
| last_time_username_changed:{ | |
| type: String, | |
| required: true | |
| }, | |
| last_time_email_changed:{ | |
| type: String, | |
| required: true | |
| }, | |
| last_time_password_changed:{ | |
| type: String, | |
| required: true | |
| }, | |
| last_time_phone_no_changed:{ | |
| type: String, | |
| required: true | |
| } | |
| } | |
| const userSchema= new mongoose.Schema(userSchemaObject,{timestamp: true}); | |
| userSchema.virtual('password') | |
| .set(function(password){ | |
| // create temp variable called _password | |
| this._password = password; | |
| // generate salt | |
| this.salt= this.makeSalt() | |
| // encrypt password | |
| this.hashed_password= this.hashPassword(password) | |
| }) | |
| .get(function(){ | |
| return this._password; | |
| }) | |
| userSchema.methods={ | |
| authentication:function(plainTextPassword){ | |
| return this.hashPassword(plainTextPassword)=== this.hashed_password; | |
| }, | |
| hashPassword: function(password){ | |
| if(!password) return ''; | |
| try{ | |
| return crypto | |
| .createHmac('sha1', this.salt) | |
| .update(password) | |
| .digest('hex') | |
| } | |
| catch(err){return ''} | |
| }, | |
| makeSalt: function(){ | |
| return Math.round(new Date().valueOf() * Math.random() + '') | |
| } | |
| } | |
| module.exports = mongoose.model('User', userSchema); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment