Skip to content

Added middleware compatible with JWT #43

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -113,6 +113,7 @@ dist

# testing
/coverage
*.rest

# production
/build
13 changes: 0 additions & 13 deletions server/config/id_rsa_pub.pem

This file was deleted.

17 changes: 10 additions & 7 deletions server/controllers/auth.controller.js
Original file line number Diff line number Diff line change
@@ -8,9 +8,14 @@ const jwt = require('jsonwebtoken')
const bcrypt = require('bcryptjs')

// reading the content of the private key
const fs = require('fs');
pathToKey = require('path').join(__dirname, '..', './config/id_rsa_priv.pem');
const PRIV_KEY = fs.readFileSync(pathToKey, 'utf8'); //private key is used for signing the token
// const fs = require('fs');
// pathToKey = require('path').join(__dirname, '..', './config/id_rsa_priv.pem');
// const PRIV_KEY = fs.readFileSync(pathToKey, 'utf8'); //private key is used for signing the token
require('dotenv').config()
const PRIV_KEY = process.env.PRIV_KEY;

// token expiration time
const tokenExpirationTime = "1m";

/*
This function is used to authenticate the user when he/she tries to login
@@ -38,11 +43,10 @@ const signin = async (req, res, next) => {
if (user && (await bcrypt.compare(password, user.password))) {
const payload = {
user: user,
iat: Date.now()
}
// Create token
const token = "Bearer " + jwt.sign(
payload, PRIV_KEY, { expiresIn: "1d", algorithm: 'RS256' }
payload, PRIV_KEY, { expiresIn: tokenExpirationTime, algorithm: 'RS256' }
);
// send user
res.status(200).json({ token, user });
@@ -97,11 +101,10 @@ const signup = async (req, res, next) => {

const payload = {
user: user,
iat: Date.now()
}
// Create token
const token = "Bearer " + jwt.sign(
payload, PRIV_KEY, { expiresIn: "1d", algorithm: 'RS256' }
payload, PRIV_KEY, { expiresIn: tokenExpirationTime, algorithm: 'RS256' }
);
// return new user
res.status(201).json({ token, user });
40 changes: 40 additions & 0 deletions server/middlewares/auth.middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const jwt = require("jsonwebtoken");

// reading the content of the private key
// const fs = require("fs");
// pathToKey = require("path").join(__dirname, "..", "./config/id_rsa_priv.pem");
// const PRIV_KEY = fs.readFileSync(pathToKey, "utf8"); //private key is used for signing the token
require('dotenv').config()
const PRIV_KEY = process.env.PRIV_KEY;

const tokenCheck = (req, res, next) => {
// Get the token from the header if present
let getToken =
req.body.token ||
req.query.token ||
req.headers["authorization"] ||
req.headers["x-access-token"];

// If token is not present
if (!getToken) {
return res.status(403).send("A token is required for authentication");
}

const token = getToken.split(" ")[1]; //removing the Bearer from the token

// Verify the token
jwt.verify(token, PRIV_KEY, { algorithms: ["RS256"] }, (err, user) => {
// If token is not valid
if (err) {
return res.status(401).send(err);
} else {
// If token is valid
console.log("Token verified");
// Save the user in the request object
req.user = user;
}
});
next(); //calling next() to move to the next middleware
};

module.exports = tokenCheck;
2 changes: 1 addition & 1 deletion server/models/user.models.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const mongoose = require("mongoose");
import {isEmail} from "validator"
const isEmail = require("validator/lib/isEmail");

const userSchema = new mongoose.Schema({
name: String,
7 changes: 6 additions & 1 deletion server/routes/auth.routes.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
const express = require('express');
const router = express.Router()
const router = express.Router();
const authMiddleWare = require('../middlewares/auth.middleware');
const authController = require('../controllers/auth.controller');


router.post('/signin', authController.signin);

router.post('/signup', authController.signup);

router.get('/test', authMiddleWare,(req, res) => {
res.json(req.user);
});

module.exports = router;