undefined value Array inside Json - json

This is my code to get logged-in user data
router.post('/login', function (req, res, next) {
/* look at the 2nd parameter to the below call */
let errors = [];
if (!req.body.password || !req.body.email) {
req.flash('error_msg', 'please enter email and password');
res.redirect('/login')
}
passport.authenticate('local', function (err, user, info) {
if (err) { return next(err); }
if (!user) {
req.flash('error_msg', 'your email or password is not correct');
res.redirect('/login')
}
req.logIn(user, function (err) {
if (err) { return next(err); }
var type = user.type;
var dt = dateTime.create();
var formatted = dt.format('Y-m-d H:M:S');
connection.query("update table set last_login = '"+formatted+"' where id = '"+user.id+"'", function (err, rows) {
if(type == '0'){
res.redirect('/login');
}
else if(type == '1'){
console.log(user);
res.cookie('user', user).redirect('/dashboard');
}
else{
res.redirect('/customers');
}
});
});
})(req, res, next);
});
i'm try to console some data in node js and in which data is getting something like this.
{
email: 'test#gmail.com',
username: 'tester',
id: 9,
password: '7ZaOhA0Q0tMTqHC8ExpOLDEdetCb3zKzQYFHIh9RpuI=',
type: '1',
token:
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7ImVtYWlsIjoic2l2YWFAZ21haWwuY29tIiwidXNlcm5hbWUiOiJzaXZhYSIsImlkIjo5LCJwYXNzd29yZCI6IjdaYU9oQTBRMHRNVHFIQzhFeHBPTERFZGV0Q2Izekt6UVlGSEloOVJwdUk9IiwidHlwZSI6IjEiLCJ0b2tlbiI6IiJ9LCJpYXQiOjE1MzQ1Njg3NjEsImV4cCI6MTUzNDU3MTc2MX0._3AspvfLO2K46OVilqsLtfiRcZTG2ZYvGJWe6jaQ3ZA',
customers: undefined
}
now i want to display customers field data which is contain data like this abc,xyz,pqr and it seems undefined.
so how can i get data instead of undefined and please tell me the reason behind undefined value if you know
Thank you in advance your help make my day brighter.

Related

Retrieve information upon registration

How can i do this, When a user registers , I would like the endpoint to still go ahead and get back the information which is saved inside the database.For some reason, it does not work as expected
How do i go about this :
My code is looking thus :
app.post("/api/sign-up", async function (req, res) {
dbConn.query(
`select * from accounts where email = ${dbConn.escape(req.body.email)}`,
async function (err, result, fields) {
if (result.length === 0) {
var email = req.body.email;
var phone = req.body.phone;
var password = req.body.password;
var fullname = "NULL";
const hashPass = await bcrypt.hash(password, 12);
dbConn.query(
`insert into accounts(email, phone, password, fullname) values (?,?,?,?)`,
[email, phone, hashPass, fullname],
function (error, results, fields) {
if (error) throw error;
return res.send({
error: false,
data: results[0],
message: "User created Successfully",
});
}
);
} else {
return res.send({
error: true,
message: "User exists",
});
}
}
);
});
Checked thru the internet, i could not find the information needed.
I managed to fix it.
Code looks like this now , and it shows the data inside POST man
app.post("/api/sign-up", async function (req, res) {
dbConn.query(
`select * from accounts where email = ${dbConn.escape(req.body.email)}`,
async function (err, result, fields) {
if (result.length === 0) {
var email = req.body.email;
var phone = req.body.phone;
var password = req.body.password;
var fullname = "NULL";
const hashPass = await bcrypt.hash(password, 12);
dbConn.query(
`insert into accounts(email, phone, password, fullname) values (?,?,?,?)`,
[email, phone, hashPass, fullname],
function (error, results, fields) {
if (error) throw error;
return res.send({
error: false,
email:email,phone:phone,
message: "User created Successfully",
});
//return res.status(201).json({message: 'User created Successfully', "email":email,"phone":phone});
}
);
} else {
return res.send({
error: true,
message: "User exists",
});
}
}
);
});
Thanks to everyone who decided to take a Look :)

User always getting failure redirected using passport?

