Eric Whale

Add jwt token to signin, signup

1 -const jwt = require("jsonwebtoken");
2 const bcrypt = require("bcryptjs"); 1 const bcrypt = require("bcryptjs");
3 // handles "exception" inside of async express routes 2 // handles "exception" inside of async express routes
4 const asyncHandler = require("express-async-handler"); 3 const asyncHandler = require("express-async-handler");
5 const User = require("../models/userModel"); 4 const User = require("../models/userModel");
5 +const jwtGenerator = require("../config/jwt");
6 6
7 // @desc Signup new user 7 // @desc Signup new user
8 // @route POST /api/users 8 // @route POST /api/users
...@@ -39,7 +39,7 @@ const signupUser = asyncHandler(async (req, res) => { ...@@ -39,7 +39,7 @@ const signupUser = asyncHandler(async (req, res) => {
39 _id: user.id, 39 _id: user.id,
40 username: user.username, 40 username: user.username,
41 email: user.email, 41 email: user.email,
42 - // TODO: Add token! 42 + token: jwtGenerator(user._id),
43 }); 43 });
44 } else { 44 } else {
45 res.status(400); 45 res.status(400);
...@@ -61,7 +61,7 @@ const loginUser = asyncHandler(async (req, res) => { ...@@ -61,7 +61,7 @@ const loginUser = asyncHandler(async (req, res) => {
61 _id: userInDB.id, 61 _id: userInDB.id,
62 username: userInDB.username, 62 username: userInDB.username,
63 email: userInDB.email, 63 email: userInDB.email,
64 - // TODO: Add Token! 64 + token: jwtGenerator(userInDB._id),
65 }); 65 });
66 } else { 66 } else {
67 res.status(400); 67 res.status(400);
...@@ -72,7 +72,10 @@ const loginUser = asyncHandler(async (req, res) => { ...@@ -72,7 +72,10 @@ const loginUser = asyncHandler(async (req, res) => {
72 // @desc Get user(only self) 72 // @desc Get user(only self)
73 // @route GET /api/users/self 73 // @route GET /api/users/self
74 // @access Private 74 // @access Private
75 -const getSelf = asyncHandler(async (req, res) => {}); 75 +const getSelf = asyncHandler(async (req, res) => {
76 + // Not figured out
77 + res.status(200).json(req.user);
78 +});
76 79
77 module.exports = { 80 module.exports = {
78 signupUser, 81 signupUser,
......
1 +const jwt = require("jsonwebtoken");
2 +
3 +const jwtGenerator = (id) => {
4 + // https://github.com/auth0/node-jsonwebtoken
5 + const token = jwt.sign({ id }, JWT_SECRET, { expiresIn: "2 days" });
6 + return token;
7 +};
8 +
9 +module.exports = { jwtGenerator };