login validation with response from controller - mysql

I am using simple validation for login page. In the controller i have used the validation conditions.
LoginController.js
login : function(req,res) {
var username = req.param('username');
var password = req.param('password');
console.log("user : " + username + " : " + password);
Login.findOne({ username: username }, function (err, usr) {
if (err) {
res.send(500, { error: "DB Error" });
} else {
if (usr) {
console.log("found user : " + usr.username + " password : " + usr.password)
if (password == usr.password) {
req.session.user = usr;
res.send(200,usr);
} else {
res.send(400, { error: "Wrong Password" });
}
} else {
res.send(404, { error: "User not Found" });
}
}
});
These errors are displayed in the server side, like in run time to show these error in User Interface(UI) with the resin the react file
LoginForm.jsx
signin: function() {
console.log("in Signin");
var username = this.refs.username.value.trim();
var password = this.refs.password.value.trim();
this.onSubmit({username: username, password: password});
this.refs.password.value = '';
},
onSubmit: function(login) {
var username = this.refs.username.value.trim();
var password = this.refs.password.value.trim();
socket.post(this.props.url, login, function whenServerResponds(usr) {
console.log(usr);
/// how to correct it
if(res.usr){alert("login success");}else{
if(res.getResponseHeader("error")){alert("password incorrect");}
else{alert("user not found")}
///
}
});
},

This format is not gonna work res.send(200,usr);
Try to send in exact format like this
login: function(req, res) {
var username = req.param('username');
var password = req.param('password');
console.log("user : " + username + " : " + password);
Login.findOne({
username: username
}, function(err, usr) {
if (err) {
res.status(500).send({
error: "DB Error"
});
} else {
if (usr) {
console.log("found user : " + usr.username + " password : " + usr.password)
if (password == usr.password) {
req.session.user = usr;
res.status(200).send(usr);
} else {
res.status(400).send({
error: "Wrong Password"
});
}
} else {
res.status(404).send({
error: "User not Found"
});
}
}
});
}
And access your user object or error

Related

TypeError: Cannot read properties of undefined (reading 'password') NodeJS

When I try to use an invalid email address in the login form, the app crashes saying: Cannot read properties of undefined (reading 'password').
You can see my auth.js's login part below:
exports.login = async (req, res) => {
try {
const { email, password } = req.body;
if ( !email || !password ) {
return res.status(400).render('login', {
message: 'Please provide an email and password.'
})
}
db.query('SELECT * FROM users WHERE email = ?', [email], async (error, results) => {
console.log(results);
if( !results || !(await bcrypt.compare(password, results[0].password) ) ) {
res.status(401).render('login', {
message: 'Email or password is incorrect.'
})
} else {
const id = results[0].id;
const token = jwt.sign({ id }, process.env.JWT_SECRET, {
expiresIn: process.env.JWT_EXPIRES_IN
});
console.log('The token is: ' + token);
const cookieOptions = {
expires: new Date(
Date.now() + process.env.JWT_COOKIE_EXPIRES * 24 * 60 * 60 * 1000
),
httpOnly: true
}
res.cookie('jwt', token, cookieOptions);
res.status(200).redirect("/");
}
})
} catch (error) {
console.log(error);
}
}
It should show the same line that I can see when I use an incorrect password (That part works just fine).
message: 'Email or password is incorrect.'
If the email is invalid, the query will return an empty array, not an undefined, meaning that your check is wrong - you should check the length of the array.
Of course, you can always leave the check that result is defined just to be on the safe side:
if( !results || !results.length || !(await bcrypt.compare(password, results[0].password) ) ) {
res.status(401).render('login', {
message: 'Email or password is incorrect.'
});
} else {

How do i produce multer error message in my postman

Im trying to res.status.send a multer error message to postman when my file image exceeds 1MB. But when i try to run my code it only gives me this entire chunk of error message. I just want to get the error message itself(LIMIT_FILE_SIZE).Is there any way to achieve this?
IMAGE HERE
My current app.js:
var multer = require('multer');
var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, './uploads');
},
filename: function(req, file, callback) {
callback(null, path.basename(file.originalname));
}
})
const upload = multer({
dest: storage,
storage: storage,
limits: {
fileSize: 1024 * 1024
},
fileFilter: function(req, file, callback, error) {
var ext = path.extname(file.originalname);
var error_msg = error instanceof multer.MulterError
if(ext !== '.jpg') {
req.fileValidationError = "Not a jpg file!";
return callback(null, false, req.fileValidationError);
}
if(error_msg) {
return callback(null, false, new MulterError('LIMIT_FILE_SIZE'))
}
callback(null,true)
}
});
app.post("/upload",upload.single('name'),(req,res,next) => {
if(req.fileValidationError) {
res.status(500).send({message:req.fileValidationError});
}
else {
if(error.code === 'LIMIT_FILE_SIZE') {
req.fileSizeError = "Image more than 1MB!"
res.status(500).send({message:req.fileSizeError});
}
else {
console.log('File Received!');
console.log(req.file);
var sql = "INSERT INTO `file`(name,description,type,size) VALUES('" + req.file.filename + "', '" + (req.file.encoding + "_" + req.file.destination + "_" + req.file.path)+ "', '" + req.file.mimetype + "', '" + req.file.size + "')";
db.query(sql, (error, results) => {
console.log('Inserted Data!');
});
const message = "Successfully Uploaded!"
res.status(200).send({message:message, file_details:req.file})
}
}
})
Multer delegates the error to Express which is the standard way of throwing errors in express. To catch a specific error, you can use the multer upload middleware inside the route callback. This is the method as given by multer's documentation, also mentioned by #Mattia Rasulo
router.post('/image', function (req, res, next) {
upload.single('image')(req, res, function (error) {
if (req.fileValidationError) {
res.status(500).send({ message: req.fileValidationError });
}
else {
if (error) {
res.status(500).send({ message: error.code === 'LIMIT_FILE_SIZE' ? "Image more than 1MB!" : error.message });
}
else {
console.log('File Received!');
console.log(req.file);
var sql = "INSERT INTO `file`(name,description,type,size) VALUES('" + req.file.filename + "', '" + (req.file.encoding + "_" + req.file.destination + "_" + req.file.path)+ "', '" + req.file.mimetype + "', '" + req.file.size + "')";
db.query(sql, (error, results) => {
console.log('Inserted Data!');
});
const message = "Successfully Uploaded!"
res.status(200).send({message:message, file_details:req.file})
}
}
});
});
Multer just sends the error to your global error middleware so you just catch it and check upon what error is:
if(err.message === 'file too large') [change the message as you need].
This is how I've handled your exact same issue!
https://www.npmjs.com/package/multer#error-handling

