When using a get request for all the users in my database (see code below) i only get the "first" user in the database. If i instead try to use the "findOne"-method i get the same user as before no matter what i put in (the username doesn't even have to be in the db it still gives me the same user). I've been trying to understand why this isn't working but can't find any problems with the code. Could it be a problem with db settings or something similar? All help is appreciated!
In AuthController:
// Get all users
AuthController.allusers = function(req, res) {
User.find({}, function(err, users) {
}).then(function(users) {
res.json({users: users});
});
}
In routes:
// GET Routes.
router.get('/users', AuthController.allusers);
Since you are using Sequelizejs, you might want to do findAll.
AuthController.allusers = function(req, res) {
User.findAll().then(function (users) {
res.send({users: users});
}
}
According to the docs:
find - Search for one specific element in the database
findAll - Search for multiple elements in the database
Related
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('/');
}
});
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)
});
To summarize, I have a mongodb database with a 'groupcollection' in it. One of the attributes is called 'deleted' and it has values either true or false. I want to update the value of 'deleted' for a specific document using 'groupname' as the query attribute. However, when I try the code below I receive the error "TypeError: collection.updateOne is not a function"
router.post('/deletegroup', function(req, res) {
var db = req.db;
var collection = db.get('groupcollection');
var filter = {"groupname" : req.body.groupname};
var updates = { $set: {"deleted" : true} };
collection.updateOne(filter, updates, function(err) {
if (err) {
// If it failed, return error
res.send("There was a problem deleting the group from the database.");
}
else {
// And forward to success page
res.redirect("grouplist");
}
});
});
I've read the documentation on updateOne() for Node.js from mongoDB and I can't seem to figure out the reason for the error. Also, I am still very new to javascript/nodejs/mongo so I would greatly appreciate more informative answers!
The solution I came up with was using unique IDs for each group and instead of using updateOne() just using update() and having the unique ID as the query to make sure that I don't modify groups with the same name
Given routes
GET /user/42
GET /user/dude
where 42 is user id and dude is username.
So, I want to have method in my controller that return user for both cases. Here it is:
// api/controllers/UserController.js
findOne: function(req, res) {
User.findOne({
or: [
{id: req.params.id},
{username: req.params.id}
]
}).exec(function(err, user) {
if (err) {
return console.log(err);
}
res.json(user);
});
},
When I try to GET /user/42 everything is fine.
When I try to GET /user/dude I get error:
Error (E_UNKNOWN) :: Encountered an unexpected error
error: invalid input syntax for integer: "dude"
It seems like sails refuses to process {id: 'dude'} because of type mismatch.
I am using sails 0.10.5 with sails-postgresql 0.10.9. So what am I doing wrong?
UPD: I do know how to solve problem. Of course I can put if statement to my controller and check what type of parameter it got. Actually, I just created two routes with regexp parameters that point to single method.
My actual problem is why I can not do this with or. Does sails provide such way?
By default, sails get method only supports id numbers. You will need
to define custom routes and implement the relevant api method to
support a get request using a string instead of a number.
Technical Details:
To solve your exact problem, you need to define the following route in your routes.js
module.exports.routes = {
...
'/user/get/:param': 'UserController.findByIDorName',
...
}
This will pass anything after the /user/get/ as the parameter named 'param' to the findByIDorName controller method.
Next you need to check the type of the param and decide if you want to fetch the user info based on the id or the name, so add this function in your userController.js
findByIDorName : function (req, res) {
if (isNaN(req.param)){
//find the user by his username after any validation you need
}
else {
//find the user by his id and return
}
}
I am using express to connect to my mongoDB:
mongodb.MongoClient.connect(mongourl, function(err, database) {
// How would one switch to another database here?
});
I have to connect to the admin database in the first place. After the conenction has been established, i would like to switch the database.
Although i have searched through the official documentation, i was unable to find something that fits my needs.
I am aware of the MongoClient::open() method, but i would like to stick to connect().
Any help is appreciated.
You can switch to another database like so:
mongodb.MongoClient.connect(mongourl, function(err, database) {
// switch to another database
database = database.db(DATABASE_NAME);
...
});
(docs)
EDIT: for clarification: this also allows you to open multiple databases over the same connection:
mongodb.MongoClient.connect(mongourl, function(err, database) {
// open another database over the same connection
var database2 = database.db(DATABASE_NAME);
// now you can use both `database` and `database2`
...
});
You just have to call MongoClient.connect once again, because there is one connection per database. That means, you cannot change the database of an existing connection. You have to connect a second time:
mongodb.MongoClient.connect(mongourl, function(err, database) {
mongodb.MongoClient.connect(mongourl_to_other_database, function(err, database2) {
// use database or database2
});
});