how can i connect userid to the loggedin user - mysql

router.get('/profilePage/:userid', function(req, res) {
var userid = req.session.user
console.log(userid)
if (!userid) {
//No user id provided
} else {
pool.query('SELECT * from users where id = ?',
[userid],
(error, results, feilds)=> {
if (error) {
console.log("error ocurred while getting user details of " + userid, error);
res.send({
"code": 400,
"failed": "error ocurred"
});
} else {
if (results.length > 0) {
const profile = results[0]
//You can then access the user id with
console.log(profile.fullname)
res.render("profilePage",{profile});
} else {
console.log('unable to retrieve a profile')
}
}
});
}
});
how can I make the userid = logged-in user? I tried many ways such as sessions (var userid = req.session.user) but all did not work what is the correct way to make the userid = to logged-in user id?

Related

How do I make this owner authentication work?

I have a problem with this code. I would appreciate it very much if someone could help me with this. If you have any missing information feel free to ask. Note: Iam using mysql2.
router.get('/restaurants/:name/:location/dashboard', userContoller.isLoggedInAdmin, async (req, res) => {
const restaurantName = req.params.name;
const restaurantLocation = req.params.location;
console.log(`restaurantName: ${restaurantName}`);
console.log(`restaurantLocation: ${restaurantLocation}`);
try {
// Query the database to retrieve the owner's information and the information for the specific restaurant
const [ownerRows] = await db.promise().query(
'SELECT * FROM owner WHERE id = (SELECT owner_id FROM restaurant WHERE name = ? AND location = ?)',
[restaurantName, restaurantLocation]
);
const [restaurantRows] = await db.promise().query(
'SELECT * FROM restaurant WHERE name = ? AND location = ?',
[restaurantName, restaurantLocation]
);
console.log(`ownerRows: ${JSON.stringify(ownerRows)}`);
console.log(`restaurantRows: ${JSON.stringify(restaurantRows)}`);
const owner = ownerRows[0];
const restaurant = restaurantRows[0];
console.log(`owner: ${JSON.stringify(owner)}`);
console.log(`restaurant: ${JSON.stringify(restaurant)}`);
// Check if the owner is logged in and has permission to access the dashboard
if (req.owner && req.owner.id === restaurant.owner_id) {
// Render the dashboard template and pass the owner's information and information for the specific restaurant to it
res.render('role/admin/index', { owner: owner, restaurant: restaurant });
} else {
console.log('Owner not granted access to dashboard');
// Redirect the owner to the login page
res.render('errors/no permission');
}
} catch (error) {
console.error(error);
res.sendStatus(500);
}
});
So I have this route and I want it to work. I have a user, owner and a restaurant table. In the owner table is the owner id and the user id as a foreign key referencing to the primary key in the user table. In the restaurant table there is a column called owner_id which is a foreign key referencing to the primary key in the owner table. What this basically means is that the user is the owner/admin of one or more restaurants. The problem is that somehow the owner does not have access to the restaurant even though he is connected with it.
Here is the middleware:
exports.isLoggedInAdmin = async (req, res, next) => {
console.log('isLoggedInAdmin middleware called');
if (req.cookies.one) {
try {
const decode = await jwt.verify(req.cookies.one, process.env.JWT_SECRET);
const [user] = await db.promise().query("SELECT * FROM user WHERE id = ?", [decode.id]);
if (!user) {
return res.status(401).json({ message: "Unauthorized" });
}
const [owner] = await db.promise().query("SELECT * FROM owner WHERE user_id = ?", [decode.id]);
if (!owner) {
return res.status(401).json({ message: "Unauthorized" });
}
if (user.id !== owner.user_id) {
return res.status(401).json({ message: "Unauthorized" });
}
console.log('Owner found:', owner);
req.owner = {
id: owner.id,
user_id: owner.user_id,
};
next();
} catch (error) {
console.error(error);
return res.status(401).json({ message: "Unauthorized" });
}
} else {
console.log('No owner found');
next();
}
};
Here is the login system (focus on the cookie for the owner):
exports.login = async (req, res) => {
try {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).render("login", {
msg: "Please Enter Your Email and Password",
msg_type: "error",
});
}
db.query(
"select * from user where email=?",
[email],
async (error, result) => {
console.log(result);
if (result.length <= 0) {
return res.status(401).render("login", {
msg: "Please Enter Your Email and Password",
msg_type: "error",
});
} else {
if (!(await bcrypt.compare(password, result[0].password))) {
return res.status(401).render("login", {
msg: "Please Enter Your Email and Password",
msg_type: "error",
});
} else {
const id = result[0].id;
const token = jwt.sign({ id: 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,
};
// Check if the user is in the owner table
db.query("SELECT * FROM owner WHERE user_id=?", [id], (error, result) => {
if (result.length > 0) {
// Set the cookie for owner
res.cookie("one", token, cookieOptions);
res.status(200).redirect("/restaurants/:name/:location/dashboard");
} else {
// Check if the user is in the manager table
db.query("SELECT * FROM manager WHERE user_id=?", [id], (error, result) => {
if (result.length > 0) {
// Set the cookie for manager
res.cookie("two", token, cookieOptions);
res.status(200).redirect("/manager/dashboard");
} else {
// Check if the user is in the cook table
db.query("SELECT * FROM cook WHERE user_id=?", [id], (error, result) => {
if (result.length > 0) {
// Set the cookie for cook
res.cookie("three", token, cookieOptions);
res.status(200).redirect("/cook/dashboard");
} else {
// Check if the user is in the waiter table
db.query("SELECT * FROM waiter WHERE user_id=?", [id], (error, result) => {
if (result.length > 0) {
// Set the cookie for waiter
res.cookie("four", token, cookieOptions);
res.status(200).redirect("/waiter/dashboard");
}
});
}
});
}
});
}
});
}
}
}
);
} catch (error) {
console.log(error);
}
};
Here is the log:
isLoggedInAdmin middleware called
Owner found: [ { id: 7, user_id: 42 } ]
restaurantName: BLOCKHOUSE
restaurantLocation: Pakistan
ownerRows: [{"id":7,"user_id":42}]
restaurantRows: [{"id":40,"name":"BLOCKHOUSE","location":"Pakistan","email":"2021erik.mettner#gmail.com","phonenumber":"012386763618","owner_id":7}]
owner: {"id":7,"user_id":42}
restaurant: {"id":40,"name":"BLOCKHOUSE","location":"Pakistan","email":"2021erik.mettner#gmail.com","phonenumber":"012386763618","owner_id":7}
Owner not granted access to dashboard
I know where the problem is. It is here:
// Check if the owner is logged in and has permission to access the dashboard
if (req.owner && req.owner.id === restaurant.owner_id)
My Problem is that I dont know how to fix it. I want that the owner can access his restaurants. Only he, not any other owner.

