I am developing an apt management app.
Basically, if a user is a resident, they get to see their apt fee payment data.
If the user is from apt management, they select one of the 5 db update options from the apt mgmt menu page by clicking one of the submit buttons numbered from 1 to 5.
I am trying to make my code session-based so I am attaching my own variables to req.session
object as req.session.loggedin
, req.session.userid
and req.session.userpwd
.
I authenticate username
and userpwd
inputs from login page in the first post request to '/server'
and if they match in db then I set req.session.loggedin
to true
.
I was hoping that I would be able to use the req.session.loggedin
and req.session.username
variables in the second request to '/mgtmenupg'
and other requests but unfortunately it doesn’t work because I get undefined error.
At the moment I can’t progress any further. What do I have to do to able able to access req.session.loggedin
and req.session.username
variables in other requests?
Any help will be appreciated.
Attached is my minimal reproducable examples of js code.
var express = require('express'); // Import Express package
var session = require('client-sessions');
//var session = require('express-session');
var bodyParser = require('body-parser'); // Import body-parser module to parse incoming requests
var cookieParser = require('cookie-parser');
var path = require('path'); //import path module.
var app = express(); // Create an Express app variable so that we can use Express in anywhere.
var router = express.Router();
var cors = require('cors'); //import cors from "cors". CORS allows frontend and backend to share data because they are on different servers.
var port = 3000; //Set port to 3000. This is where our backend server will be.
var mysql = require('mysql');
var alert = require('alert');
const { config } = require('process');
//var { response } = require('express');
var con = mysql.createConnection({ // Create connection object.
host: 'localhost',
user: 'root',
password: 'hsAdmin',
database: 'havuzsDB'
});
//const { request } = require('http');
// Below, we use the imported modules in our Express app.
app.use(express.json() ); // use Express module body-parser to parse JSON-encoded request bodies
app.use(express.urlencoded({extended: true})); // use Express module body-parser to parse URL-encoded request bodies
app.use(cookieParser());
// Use the sessions package to determine if user is logged-in.
app.use(session({
cookieName: 'session',
secret: 'top99secret',
duration: 30 * 60 * 1000,
activeDuration: 5 * 60 * 1000,
httpOnly: true,
secure: true,
ephemeral: true
//resave: true,
//saveUninitialized: true
}));
app.use(cors());
// Set up view engine.
app.engine('html',require('ejs').renderFile);
app.set('view engine', 'ejs');
//app.set('views', path.join(_dirname, 'views'));
// Start your server on a specified port and listen for http request on that port.
// app.listen() is the function that starts a port and host, in our case the localhost for the connections
// to listen to incoming requests from a client.
app.listen(port, () => {
alert("server is running at http://127.0.0.1:", port); //Show server url at console. Use this url in <script> tag of your html code.
});
/* You can use this to check if your server is working.
app.get('/', (req, res)=>{
res.send("Welcome to my server");
}); */
// Connect to havuzsDB database.
con.connect(function(err) {
if (err) {
throw err;
alert("DB Connection failed");
}
else
alert("DB Connected!");
});
// Route to send the local image file to be used as app homepage background, to the client.
app.get('/havuzlusite-img.jpg', function(req, res) {
res.sendFile("D:/Behrans-files/Web-projects/havuzlusite/havuzlusite-img.jpg");
});
// Route to send home page file to the client.
app.get('/', function(req, res) {
res.sendFile("D:/Behrans-files/Web-projects/havuzlusite/homepg.html");
});
// Route to send the login form to the client.
app.get('/loginpg', function(req, res) { //Send login page file to the client.
res.sendFile("D:/Behrans-files/Web-projects/havuzlusite/loginpg.html");
});
//Route to receive and authenticate user login data.
app.post('/server', (req, res) => {
req.session.username = req.body.isim; // save username input in a local variable.
req.session.userpwd = req.body.sifre; // save user pwd in a local variable.
if (req.session.username && req.session.userpwd) { //Check if user has entered name and password in the login form.
con.query('SELECT * FROM havuzs_sakinleri WHERE isim = ? AND sifre = ?', [req.session.username, req.session.userpwd], function(err, rows) {
if (rows.length > 0) {
req.session.loggedin = true;
req.session.rows = rows;
} else {
return alert('İsim ve şifre veri tabanında bulunamadı. Lütfen geçerli bir isim/şifre girin!');
//return res.render('loginpg');
}
res.end();
})
} else {
return res.send('Lütfen isim ve şifre giriniz!');
res.end();
}
//console.log('loggedin:', req.session.loggedin, 'username: ', username);
//If user is a resident, display resident data.
if (req.session.loggedin && req.session.username !== 'Yonetim') {
if (req.session.rows) { // If user name/pwd match db,
var rows = req.session.rows;
return res.render('userdatapg', {rows}); // Display resident data.
res.end;
}
};
//If user is an authorized building management team member, display management menu.
if (req.session.loggedin && req.session.username == 'Yonetim') {
return res.render('mgtmenupg'); //Display db update menu page.
res.end();
}
});
// Determine which button is clicked.
app.post('/mgtmenupg/:btnno', (req, res) => {
// Route to handle apt fee payment - If button#1 is clicked.
if (req.params.btnno == 1) {
res.render('userpmtpg'); //Display user apt fee payment page.
app.post('/userpmtpg', (req, res) => { //Post request to access payment month and payment amount inputs from user.
var username = req.body.username;
var pmtmnth = req.body.pmt_mnth;
var pmtamt = req.body.pmt_amt;
queryusername(username, function(response) { //Pass username and call function to see if the user is in db.
if (response == 'Found') { //If response has no error message, call function to update user payment data in db.
updateUsrPmtData(username, pmtmnth, pmtamt, function(response) { //Call function to update user apt fee payment data in db.
return alert(response); //Display db update status message from called function.
});
} else if (response == 'Not found')
res.send('İsim veri tabanında bulunamadı. Ana sayfaya dönmek için lütfen Ana sayfa butonuna tıklayınız!'); //If response has error message, display error message.
else
res.send('Site sakini ismi veri tabanında aranırken sorun oluştu.');
})
res.render('mgtmenupg');
res.end();
})
}
// Route to handle deletion of existing resident user - If button#2 is clicked.
if (req.params.btnno == 2) {
res.render('deluserpg');
app.post('/deluserpg', (req,res) => {
var username = req.body.username;
queryusername(username, function(response) { //Pass username and call function to see if the user is in db.
if (response == 'Found') { //If response has no error message, it means user is in db, call function to delete it.
deleteUser(username, function(response) { // Pass username input data as parameter to call deleteuser function.
return alert(response); //Display db delete status message from called function.
res.render('mgtmenupg');
})
} else if (response == 'Not found') {
return alert('İsim veri tabanında bulunamadı. Lütfen sistemde mevcut bir isim girin.'); //If response has error message, display error message.
return res.render('deluserpg');
} else
return res.send('Site sakini ismi veri tabanında aranırken sorun oluştu.');
})
res.end();
})
};