AllenYuan

user auth

May 6th, 2020
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var mongoose = require('mongoose');
  2. var uniqueValidator = require('mongoose-unique-validator');
  3. var crypto = require('crypto');
  4. // JWT for user
  5. var jwt = require('jsonwebtoken');
  6. // secret to sign the JWT
  7. var secret = require('../config').secret;
  8.  
  9. // schema representing user data
  10. var UserSchema = new mongoose.Schema(
  11.   {
  12.     username: {
  13.       type: String,
  14.       lowercase: true,
  15.       unique: true,
  16.       required: [true, "can't be blank"],
  17.       match: [/^[a-zA-Z0-9]+$/, 'is invalid'],
  18.       index: true,
  19.     },
  20.     email: {
  21.       type: String,
  22.       lowercase: true,
  23.       unique: true,
  24.       required: [true, "can't be blank"],
  25.       match: [/\S+@\S+\.\S+/, 'is invalid'],
  26.       index: true,
  27.     },
  28.     bio: String,
  29.     image: String,
  30.     hash: String,
  31.     salt: String,
  32.   },
  33.   {timestamps: true}
  34. );
  35.  
  36. UserSchema.plugin(uniqueValidator, {message: 'is already taken.'});
  37.  
  38. // record a salt and hash for the password
  39. UserSchema.methods.setPassword = function (password) {
  40.   this.salt = crypto.randomBytes(16).toString('hex');
  41.   this.hash = crypto
  42.     .pbkdf2Sync(password, this.salt, 10000, 512, 'sha512')
  43.     .toString('hex');
  44. };
  45.  
  46. // hash the input password with respect to the salt and see
  47. // if it matches the set hash
  48. UserSchema.methods.validPassword = function (password) {
  49.   var hash = crypto
  50.     .pbkdf2Sync(password, this.salt, 10000, 512, 'sha512')
  51.     .toString('hex');
  52.   return this.hash === hash;
  53. };
  54.  
  55. // generate a JWT
  56. UserSchema.methods.generateJWT = function() {
  57.   var today = new Date();
  58.   var exp = new Date(today);
  59.   exp.setDate(today.getDate() + 60);
  60.  
  61.   return jwt.sign({
  62.     id: this._id,
  63.     username: this.username,
  64.     exp: parseInt(exp.getTime() / 1000),
  65.   }, secret);
  66. };
  67.  
  68. // send user object to front end
  69. UserSchema.methods.toAuthJSON = function () {
  70.   return {
  71.     username: this.username,
  72.     email: this.email,
  73.     token: this.generateJWT(),
  74.     bio: this.bio,
  75.     image: this,image
  76.   };
  77. };
  78.  
  79. // register the schema with mongoose as 'User'
  80. mongoose.model('User', UserSchema);
Add Comment
Please, Sign In to add comment