Skip to content

Commit

Permalink
authentication function #9
Browse files Browse the repository at this point in the history
  • Loading branch information
ElhamFadel committed Oct 26, 2021
1 parent 3dd27b5 commit 02cca9b
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 14 deletions.
13 changes: 0 additions & 13 deletions server/controllers/middleware/auth/authenticateToken.js

This file was deleted.

9 changes: 8 additions & 1 deletion server/controllers/middleware/auth/createToken.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
const {sign} = require('jsonwebtoken');
module.exports = (req, res, next) => {
const payload = req.user;
const accessToken = sign(payload,process.env.ACCESS_TOKEN_SECRET);
try{
const accessToken = sign(payload,process.env.ACCESS_TOKEN_SECRET);
res.status(201).cookie('token', accessToken, {
httpOnly: true
}).json({
message: 'User created successfully'
});
}catch(err){
return next(err)
}

}
16 changes: 16 additions & 0 deletions server/controllers/middleware/auth/isAuth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const { verify } = require('jsonwebtoken');

module.exports = async(req, res, next) => {
if (req.cookies?.token) {
try{
const token = verify(req.cookies.token, process.env.ACCESS_TOKEN_SECRET)
req.user = token;
next()
}catch{
res.status(403).json({ message: 'Invalid token' })
}

} else {
res.status(401).json({ message: 'No token provided' });
}
};

0 comments on commit 02cca9b

Please sign in to comment.