nodejs jwt
var jwt = require("jsonwebtoken");
const config = require("config"); // store jwt token seret in it.....
const { check, validationResult } = require("express-validator"); //validater fields
module.exports = (req, res, next) => {
//Get Token from header
const token = req.header("x-auth-token");
//Check if not token
if (!token) {
return res.status(401).json({ msg: "No token ,authorized" });
}
//Verify Token
try {
const decoded = jwt.verify(token, config.get("jwtToken"));
req.user = decoded.user;
console.log(req.user);
next();
} catch (error) {
res.status(401).json({ msg: "Token is not valid" });
}
};
//Controller------
module.exports.Login = async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { Email, Phone_No, Password } = req.body;
try {
//See if user exists
let user = await User.findOne({Emai});
if (!user) {
res.status(400).json({ msg: "Invalid Credentials !" });
}
//Match password
const isMatch = await bcrypt.compare(Password, user.Password);
if (!isMatch) {
res.status(400).json({ msg: "Invalid Password !" });
}
//Jwt Token
const payload = {
user: {
id: user.id,
},
};
jwt.sign(
payload,
config.get("jwtToken"), { expiresIn: 360000 },
(err, token) => {
if (err) throw err;
res.json({ msg: "Login success", token });
}
);
} catch (err) {
console.error(err.message);
res.status(500).send("server error");
}
};
//reactjs side
import axios from "axios";
import JwtDecode from "jwt-decode";
const setAuthToken = () => {
const token = window.localStorage.getItem("token");
console.log("Token get", token);
if (token) {
// Apply authorization token to every request if logged in
axios.defaults.headers.common["x-auth-token"] = token;
} else {
// Delete auth header
delete axios.defaults.headers.common["x-auth-token"];
}
};
export default setAuthToken;
export function getDetails (token){
try{
return JwtDecode(token);
}catch(e){
console.error(e);
}
}