You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

token.js 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. const validator = require('validator')
  2. const mongoose = require('mongoose')
  3. const bcrypt = require('bcryptjs')
  4. const jwt = require('jsonwebtoken')
  5. const User = require('../models/user')
  6. const tokenSchema = new mongoose.Schema({
  7. token: {
  8. type: String,
  9. required: true
  10. },
  11. userId: {
  12. type: String,
  13. required: true
  14. }
  15. })
  16. tokenSchema.statics.findByCredentials = async (email, password) => {
  17. const user = await User.findOne({email})
  18. if(!user) {
  19. return
  20. }
  21. const checkMatch = await bcrypt.compare(password, user.password)
  22. console.log(password)
  23. console.log(user.password)
  24. if(checkMatch) {
  25. return user
  26. }
  27. return null
  28. }
  29. tokenSchema.statics.generateAuthToken = async function(userArg) {
  30. const user = userArg
  31. const token = jwt.sign({ _id: user._id.toString() }, 'ovoJeSecret', { expiresIn: 60 * 20 })
  32. user.tokens = user.tokens.concat({ token })
  33. await user.save()
  34. return token
  35. }
  36. tokenSchema.statics.refreshAuthToken = async function(token, refreshOptions) {
  37. const payload = jwt.verify(token, 'ovoJeSecret', refreshOptions.verify)
  38. delete payload.iat
  39. delete payload.exp
  40. delete payload.nbf
  41. delete payload.jti
  42. const jwtSignOptions = Object.assign({ }, this.options, { jwtid: refreshOptions.jwtid })
  43. return jwt.sign(payload, 'ovoJeSecret', jwtSignOptions)
  44. }
  45. tokenSchema.statics.destroyToken = async function(token) {
  46. const findUser = await User.findOne({ 'tokens.token': token })
  47. findUser.tokens = findUser.tokens.filter((currToken) => {
  48. return currToken.token !== token
  49. })
  50. await findUser.save()
  51. console.log('uspesno')
  52. return jwt.sign(token, 'a', { expiresIn: 1 })
  53. }
  54. const Token = mongoose.model('Token', tokenSchema)
  55. module.exports = Token