From d4dac9c67605528d3672555feb81393d0e113bcc Mon Sep 17 00:00:00 2001 From: JayWll Date: Mon, 13 Apr 2020 16:26:04 -0600 Subject: [PATCH] Video 107: Generating Authentication Tokens --- task-manager/src/models/user.js | 19 ++++++++++++++++++- task-manager/src/routers/user.js | 6 ++++-- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/task-manager/src/models/user.js b/task-manager/src/models/user.js index 588dadb..c66a6ce 100644 --- a/task-manager/src/models/user.js +++ b/task-manager/src/models/user.js @@ -1,6 +1,7 @@ const mongoose = require('mongoose') const validator = require('validator') const bcrypt = require('bcryptjs') +const jwt = require('jsonwebtoken') const userSchema = new mongoose.Schema({ name: { @@ -39,9 +40,25 @@ const userSchema = new mongoose.Schema({ throw new Error('Age must be a positive number') } } - } + }, + tokens: [{ + token: { + type: String, + required: true + } + }] }) +userSchema.methods.generateAuthToken = async function () { + const user = this + const token = jwt.sign({ _id: user._id.toString() }, 'thisismynewcourse') + + user.tokens = user.tokens.concat({ token }) + await user.save() + + return token +} + userSchema.statics.findByCredentials = async (email, password) => { const user = await User.findOne({ email }) diff --git a/task-manager/src/routers/user.js b/task-manager/src/routers/user.js index f3c2559..25c242b 100644 --- a/task-manager/src/routers/user.js +++ b/task-manager/src/routers/user.js @@ -7,7 +7,8 @@ router.post('/users', async (req, res) => { try { await user.save() - res.status(201).send(user) + const token = await user.generateAuthToken() + res.status(201).send({ user, token }) } catch (e) { res.status(400).send(e) } @@ -16,7 +17,8 @@ router.post('/users', async (req, res) => { router.post('/users/login', async (req, res) => { try { const user = await User.findByCredentials(req.body.email, req.body.password) - res.send(user) + const token = await user.generateAuthToken() + res.send({ user, token }) } catch (e) { res.status(400).send() }