Last active
October 22, 2019 05:08
-
-
Save Bilguun132/c63a552c09c67a3cfc8b5143522aefb1 to your computer and use it in GitHub Desktop.
nodejs-auth-Tutorial-usermodel
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 config = require('config'); | |
| const jwt = require('jsonwebtoken'); | |
| const Joi = require('joi'); | |
| const mongoose = require('mongoose'); | |
| //simple schema | |
| const UserSchema = new mongoose.Schema({ | |
| name: { | |
| type: String, | |
| required: true, | |
| minlength: 3, | |
| maxlength: 50 | |
| }, | |
| email: { | |
| type: String, | |
| required: true, | |
| minlength: 5, | |
| maxlength: 255, | |
| unique: true | |
| }, | |
| password: { | |
| type: String, | |
| required: true, | |
| minlength: 3, | |
| maxlength: 255 | |
| }, | |
| //give different access rights if admin or not | |
| isAdmin: Boolean | |
| }); | |
| //custom method to generate authToken | |
| UserSchema.methods.generateAuthToken = function() { | |
| const token = jwt.sign({ _id: this._id, isAdmin: this.isAdmin }, config.get('myprivatekey')); //get the private key from the config file -> environment variable | |
| return token; | |
| } | |
| const User = mongoose.model('User', UserSchema); | |
| //function to validate user | |
| function validateUser(user) { | |
| const schema = { | |
| name: Joi.string().min(3).max(50).required(), | |
| email: Joi.string().min(5).max(255).required().email(), | |
| password: Joi.string().min(3).max(255).required() | |
| }; | |
| return Joi.validate(user, schema); | |
| } | |
| exports.User = User; | |
| exports.validate = validateUser; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment