How do I exclude additional properties using express-validator? - javascript

I am using express-validator in my express app, and I am attempting to prevent additional fields being specified on POST requests. This is because I am passing the value of req.body to my ORM to insert into the database, and I want to avoid having to explicitly map between my inserted object and request body alongside adding validators.
Is this possible? I can't seem to find it in the documentation. Using JSON Schema you can do this with additionalProperties: false

After some more research, I found that it's possible to do with with the Matched Data API
In my express controller I can now do;
const { matchedData } = require('express-validator');
(req, res) => {
const matched = matchedData(req, {
includeOptionals: true,
});
db.insert(matched)
...
}

Related

Is this a secure enough method to recover data?

I'd love to know if this method I'm using is secure enough to use on a public project, since I can't really find any other way to retrieve my id from my currently logged in user, but it's a fairly straightforward method , I find. If this method is not secure would it be possible to have a way to proceed? Thanks in advance.
I have a button for example when I use the send of the html that there is inside my div userid on the server to then use this information to make SQL queries from my app.js server.
I use socket.io hbs express node js jwt mysql
From my pages.js file generated with the express library where the main roads of my website are located, I send my user ID.
router.get('/accueil', authController.isLoggedIn, (req, res) => {
if(req.user) {
res.render('./accueil', {
data: req.user.id
});
} else {
res.redirect('/');
}
});
With Handlebars I display this data in my index.hbs (display: none;).
<div id="iduser">{{data}}</div>
Then I get my iduser div on my client.js
let userid = document.getElementById('iduser').innerHTML;
// (My method to display this div)
socket.on('uid', (data) => {
pargent.innerHTML = JSON.stringify(data.data[0].argent);
})
//
So I want to use this userid variable to make SQL queries from my app.js.
(let userid = document.getElementById('iduser').innerHTML;)
I am using socket.io for communication between client and server to send my userid data
Example :
db.query('UPDATE users SET money = money + ? WHERE id = ?', [100, theUserId]);
No
Never trust user supplied data.
References:
https://www.oreilly.com/library/view/http-developers-handbook/0672324547/0672324547_ch22lev1sec1.html
https://flylib.com/books/en/1.290.1.90/1/
https://www.garybell.co.uk/never-trust-user-input/
https://medium.com/#berniedurfee/never-trust-a-client-not-even-your-own-2de342723674
https://www.invicti.com/blog/web-security/input-validation-errors-root-of-all-evil/
https://laravel-news.com/never-trust-your-users
https://www.wearenova.co.uk/nova-blog/when-it-comes-to-online-security-why-you-should-never-trust-a-client
It depends on your authController.isLoggedIn logic,
But I would like to suggest an alternative solution simple as that;
iron-session
Read their docs, it's matches your use case and easy to use; here is equivalent of the snippet you provided with iron session:
//initiate session middleware yourself
router.use(session)
// later here
router.get('/accueil', (req, res) => {
if(req.session.user) {
res.render('./accueil', {
data: req.user.id
});
} else {
res.redirect('/');
}
});

Updating all elements from a JSON file via Express router.put with Sequelize

