Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2019
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. const config = require('config');
  2. const jwt = require('jsonwebtoken');
  3. const Joi = require('joi');
  4. const mongoose = require('mongoose');
  5.  
  6. //simple schema
  7. const UserSchema = new mongoose.Schema({
  8. name: {
  9. type: String,
  10. required: true,
  11. minlength: 3,
  12. maxlength: 50
  13. },
  14. email: {
  15. type: String,
  16. required: true,
  17. minlength: 5,
  18. maxlength: 255,
  19. unique: true
  20. },
  21. password: {
  22. type: String,
  23. required: true,
  24. minlength: 3,
  25. maxlength: 255
  26. },
  27. //give different access rights if admin or not
  28. isAdmin: Boolean
  29. });
  30.  
  31.  
  32. //custom method to generate authToken
  33. UserSchema.methods.generateAuthToken = function() {
  34. const token = jwt.sign({ _id: this._id, isAdmin: this.isAdmin }, config.get('myprivatekey')); //get the private key from the config file -> environment variable
  35. return token;
  36. }
  37.  
  38. const User = mongoose.model('User', UserSchema);
  39.  
  40. //function to validate user
  41. function validateUser(user) {
  42. const schema = {
  43. name: Joi.string().min(3).max(50).required(),
  44. email: Joi.string().min(5).max(255).required().email(),
  45. password: Joi.string().min(3).max(255).required()
  46. };
  47.  
  48. return Joi.validate(user, schema);
  49. }
  50.  
  51. exports.User = User;
  52. exports.validate = validateUser;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement