Skip to content
This repository has been archived by the owner on Oct 16, 2023. It is now read-only.

Commit

Permalink
validação em controllers e limite de requisições em rotas (#4)
Browse files Browse the repository at this point in the history
* feat: ✨ ratelimit em rotas

* feat: 🦺 operador $eq para validação

* style: 🎨 formatar controllers/rotas

* refactor: ♻️ alterar ordem de router.use em task.js
  • Loading branch information
renatocfrancisco authored Jul 5, 2023
1 parent 77dd9be commit 58fa41f
Show file tree
Hide file tree
Showing 5 changed files with 30 additions and 16 deletions.
14 changes: 7 additions & 7 deletions controllers/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ class AuthController {
return res.status(400).json('Please enter all fields required to login')
}

const foundUser = await User.findOne({ username })
const foundUser = await User.findOne({ username: { $eq: username } })
const validPass = foundUser ? await bcrypt.compare(password, foundUser.password) : false
if (!foundUser || !validPass) {
return res.status(400).json('Invalid login credentials')
Expand All @@ -24,7 +24,7 @@ class AuthController {
}

static refresh = async (req, res) => {
const refreshToken = getRefreshToken();
const refreshToken = getRefreshToken()
if (!refreshToken) {
return res.status(400).json({ msg: 'User not logged in' })
}
Expand All @@ -37,14 +37,14 @@ class AuthController {
res.status(400).json({ msg: 'Invalid token' })
}

function getRefreshToken() {
if(!req.headers.cookie) {
if(!req.headers.cookies){
function getRefreshToken () {
if (!req.headers.cookie) {
if (!req.headers.cookies) {
return null
}else{
} else {
return req.headers.cookies.split('jwt=')[1].split(';')[0].trim()
}
}else{
} else {
const cookie = req.headers.cookie.split(';').find(c => c.trim().startsWith('jwt='))
if (!cookie) {
return null
Expand Down
8 changes: 4 additions & 4 deletions controllers/task.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ class TaskController {
}

static getTasks = async (req, res) => {
Task.find({ user: req.user._id })
Task.find({ user: { $eq: req.user._id } })
.then(tasks =>
tasks.length === 0
? res.status(404).json({ msg: 'No tasks found. Get busy!' })
Expand All @@ -37,7 +37,7 @@ class TaskController {
}

static getTask = async (req, res) => {
Task.find({ _id: req.params.id, user: req.user._id })
Task.find({ _id: { $eq: req.params.id }, user: { $eq: req.user._id } })
.then(task => res.json(task))
.catch(err => res.status(400).json('Error: ' + err))
}
Expand Down Expand Up @@ -69,7 +69,7 @@ class TaskController {
updateObj.task = task
}

Task.findOneAndUpdate({ _id: req.params.id, user: req.user._id }, { $set: updateObj }, { new: true })
Task.findOneAndUpdate({ _id: { $eq: req.params.id }, user: { $eq: req.user._id } }, { $set: updateObj }, { new: true })
.then(task => {
if (!task) {
return res.status(404).json('Task not found')
Expand All @@ -80,7 +80,7 @@ class TaskController {
}

static deleteTask = (req, res) => {
Task.findOneAndDelete({ _id: req.params.id, user: req.user._id })
Task.findOneAndDelete({ _id: { $eq: req.params.id }, user: { $eq: req.user._id } })
.then(() => res.json('Task deleted.'))
.catch(err => res.status(400).json('Error: ' + err))
}
Expand Down
6 changes: 2 additions & 4 deletions routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@ const rateLimit = require('express-rate-limit')
const { login, refresh, logout } = require('../controllers/auth')

const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100,
standardHeaders: true,
legacyHeaders: false,
windowMs: 1 * 60 * 1000,
max: 50,
message: 'Max requests reached. Please try again later.'
})

Expand Down
9 changes: 8 additions & 1 deletion routes/task.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
const jwt = require('../middlewares/jwt')
const router = require('express').Router()
const TaskController = require('../controllers/task')
const rateLimit = require('express-rate-limit')

router.use(jwt)
const limiter = rateLimit({
windowMs: 1 * 60 * 1000,
max: 50,
message: 'Max requests reached. Please try again later.'
})

router.use(limiter, jwt)

router.get('/', TaskController.getTasks)
router.get('/:id', TaskController.getTask)
Expand Down
9 changes: 9 additions & 0 deletions routes/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@ const jwt = require('../middlewares/jwt')
const admin = require('../middlewares/admin')
const router = require('express').Router()
const UserController = require('../controllers/user')
const rateLimit = require('express-rate-limit')

const limiter = rateLimit({
windowMs: 1 * 60 * 1000,
max: 50,
message: 'Max requests reached. Please try again later.'
})

router.use(limiter)

router.get('/', jwt, admin, UserController.getUsers)
router.get('/:id', jwt, admin, UserController.getUser)
Expand Down

0 comments on commit 58fa41f

Please sign in to comment.