I am trying to create an Express router route which allows me to update a MySQL schema containing data about 'members' (members of clubs). The members table in the schema contains many columns, e.g. member_id, forename, surname, address, etc, etc. I have created an Express route which allows me to update (using the Sequelize update method) a single column in the table, by specifying the specific column - in my example below, the column 'forename'. This code has been successfully tested using Insomnia.
router.put("/byId/", async (req, res) => {
const { forename, member_id } = req.body
await Members.update({forename: forename}, {where:{ member_id: member_id}})
res.json(forename)
});
Whilst I could add all the table columns in the const definition and in the Sequelize update method, I was wondering if there is a way that I can code this so that it reads whatever key value pairs it finds in the JSON and updates all fields for which key value pairs exist.
I do something similar to the approach I have in mind when creating a member, using the router below - where individual columns are not specified specifically:
router.post("/", async (req, res) => {
const member = req.body;
await Members.create(member);
res.json(member);
});
So I attempted to modify my update router as follows, following a similar approach to the create code:
router.put("/byId/", async (req, res) => {
const member = req.body
await Members.update(member, {where:{ member_id: member_id}})
res.json(member)
});
However this threw a "Error: Failure when receiving data from the peer" error in Insomnia, and crashed the Node server with an error "ReferenceError: member_id is not defined".
This latter error makes sense to me - I'm trying to update a record for a specific member_id, but don't define member_id. I'm just not clear exactly how I can define that whilst retaining the 'update all fields for which key value pairs exist' functionality I'm looking for. Nor whether resolving that will be enough to make this route work as I'd hoped.
Per Dave's comment:
The member ID is a property of member and must be accessed as such.
It was an easy fix:
router.put("/byId/", async (req, res) => {
const member = req.body
await Members.update(member, {where:{ member_id: member.member_id}})
res.json(member)
});

Express JS url parameter variable issue

I have this user route
const express = require('express');
const router = express.Router();
const {
GetAll,
} = require('../areas/directory/controllers/usercontroller');
router.route('/getall?:username&:email').get(GetAll);
module.exports = router;
When I try to access the url in Postman like this: http://localhost:5000/api/user/getall?username=nameone&email=emailone
I get this error: Cannot GET /api/user/getall
But, if I change it to
router.route('/getall/:username&:email').get(GetAll);
and access the url in Postman like this: http://localhost:5000/api/user/getall/username=nameone&email=emailone
it works.
On the other hand, even if it works, I am unable to get the value of my variable.
var username = req.params.username;
will return username=nameone instead.
For http://localhost:5000/api/user/getall?username=nameone&email=emailone to work, you should change
router.route('/getall?:username&:email').get(GetAll);
to
"router.route('/getall').get(GetAll);"
and use req.query.username to access the value of username query parameter and req.query.email to access the value of email query parameter.
After making these changes, you can call http://localhost:5000/api/user/getall?username=nameone&email=emailone in Postman, you will be able to see the value of username and email in your code.
This is because you need not have to specify the query parameters in the path, like ?:username in router.route('getall').
Edit: adding few more details about path and query
Please see the top 2 solutions for this question to learn more about path and query and why you should change your code to the way I mentioned above : here is the link.
Reason for the error...
Actually the thing what you are trying to do is called query passing in the rest api..
But you are trying to access them like params
sollution 💖
follow the steps to access the queries
**To pass the data using ? in the api request should be like this you can have multiple query objects
http://localhost:5000/getall?email='email'&&password='password'
Access the query in express app like this
app.post('/getall', (req, res) => {
const {
email,
password
} = req.query
return res.status(200).json({
email,
password
})
})
The req.query contains the data you trying to pass throw ? and then query properties
Response of above code would be like this
{
"email": "'email'",
"password": "'password'"
}
You should not give query parameters in URL. So, for express the url must be just /getall and in your code you access those variables using req.params.whatever_query_parameter

Sending an array with axios.get as params is undefined