"Mysql problem "profile data do not show in my html page

I am trying to view a data from Mysql and pass it to the profile page where i can see the info of the user but i tried many time and different ways but couldnt find a way and also there is no errors I used {{#each}}{{this.fullname}}{{/each}} i tired if also but the data does not display would anyone help me to pls to solve it or if there is another way to display my data
i am using node js, express and hbs engine
router.get('/profilePage/:userid', function(req, res) {
var userid = req.params.userid;
pool.query('SELECT * from users where id = ?', userid, function(error, results, feilds) {
if (error) {
console.log("error ocurred while getting user details of " + userid, error);
res.send({
"code": 400,
"failed": "error ocurred"
});
} else {
res.render("profilePage",{user:results});
}
});
});
Try this:
router.get('/profilePage/:userid', function(req, res) {
var userid = req.params.userid;
if (!userid) {
//No user id provided
} else {
pool.query('SELECT * from users where id = ?',
[userid],
(error, results, feilds)=> {
if (error) {
console.log("error ocurred while getting user details of " + userid, error);
res.send({
"code": 400,
"failed": "error ocurred"
});
} else {
if (results.length > 0) {
const profile = results[0]
//You can then access the user id with
console.log(profile.id)
res.render("profilePage",{user:profile});
} else {
console.log('unable to retrieve a profile')
}
}
});
}
});

How to get username of a person who is logged in,from database mysql in node.js

I have made a login system where i am logging in using mobile number and password.Before my code was showing welcome back 03**** ** because i had used request.session.number. I have changed the code so that i can get first name from the database whether employer or helper login.But it is not working.It is showing welcome back, undefined. I am unable to get the name from database.Can anyone tell me how to get it or where i am wrong. I will be thankful if anyone can help me in this regard.
app.post('/auth', function(request, response) {
var number = request.body.number;
var password = request.body.pwd;
if (number && password) {
var sql = `SELECT fyp_helpers.Mobile_number AS number,fyp_helpers.Password AS Password FROM fyp_helpers WHERE Mobile_number = ? UNION SELECT
fyp_employers.Employer_Contact AS number , fyp_employers.Employer_Password AS Employer_Password FROM fyp_employers
WHERE Employer_Contact = ?`;
connection.query(sql, [number, number], function (error, results, fields) {
if (results.length > 0) {
var hashedPassword = results[0].Password;
bcrypt.compare(password, hashedPassword, function (cryptErr, cryptResult) {
if (cryptResult) {
request.session.loggedin = true;
request.session.number = number;
var name= connection.query(`select fyp_helpers.First_Name As name FROM fyp_helpers UNION select fyp_employers.Employer_Fname As name FROM fyp_employers`,[name,name],function(error, results, fields)
{
if(!err)
console.log(name);
else
console.log(error);
})
response.redirect('/home');
} else {
response.send('Incorrect Password!');
console.log(cryptErr);
}
response.end();
});
} else {
response.send('User not registered');
}
});
}
else {
response.send('Please enter Username and Password!');
response.end();
}
});
app.get('/home', function(request, response) {
if (request.session.loggedin) {
response.send('Welcome back, ' + request.session.name + '!');
} else {
response.send('Please login to view this page!');
}
response.end();
});
app.listen(3000);
Everything is working fine but the only problem is it is not getting name.
Edit
var name= connection.query(`select fyp_helpers.First_Name As name FROM fyp_helpers UNION select fyp_employers.Employer_Fname As name FROM fyp_employers`,[name,name],function(error, results, fields)
{
if(!error) {
request.session.name = name;
console.log(name);
}
else
console.log(error);
})
I have declared name to session but it is still not working.Do i place it on wrong position or my query is not right to select the name?
You forgot to add name in request.session.name. Variable name is fetched but not used.

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.

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
}
}