No matter what I change the user login will keep redirecting to failure instead of success. I don't know if I'm missing something or if I did something wrong. I tried to read the documentation for passport but, I found it pretty confusing. Here is my github link if you need to see the rest of the code. The node files are in app.js and passport-config.js.The sign up part of the website is working. https://github.com/gego144/to-do-list-website/tree/main
const customFields = {
usernameField: 'email',
passwordField: 'password'
}
const verifyCallback = (username, password, done) => {
user_exists = userName_Checker(username), function (err, user) {
if (err) { return done(err); }
if (userName_Checker(username) == false) {
console.log('wrong user');
return done(null, false, { message: 'Incorrect username.' });
}
if (password_finder(username, password)) {
console.log('wrong pass');
return done(null, false, { message: 'Incorrect password.' });
}
console.log('wtf');
return done(null, user);
};
;
}
const strategy = new LocalStrategy(customFields, verifyCallback);
passport.use(strategy);
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
// function that checks to see if the users email is in the database
function userName_Checker(email_name){
var sql = "select * from info where email = ?";
var user_email = [[email_name]];
db.query(sql, [user_email],function (err,result){
if (err) throw err;
var not_unique = result.length;
if(not_unique == 0){
return false;
}
else{
return true;
}
}
)}
// function that checks to see if the password in the database matches with the email
function password_finder(email_name, pass){
var sql = "SELECT password FROM info WHERE email = ?";
var user_email = [[email_name]];
db.query(sql, [user_email],function (err,result){
if (err) throw err;
bcrypt.compare(result, pass, function(err, res){
if(err){ throw err};
if(res){
return true;
}
else{
return false;
}
})
}
)}
My post method in my other file.
app.post('/login', passport.authenticate('local', {
successRedirect: '/',
failureRedirect:'/index.html',
failureFlash: true
}))
Edit 1.
I just want to mention that the console.logs you see in verify Callback all don't log anything for some reason too.
The problem might be in the serialization logic.
In passport.serializeUser, you are passing in the whole user object, but when deserializing you are passing the id
Though I am not using SQL, the logic should be similar.
So the code should be something like this:
// Session
// Pass in user id => keep the session data small
passport.serializeUser((id, done) => {
done(null, id);
});
// Deserialize when needed by querying the DB for full user details
passport.deserializeUser(async (id, done) => {
try {
const user = await User_DB.findById(id);
done(null, user);
} catch (err) {
console.error(`Error Deserializing User: ${id}: ${err}`);
}
});
// Export the passport module
module.exports = (passport) => {
passport.use(new LocalStrategy({ usernameField: 'email', }, async (email, password, done) => {
try {
// Lookup the user
const userData = await User_DB.findOne({ email: email, }, {
password: 1, }); // Return the password hash only instead of the whole user object
// If the user does not exist
if (!userData) {
return done(null, false);
}
// Hash the password and compare it to the hash in the database
const passMatch = await bcrypt.compare(password, userData.password);
// If the password hash does not match
if (!passMatch) {
return done(null, false);
}
// Otherwise return the user id
return done(null, userData.id);
} catch (err) {
passLog.error(`Login Error: ${err}`);
}
}));
};
These options for passport seems to malfunction a lot or exhibit weird behaviors, so I suggest you handle the redirection logic like in my controller.
{ successRedirect: '/good',
failureRedirect: '/bad' }
Login controller logic:
(I am omitting the code here for session storage and made some modifications, but this code should work for what you need)
const login = (req, res, next) => {
//Using passport-local
passport.authenticate('local', async (err, user) => {
//If user object does not exist => login failed
if (!user) { return res.redirect('/unauthorized'); }
//If all good, log the dude in
req.logIn(user, (err) => {
if (err) { return res.status(401).json({ msg: 'Login Error', }); }
// Send response to the frontend
return res.redirect('/good');
});
});
})(req, res, next);
};
The actual route:
// Import the controller
const {login} = require('../controllers/auth');
// Use it in the route
router.post('/auth/login', login);

if -else condition is not working in node js