I am making a get request with additional params options, since I am using that request on a filter, so the params are filters for what to get back:
const res = await axios.get("http://localhots:3000/getsomedata", {
params: {
firstFilter: someObject,
secondFilter: [someOtherObject, someOtherObject]
}
});
The request goes through just fine, on the other end, when I console.log(req.query); I see the following:
{
firstFilter: 'someObject',
'secondFilter[]': ['{someOtherObject}', '{someOtherObject}'],
}
If I do req.query.firstFilter that works just fine, but req.query.secondFilter does not work and in order for me to get the data, I have to do it with req.query["secondFilter[]"], is there a way to avoid this and be able to get my array of data with req.query.secondFilter?
My workaround for now is to do:
const filter = {
firstFilter: req.query.firstFilter,
secondFilter: req.query["secondFilter[]"]
}
And it works of course, but I don't like it, I am for sure missing something.
Some tools for parsing query strings expect arrays of data to be encoded as array_name=1&array_name=2.
This could be a problem if you have one or more items because it might be an array or might be a string.
To avoid that problem PHP required arrays of data to be encoded as array_name[]=1&array_name[]=2 and would discard all but the last item if you left the [] out (so you'd always get a string).
A lot of client libraries that generated data for submission over HTTP decided to do so in a way that was compatible with PHP (largely because PHP was and is very common).
So you need to either:
Change the backend to be able to parse PHP style
Change your call to axios so it doesn't generate PHP style
Backend
The specifics depend what backend you are using, but it looks like you might be using Express.js.
See the settings.
You can turn on Extended (PHP-style) query parsing by setting it to "extended" (although that is the default)
const app = express()
app.set("query parser", "extended");
Frontend
The axios documentation says:
// `paramsSerializer` is an optional function in charge of serializing `params`
// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
paramsSerializer: function (params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
So you can override that
const res = await axios.get("http://localhots:3000/getsomedata", {
params: {
firstFilter: someObject,
secondFilter: [someOtherObject, someOtherObject]
},
paramsSerializer: (params) => Qs.stringify(params, {arrayFormat: 'repeat'})
});
My example requires the qs module
This has to do with params not being serialized correctly for HTTP GET method. Remember that GET has no "body" params similar to POST, it is a text URL.
For more information I refer to this answer, which provides more detailed info with code snippets.

Mongodb does not save a document

I am trying to store some data from an HTML formulary. I send the data using the HTTP POST method and I received them using Express framework in Node.js. The data arrives and it seems to work, but when I try to store them into MongoDB using Mongoose, the database is created but no data is stored when I execute DB.sis_dictionary.find()
I've tried to build different types of schemas and models, but none seems to work. And I get no error from Node.js, it seems to be working, but the MongoDB database does not store anything.
const Mongoose = require('mongoose');
Mongoose.connect('mongodb://localhost:27017/sis_dictionary', {useNewUrlParser: true});
const Schema = Mongoose.Schema;
const wordSchema = new Schema({
word: String
})
const Word = Mongoose.model('Word', wordSchema);
app.post('/saveWord', (req, res) => {
var word = new Word({word: String(req.body)});
word.save(function(err){
if(err) {
return console.error(err);
} else {
console.log("STATUS: WORKING");
}
})
console.log(req.body);
})
server.listen(3000);
console.log("SERVER STARTUP SUCCESS");
In the console, I get the message: "STATUS: WORKING".
sis_ditionary is your DB name and Words should be your collection name. As mongoose automatically creates a plural name for collection from a model if model name not specified when creating from a schema
db.collection.find() is a command to find a collection data when using mongo-shell. Run below command to get data:
use sis_dictionary
db.Words.find()
To beautify result use pretty method
db.Words.find().pretty()
First command will select DB and second command list collection data.
So when you execute db.sis_dictionary.find() it won't work because sis_dictinary is your DB name.
Nodejs way with 'mongoose'
//Model.find({});
Word.find({});
Also, check this line var word = new Word({word: String(req.body)});
What does req.body have? If req.body is {word:"example word"} then you directly pass req.body to modal constructor ie new Word(req.body);
According to your database URL, mongodb://localhost:27017/sis_dictionary, sis_dictionary is the database name.
And according to your mongoose model, Word is your collection name.
When you save a document, it saves under a collection. So you have to make a query under the collections.
So when you try to get data using DB.sis_dictionary.find(), definitely it won't work.
Your query should be like db.collection.find()
Use the following query,
use sis_dictionary
db.words.find()
// for better view
db.words.find().pretty()
For more please check the documentation.
Thank you everybody. You were all right, it was a problem related to my collections names. db.words.find().pretty() worked perfectly!The problem is solved.

Categories