I am trying to get the name and other info from the jwt and I can so far only get the Id of the user.
This is the routes folder for authentication
const config = require("config");
const jwt = require("jsonwebtoken");
const { User } = require("../models/user");
const mongoose = require("mongoose");
const express = require("express");
const Joi = require("joi");
const _ = require("lodash");
const bcrypt = require("bcrypt");
const router = express.Router();
router.post("/", async (req, res) => {
const { error } = validate(req.body);
if (error) return res.status(400).send(error.details[0].message);
let user = await User.findOne({ email: req.body.email });
if (!user) return res.status(400).send("Invalide email or password.");
//compare the passowrd in the body and the password entered when registeration
const validePassword = await bcrypt.compare(req.body.password, user.password);
if (!validePassword)
return res.status(400).send("Invalide email or password.");
const token = user.generateAuthToken();
res.send(token);
});
function validate(req) {
const schema = {
email: Joi.string()
.required()
.min(5)
.max(250)
.email(),
password: Joi.string()
.required()
.min(7)
.max(1024)
};
return Joi.validate(req, schema);
}
module.exports = router;
this is the middleware folder
const jwt = require("jsonwebtoken");
const config = require("config");
module.exports = function(req, res, next) {
const token = req.header("x-auth-token");
if (!token) return res.status(401).send("Access denied. No token provided.");
try {
const decoded = jwt.verify(token, config.get("jwtPrivateKey"));
req.user = decoded;
next();
} catch (ex) {
res.status(400).send("Invalid token.");
}
};
This is the function for getting the current user when they are logged in...
export function getCurrentUser() {
try {
const jwt = localStorage.getItem(tokenKey);
return jwtDecode(jwt);
} catch (ex) {
return null;
}
}
This is all I have in my profile component file where the ComponentDidMount is located...
import React, { Component } from "react";
import { Link } from "react-router-dom";
import NavBar from "./navBar";
import "../profile.css";
import { getCurrentUser } from "../services/authService";
class Profile extends Component {
state = {};
async componentDidMount() {
const currentUser = await getCurrentUser();
console.log(currentUser)
}
When I log the the currentUser this is what I get...
{_id: "5d96a81f9a2f1a8bd485f76c", iat: 1570751361}
iat: 1570751361
_id: "5d96a81f9a2f1a8bd485f76c"
PLEASE HELP
if you need username in payload,you need to add username when you sign the token.If you can't sign with username for some reason,write another service to return username from userId or whatever field exist in your jwt.
userSchema.methods.generateAuthToken = function() {
const token = jwt.sign( { _id: this._id,
isAdmin: this.isAdmin,
_username:this.username },
config.get("jwtPrivateKey") );
return token;
};
i have added new _username:this.username
key value pair inside the jwt.sign function, _username
is the key and this.username
should be your actual username which is in the database.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With