I have a form with the onSubmit function, which collects input from the state and sends it to the server.
Then I collect the input from req.body and ip from the headers on the backend.
IP is saved, and the form input is transferred to another daemon process via pm2 and finally sent by mail with a mandrel, and not saved on any db.
Scenario I
The ip clients are compiled and saved for redis:
module.exports = (req, res, next) => {
const client = redis.createClient()
client.select(2, (err) => {
console.log('redisWriteIP selected 2snd redis db')
if (err) {
next(new DbErr(err))
} else {
const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress
client.set(ip, true, 'EX', 120, (err, rep) => {
if (err) {
next(new DbErr(err))
} else {
return next()
}
})
}
})
}
Question 1 : Do I need to sanitize ip in this scenario? Can a user smooth out request headers and send anything else besides their ip address or numbers?
Scenario 2
Input fields filled by the user and sent to api on req.body
Api server - using the body analyzer:
const api = express()
const bodyParser = require('body-parser')
api.use(bodyParser.urlencoded({ extended: false }))
api.use(bodyParser.json())
api.set('trust proxy', 'loopback')
const routes = require('./routes')
api.use('/api', routes)
middlware:
module.exports = (req, res, next) => {
let payload = req.body
const err = {}
let isFormValid = true
if (payload.question) {
if (typeof payload.email !== 'string' || !validator.isEmail(payload.email)) {
isFormValid = false
err.email = 'Please provide a correct email address.'
}
if (typeof payload.name !== 'string' || payload.name.trim().length === 0) {
isFormValid = false
err.name = 'Please provide your name.'
}
} else if (payload.booking) {
if (typeof payload.email !== 'string' || !validator.isEmail(payload.email)) {
isFormValid = false
err.email = 'Please provide a correct email address.'
}
if (typeof payload.dates !== 'string' || payload.dates.trim().length === 0) {
isFormValid = false
err.msg = 'Something went wrong'
}
} else {
isFormValid = false
err.msg = 'Something went wrong'
}
if (!isFormValid) {
next(new FormFieldErr(JSON.stringify(err)))
} else {
return next()
}
}
, :
...
pm2.sendDataToProcessId(pid, payload, (err, res) => {
if (err) {
next(new MailerErr(err))
} else {
next()
}
})
2:
req.body, - , db.
, if (payload.question) {...} pm2.sendDataToProcessId?
, , .
3
, middlware req.body , , ?
, , , . , req.body , .
- :
:
module.exports = (req, res, next) => {
req.body.replace(/[|&;$%@"<>()+,]/g, "")
return next()
}
api:
api.route('/', sanitise, someMiddleware, (req, res, next) => {
// Now we can safely handle req.body in the middlwares.
})