-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implemented authentication and authorization features
- Loading branch information
1 parent
8c471df
commit cec7f3c
Showing
9 changed files
with
168 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
import User from "../models/User.js"; | ||
import bcrypt from "bcrypt"; | ||
import jwt from "jsonwebtoken"; | ||
import asyncHandler from "express-async-handler"; | ||
|
||
|
||
// @desc Login | ||
// @route POST /auth | ||
// @access Public | ||
const login = asyncHandler(async (req, res) => { | ||
const { username, password } = req.body; | ||
|
||
if (!username || !password) { | ||
return res.status(400).json({ message: 'All fields are required' }); | ||
}; | ||
|
||
const foundUser = await User.findOne({ username }).exec(); | ||
|
||
if (!foundUser || !foundUser.active) { | ||
return res.status(401).json({ message: 'Unauthorized' }); | ||
}; | ||
|
||
const match = await bcrypt.compare(password, foundUser.password); | ||
|
||
if (!match) return res.status(401).json({ message: 'Unauthorized' }); | ||
|
||
const accessToken = jwt.sign( | ||
{ | ||
"UserInfo": { | ||
"username": foundUser.username, | ||
"roles": foundUser.roles | ||
} | ||
}, | ||
process.env.ACCESS_TOKEN_SECRET, | ||
{ expiresIn: '15m' } | ||
); | ||
|
||
const refreshToken = jwt.sign( | ||
{ "username": foundUser.username }, | ||
process.env.REFRESH_TOKEN_SECRET, | ||
{ expiresIn: '7d' } | ||
); | ||
|
||
// Create secure cookie with refresh token | ||
res.cookie('jwt', refreshToken, { | ||
httpOnly: true, //accessible only by web server | ||
secure: true, //https | ||
sameSite: 'None', //cross-site cookie | ||
maxAge: 7 * 24 * 60 * 60 * 1000 //cookie expiry: set to match rT | ||
}); | ||
|
||
// Send accessToken containing username and roles | ||
res.json({ accessToken }) | ||
}); | ||
|
||
// @desc Refresh | ||
// @route GET /auth/refresh | ||
// @access Public - because access token has expired | ||
const refresh = (req, res) => { | ||
const cookies = req.cookies | ||
|
||
if (!cookies?.jwt) return res.status(401).json({ message: 'Unauthorized' }); | ||
|
||
const refreshToken = cookies.jwt; | ||
|
||
jwt.verify( | ||
refreshToken, | ||
process.env.REFRESH_TOKEN_SECRET, | ||
asyncHandler(async (err, decoded) => { | ||
if (err) return res.status(403).json({ message: 'Forbidden' }) | ||
|
||
const foundUser = await User.findOne({ username: decoded.username }).exec() | ||
|
||
if (!foundUser) return res.status(401).json({ message: 'Unauthorized' }) | ||
|
||
const accessToken = jwt.sign( | ||
{ | ||
"UserInfo": { | ||
"username": foundUser.username, | ||
"roles": foundUser.roles | ||
} | ||
}, | ||
process.env.ACCESS_TOKEN_SECRET, | ||
{ expiresIn: '15m' } | ||
) | ||
|
||
res.json({ accessToken }) | ||
}) | ||
); | ||
}; | ||
|
||
// @desc Logout | ||
// @route POST /auth/logout | ||
// @access Public - just to clear cookie if exists | ||
const logout = (req, res) => { | ||
const cookies = req.cookies | ||
if (!cookies?.jwt) return res.sendStatus(204) //No content | ||
res.clearCookie('jwt', { httpOnly: true, sameSite: 'None', secure: true }) | ||
res.json({ message: 'Cookie cleared' }) | ||
}; | ||
|
||
export { | ||
login, | ||
refresh, | ||
logout | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
import rateLimit from "express-rate-limit"; | ||
import { logEvents } from "./logger.js"; | ||
|
||
const loginLimiter = rateLimit({ | ||
windowMs: 60 * 1000, // 1 minute | ||
max: 5, // Limit each IP to 5 login requests per `window` per minute | ||
message: | ||
{ message: 'Too many login attempts from this IP, please try again after a 60 second pause' }, | ||
handler: (req, res, next, options) => { | ||
logEvents(`Too Many Requests: ${options.message.message}\t${req.method}\t${req.url}\t${req.headers.origin}`, 'errLog.log') | ||
res.status(options.statusCode).send(options.message) | ||
}, | ||
standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers | ||
legacyHeaders: false, // Disable the `X-RateLimit-*` headers | ||
}) | ||
|
||
export { loginLimiter }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
import express from "express"; | ||
import * as authController from "../controllers/authController.js"; | ||
import { loginLimiter } from "../middleware/loginLimiter.js"; | ||
|
||
const router = express.Router(); | ||
|
||
router.route('/') | ||
.post(loginLimiter, authController.login); | ||
|
||
router.route('/refresh') | ||
.get(authController.refresh); | ||
|
||
router.route('/logout') | ||
.post(authController.logout); | ||
|
||
// Export the router instance | ||
export { router }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters