I am trying to do a simple login using nodejs and sequelize, i already have a user on the database and i try to send the info as req.body and checking if it exist in the where clausure
Like this:
router.post('/', function (req, res, next) {
console.log("hi");
if (JSON.stringify(req.body) == "{}") {
return res.status(400).json({ Error: "Login request body is empty" });
}
if (!req.body.username || !req.body.password) {
return res.status(400).json({ Error: "Missing fields for login" });
}
User.find({ where: { username: req.body.username,password: req.body.password} })
.then(function (user) {
return res.status(200).json({ message: "loged in!" });
}).catch(function (err) {
return res.status(400).json({ Error: "There is no user with those fields" });
});
});
it enters always on the loged in message, even if i send data that doesn't exist on the database, any info why it is happening?
You need to check if user is actually defined:
User.find({ where: { username: req.body.username,password: req.body.password} })
.then(function (user) {
if (! user) {
return res.status(400).json({ Error: "There is no user with those fields" });
} else {
return res.status(200).json({ message: "loged in!" });
}
})
.catch(...)
You're assuming that a query that doesn't yield any results will throw an error, but it won't (because the query ran successfully).
Also, you can make unique index on db to be completely sure that user is unique.
Btw, this index will speed-up login process.
Sequelize index docs ref
Related
So, as you could see from my previous questions, I've been stuck in populate of mongoose. I have two models, User and Post, and currently, I'm trying to get a single user's posts but not able to do it.
getUserPosts: async (req, res) => {
try {
const user = await User.findById(req.params.id).populate("posts");
if (!user) {
return res.status(400).json({ error: "No user" });
}
return res.status(200).json({ userposts: user.posts });
} catch (err) {
return res.status(500).json({ error: "Server error" });
}
}
The problem is I'm somehow getting an empty array of posts. If I manually push the posts documents post id, then it's working, otherwise it's not.
I am trying to refactor some inherited code. In every endpoint was the same validation code. I want to pull it out into it's own method. I am new to promises, but I think that is what I want to use. The issues is prom seems to be resolved at the User.findOne call and exits with an undefined prom.promise.
cheers
bob
function validateUser(req) {
var prom = q.defer();
var token = getToken(req.headers);
if (token) {
console.log("have a token")
var decoded = jwt.decode(token, config.secret);
console.log("now going to look for the user")
//Problem exit is on next line
User.findOne({
name: decoded.name
}, function (err, user) {
if (err) throw err;
prom.reject(err);
if (!user) {
console.log("no user found")
prom.reject("Authentication failed. User not found.")
} else {
console.log("user found returning true")
prom.resolve(true);
}
})
} else {
console.log("no token found")
prom.reject("No token provided.")
}
return prom.promise;
}
why you are using promises when mongoose itself returns it.
function validateUser(req, callback) {
var token = getToken(req.headers);
if (token) {
var decoded = jwt.decode(token, config.secret);
User.findOne({
name: decoded.name
}, function (err, user) {
if (err) throw err;
callback(err);
if (!user) {
callback("Authentication failed. User not found.")
} else {
console.log("user found returning true")
callback(null, {status:true, userData:user});
}
})
} else {
callback("No token provided.")
}
}
In above code,
if token is not found callback is returned with an error in the first attempt. if token is found then it is decoded in a row and if matched in DB if the result is an error then the callback is called with err parameter else if no user is found or empty match then a custom message is sent in callback error part. But in final is returned as success with status and userData.
I am trying to make a request and login but the function checks the first element from my users database. The problem is here
var user = users[0]; how can I change code to select the users that I give it for input?
router.post('/login', function(req, res) {
User.User.forge(
{
where: {email: req.body.email}
}
).fetchAll().then(function(users) {
if (users.length == 0) {
res.json({success: false, msg: 'Authentication failed. User not found.'});
} else {
// check if password matches
var user = users[0];
user.comparePassword(req.body.password, function (err, isMatch) {
if (isMatch && !err) {
// if user is found and password is right create a token
var token = jwt.encode(user, '123456');
res.json({success: true, token: 'JWT ' + token});
} else {
res.json({success: false, msg: 'Authentication failed. Wrong password.'});
}
});
}
});
});
I've less than 50 reputations so I cannot leave a comment which would be the proper way to participate here.
Even if I'm not familiar with your syntax I don't think
var user = users[0];
is the propblem here. I guess the email is an unique property so why does
where: {email: req.body.email}
return a list with length > 1?
Do you use fetchAll() correctly or is there another method?
Hello guys am new to Sails.js ( using MySQL )
Am trying to find if a user already exists before registration.
Here this is the code:
register:function(req, res, next){
var params = req.params.all();
User.find({
or : [
{ usrnm:params.usrname },
{ eml:params.eml }
]
})
.exec(function (err, user){
if (err) {
return res.negotiate(err);
}
if (user) {
res.status(400);
return res.json('User already exists!');
}
});
User.create(params, function(err, user){
if(err){
return next(err);
}
res.status(201);
res.json(user);
});
}
The problem is:
The response is always "User already exists!" with status code - 400
If user exists with the given username or/and email, the above message is displayed regardless and then something is getting logged in the console ( which I dont understand ) and user is not created as in my MySQL those two fields are unique.
**If user does not exists ** the user gets created behind but it still displays the above message.
I want to display the message only if user exists (ie if given credentials matches) else respond with 201
register:function(req, res, next){
var params = req.params.all();
User.find({
or : [
{ usrnm:params.usrname },
{ eml:params.eml }
]
})
.exec(function (err, users){
if (err) {
return res.negotiate(err);
}
if (users.length) {
res.status(400);
return res.json('User already exists!');
} else {
User.create(params, function(err, user){
if(err){
return next(err);
} else {
res.status(201);
res.json(user);
}
});
}
});
}
You should call the create user method if a user with those parameters do not already exist, and so should put it inside the callback.
The User.find() function returns an array, so you need to check its length to see if there are any matching objects.
Okay guys I figured out a solution, i will put it here in case if it helps someone
if (user) { // will be true even if user = []
res.status(400);
return res.json('User already exists!');
}
In case when user is not found in the DB , user is = [ ] , this means [ ] != false
, hence the message within the scope is getting displayed.
I started the implementation of a RESTful API usin node.js, express, and mongodb. Everything went well until now, I've a route to authenticate an user as follow:
apiRoutes.post('/authenticate', function(req, res) {
User.findOne({
nickname: req.body.nickname
}, function(err, user) {
if (err) throw err;
if (!user) {
res.json({
success: false,
message: 'Authentication failed. User not found.'
});
} else if (user) {
console.log(user);
console.log(user.nickname);
console.log(user.email);
console.log(user.password);
console.log(user.sexe);
if (user.password != req.body.password) {
res.json({
success: false,
message: 'Authentication failed. Wrong password.'
});
} else {
var token = jwt.sign(user, app.get('salt'), {
expiresInMinutes: 1440 // expires in 24 hours
});
res.json({
success: true,
token: token
});
}
}
});
});
The user is retrieved, and loged in the console as follow:
{ sexe: 'H',
email: 'MrPanda#gmail.com',
password: 'bambou',
nickname: 'MrPanda',
_id: 56cb703e7aef3f83c7dac0a7 }
which is perfect, but then, the three following consol.log return the three following lines:
MrPanda
MrPanda#gmail.com
undefined
H
I see absolutely no reason why the password is undefined at this point, I tried to change the attribute name to 'mdp', same issue... Any ideas ? Thanks
If you are using mongoose it does not return a plain JSON object. It is actually a special mongoose object and may not function how you expect.
You have two options:
Convert the mongoose object to a JSON object.
Add {lean: true} to the Users options parameter.
OR JSON.stringify(user)
OR user.toJSON()
Use the proper get() and set() methods (which you should be doing anyways).
user.get('password')
user.get('email')
user.get('name')
Try that and let me know if it doesn't work still.