What I am trying to implement is that after logged in ,system will check user's role and redirect the user accordingly.
1- Admin
2- User
role field is integer type. below is my code
router.post('/signin', function (req, res, next) {
session_store = req.session;
req.assert('Emailid', 'Please fill register Email Address').notEmpty();
req.assert('Emailid', 'Email not valid').isEmail();
req.assert('password', 'Please fill the Password').notEmpty();
var errors = req.validationErrors();
if (!errors) {
Emailid = req.sanitize('Emailid').escape().trim();
password = req.sanitize('password').escape().trim();
var query = 'select * from userdetails where Emailid=? and password=?';
var sql='select role from userdetails where Emailid=?'
db.query(query, [Emailid, password], function (err, rows) {
if (err) {
var errornya = ("Error Selecting : %s ", err.code);
console.log(err.code);
req.flash('msg_error', errornya);
res.redirect('/login-Form');
} else {
if (rows.length <= 0) {
req.flash('msg_error', "Wrong email address or password. Try again.");
res.redirect('/login-Form');
}
else {
session_store.is_login = true;
session_store.user = Emailid;
db.query(sql, Emailid, function (err, result) {
if (err) throw err
else {
if (result == 1) { // facing issue here. It is directly going to else block though the user role is 1 in the mysql table
console.log(result)
res.redirect('/Dashboard');
}
else {
res.redirect('/Audit-Record');
}
}
});
}
}
});
}
else {
res.redirect('/login-Form');
}
});
I guess I am making some mistake while comparing the result value. Can anyone of you please check and let me know where I am going wrong.
Thanks in advance!
The issue got resolved. Actually I was comparing in wrong way. we need to write it like this
else {
session_store.is_login = true;
session_store.user = Emailid;
db.query(sql, Emailid, function (err, result) {
if (err) throw err
else {
**if (result[0].role == 1)** {
console.log(result)
res.redirect('/Dashboard');
}
else {
res.redirect('/Audit-Record');
}
}
});

Express-validator check if email existed with MySQL

Im using express-validator to check if the req.body entered is valid and to check if there is duplicate email in the MySQL database
Here is my code:
router.post(
"/signup",
[
body("uemail","email is not valid")
.isEmail()
.normalizeEmail()
.custom(async (email, {req} )=>{
const queryString = "SELECT uid FROM EarlyUsers WHERE `uemail` = ?";
return await connection.query(queryString, [email], (err, rows, fields) => {
if (err) {
console.log(err)
}else {
if (rows.length != 0) {
return false
} else {
return true
}
}
});
})
,
body("uname").isLength({ min: 5 })
],
authControllers.signUp
);
I dont know why this custom validator does not work.
I've tried to throw new Error instead of return false, but it just crash the whole thing . I really need help with this
For it to work correctly instead of returning false you reject the Promise.
if (rows.length != 0) {
return Promise.reject("user already exists.");
}
I have achieved this way it might be helpful for others, I'm using sequelize :)
const User = require("../../models/User");
body('email', 'Invalid email').exists().isEmail().trim().escape().custom(userEmail=> {
return new Promise((resolve, reject) => {
User.findOne({ where: { email: userEmail } })
.then(emailExist => {
if(emailExist !== null){
reject(new Error('Email already exists.'))
}else{
resolve(true)
}
})
})
}),
I found this solution to check that the email is not duplicate:
router.post('/register',
body('email').isEmail().normalizeEmail().withMessage('The email format is not correct.').custom((email) => {
const queryString = `SELECT * FROM users WHERE user_email = "${email}"`;
return getFinalEmail(queryString).then(user => {
console.log(user);
if (user) {
return Promise.reject('E-mail already in use');
}
});
}),
// -- other validations
// .....
(req, res) => {
/* your code for this route */
}); // end of router('/register')
function getFinalEmail(param) {
return new Promise(function(resolve, reject) {
getEmailData(param, function(result) {
console.log(result);
resolve(result);
});
});
}
function getEmailData(query, callback) {
database.query(query, function(error, data){
if(data.length > 0) {
return callback(true);
} else {
return callback(false);
}
});
}
In the above code users is the name of my table and user_email is the column that email data of users are stored.

Node.js - MySQL API, multi GET functions

I'm new in making API. I use Node.js and MySQL.
The fact is I have two GET function to get all users and one to get user by ID.
Both function are working when they are alone implemented. If both of them are implemented the function to get all user try to enter in the function to get user by ID so the API crash.
So here is my model users.js
var connection = require("../connection");
function Users()
{
//GET ALL USERS
this.get = function(res)
{
console.log('Request without id');
connection.acquire(function(err, con)
{
con.query('SELECT * FROM users', function(err, result)
{
con.release();
if (err)
res.send({status: 1, message: 'Failed to get users'})
else
res.send(result);
});
});
}
//GET USER BY ID
this.get = function(id, res)
{
console.log('Request with ID');
connection.acquire(function(err, con)
{
if (id != null)
{
con.query('SELECT * FROM users WHERE id = ?', id, function(err, result)
{
con.release();
if (err)
res.send({status: 1, message: 'Failed to find user: ' + id});
else if (result == "")
res.send({status: 1, message: 'Failed to find user: ' + id});
else
res.send(result);
});
}
});
}
And here is the routes.js
var users = require('./models/users');
module.exports = {
configure: function(app) {
app.get('/users/', function(req, res) {
users.get(res);
});
app.get('/users/:id/', function(req, res) {
users.get(req.params.id, res);
});
Do you have any idea why ?
Thanks for help :)
You can't have two functions with the same name in the same scope.
You have to rename your functions
/**
* Get all users
*/
this.get = function(res) {...}
/**
* Get user by id
*/
this.getById = function(id, res) {...}
Or you can have one function and check if an id is provided
this.get = function(id, res) {
if ( Number.isInteger(id) ) {
// return the user
} else {
res = id;
// return all users
}
}