Error retrieving Entry with AreaName in node.js

I am trying to perform a get with multiple parameters in node.js . I have the following files
entry.routes.js
module.exports = app => {
const entry = require("../controlers/entry.controller.js");
// Retrieve a single Entry with Id
app.get("/entry/:Id", entry.findOne);
app.get("/energy/api/ActualTotalLoad/:AreaName/:Resolution/:Year/:Month/:Day", entry.find1a);
};
ActualTotalLoad.model.js
const sql = require("./db.js");
// constructor
const Entry = function(entry) {
this.Id=entry.Id
};
Entry.findByPk = (Id, result) => {
sql.query(`SELECT * FROM ActualTotalLoad WHERE Id = ${Id}`, (err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
if (res.length) {
console.log("found entry: ", res[0]);
result(null, res[0]);
return;
}
// not found Customer with the id
result({ kind: "not_found" }, null);
});
};
Entry.findBy1a = (AreaName,Resolution,Year,Month,Day,result) => {
sql.query(`SELECT AreaName,AreaTypeCodeId,MapCodeId,ResolutionCodeId,Year,Month,Day FROM ActualTotalLoad WHERE AreaName = ${AreaName} AND ResolutionCodeId = ${Resolution} AND Year = ${Year} AND Month = ${Month} AND Day = ${Day}` , (err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
if (res.length) {
console.log("found entry: ", res[0]);
result(null, res[0]);
return;
}
// not found Customer with the id
result({ kind: "not_found" }, null);
});
};
module.exports=Entry;
and the file: entry.controller.js
const Entry = require("../models/ActualTotalLoad.model.js");
// Find a single Customer with a customerId
exports.findOne = (req, res) => {
Entry.findByPk(req.params.Id, (err, data) => {
if (err) {
if (err.kind === "not_found") {
res.status(404).send({
message: `Not found Entry with id ${req.params.Id}.`
});
} else {
res.status(500).send({
message: "Error retrieving Entry with id " + req.params.Id
});
}
} else res.send(data);
});
};
exports.find1a = (req, res) => {
Entry.findBy1a(req.params.AreaName,req.params.Resolution,req.params.Year,req.params.Month,req.params.Day, (err, data) => {
if (err) {
if (err.kind === "not_found") {
res.status(404).send({
message: `Not found Entry with AreaName ${req.params.AreaName}.`
});
} else {
res.status(500).send({
message: "Error retrieving Entry with AreaName " + req.params.AreaName
});
}
} else res.send(data);
});
};
I am trying to perform this get http://localhost:8765/energy/api/ActualTotalLoad/DE-AT-LU/7/2018/1/4
But I get the error "message": "Error retrieving Entry with AreaName DE-AT-LU"
What am I doing wrong?
You should change your WHERE statement like this
SELECT ... WHERE AreaName = "${AreaName}" AND ResolutionCodeId = ${Resolution} AND Year = ${Year} AND Month = ${Month} AND Day = ${Day}
Note: notice the quotes ( "${AreaName}" )
AreaName in your DB schema is problably typed as string (or text), so you need to quote you search criteria as string (surrounding it by " or ')
I assume that ResolutionCodeId, Year Month, and Day are number types, so it's ok to not quote them.

How do I redirect user to 'home' page after validating his login data with database?

After checking login data (user name and password) I would like to redirect the valid user to home page.
Here is app. post:
app.post('/', function ( req , res) {
req.checkBody('home_user_name', 'User Name is required').notEmpty();
req.checkBody('home_password', 'Password is required').notEmpty();
pool.getConnection(function (error, tempCont) {
if (!!error) {
tempCont.release();
console.log('Error');
}
else {
console.log('Connected!');
function get_role(callback) {
console.log("look here >> " + req.body.home_user_name);
here is query:
tempCont.query('SELECT * from `users` where `user_name` = ? ', [req.body.home_user_name] , function (error, results) {
if (error) callback(null);
callback(results[0].password);
});
}
here is the question how to redirect the valid user to home page? note that it is a function inside function inside app.post:
get_role(function (data) {
if (data == req.body.home_password){
console.log("User Name is " + req.body.home_user_name + " and Password is " + data);
}
else {
console.log("passwords are not identical ");
}
}
);
here is errors validation:
var errors = req.validationErrors();
if (errors) {
res.render('app', { errors: errors });
} else {
console.log("Validation: " + req.body.home_user_name);
}
}
})
})
This is the solution:
res.redirect ('home');

Check user already available in db using sails.js

I am registering a new user by checking it is already available. But for every user it shows "user is already available"
signup: function (req, res) {
var username = req.param("username");
var password = req.param("password");
var status = false;
console.log("user : " + username + " : " + password);
Signup.find({username: username}).exec(function(err, usr){
if (err) {
var response = {status:status, error:"db error"};
res.send(500, response);
} else {
if (usr) {
status = true;
res.send(400, {error: "Username already Taken"});
}
else {
signup.create({username: username, password: password}).exec(function(error, user) {
if (error) {
res.send(500, {error: "DB Error"});
} else {
req.session.user = user;
res.send(user);
}
});
}}
});
},
I assume that in your model it clear that the username must be unique. So use findOne() function. It's return only one record( object ).
signup: function(req, res) {
var username = req.param("username");
var password = req.param("password");
var status = false;
Signup.findOne({ username: username })
.exec(function(err, usr) {
if (err) {
var response = { status: status, error: "db error" };
return res.send(500, response);
}
if (usr) {
//status = true; --> in this case you don't use 'status' so this assignment is unnecessary
return res.send(400, { error: "Username already Taken" });
} else {
Signup.create({ username: username, password: password })
.exec(function(err, user) {
if (err) {
res.send(500, { error: "DB Error" });
} else {
req.session.user = user;
res.send(user.username);
}
});
}
});
}
Signup.find({username: username}).exec(function(err, usr){
// usr is an array
});
the result of find is a list with objects matching your query. The list either has items or no items. In both cases
if (usr) {}
will be true, because you basically just check whether usr is defined which it always is. So change it to
if (usr.length === 0) {
// already exists
}
Or you change find to findOne.