SHARE
TWEET

Untitled

a guest Oct 3rd, 2017 60 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const mongoose = require('mongoose')
  2. const bcryptjs = require('bcryptjs')
  3. const jwt = require('jsonwebtoken')
  4. const config = require('../config/config')
  5. // user schema
  6. const userSchema = new mongoose.Schema({
  7.   username: {
  8.     type: String,
  9.     required: true
  10.   },
  11.   email: {
  12.     type: String,
  13.     required: String
  14.   },
  15.   password: {
  16.     type: String,
  17.     required: true
  18.   },
  19.   createdAt: {
  20.     type: Date,
  21.     default: Date.now
  22.   }
  23. })
  24. // user methods
  25. userSchema.statics.createUser = async (email, username, password) => {
  26.   // make new instance of user
  27.   const user = await new User({email, username, password})
  28.   // hash user password then return the user
  29.   user.password = await bcryptjs.hash(user.password, 10)
  30.   return user.save()
  31. }
  32. userSchema.statics.auth = async (email, password) => {
  33.   // check if user exits
  34.   const user = await User.findOne({email})
  35.   if (!user) {
  36.     throw new Error('user not found')
  37.   }
  38.   // if user, verify the user password with the password provided
  39.   const verify = await bcryptjs.compare(password, user.password)
  40.   if (!verify) {
  41.     throw new Error('password not match')
  42.   }
  43.   // assign the user a token
  44.   const token = jwt.sign({
  45.     user
  46.   }, config.SECRET, {
  47.     expiresIn: '2d'
  48.   })
  49.   return token
  50. }
  51. // making a user colloection from schema
  52. const User = mongoose.model('User', userSchema)
  53.  
  54. /// export user model
  55. module.exports = User
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top