| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- const validator = require('validator')
- const mongoose = require('mongoose')
- const bcrypt = require('bcryptjs')
- const jwt = require('jsonwebtoken')
- const User = require('../models/user')
-
- const tokenSchema = new mongoose.Schema({
- token: {
- type: String,
- required: true
- },
- userId: {
- type: String,
- required: true
- }
- })
-
- tokenSchema.statics.findByCredentials = async (email, password) => {
- const user = await User.findOne({email})
- if(!user) {
- return
- }
- const checkMatch = await bcrypt.compare(password, user.password)
- console.log(password)
- console.log(user.password)
- if(checkMatch) {
- return user
- }
- return null
- }
-
- tokenSchema.statics.generateAuthToken = async function(userArg) {
- const user = userArg
- const token = jwt.sign({ _id: user._id.toString() }, 'ovoJeSecret', { expiresIn: 60 * 20 })
-
- user.tokens = user.tokens.concat({ token })
- await user.save()
-
- return token
- }
-
- tokenSchema.statics.refreshAuthToken = async function(token, refreshOptions) {
- const payload = jwt.verify(token, 'ovoJeSecret', refreshOptions.verify)
- delete payload.iat
- delete payload.exp
- delete payload.nbf
- delete payload.jti
- const jwtSignOptions = Object.assign({ }, this.options, { jwtid: refreshOptions.jwtid })
-
- return jwt.sign(payload, 'ovoJeSecret', jwtSignOptions)
- }
-
- tokenSchema.statics.destroyToken = async function(token) {
- const findUser = await User.findOne({ 'tokens.token': token })
- findUser.tokens = findUser.tokens.filter((currToken) => {
- return currToken.token !== token
- })
- await findUser.save()
- console.log('uspesno')
- return jwt.sign(token, 'a', { expiresIn: 1 })
- }
-
- const Token = mongoose.model('Token', tokenSchema)
-
- module.exports = Token
|