IF Statement is setting a session attribute in NODE js and express - javascript

I am trying to do a log in page for a Uni project and am having difficulty as when trying to redirect user based on an access level the if statement is setting the Access Role before the function and so all traffic when first logged in gets redirected to the Admin page, refreshing the page makes the code work properly as that it when the code that gets the details from the database has finished running... Any help would be great thanks!
LogInController
const session = require('express-session');
var Login = require('../models/Login');
exports.checksLogin = (req, res) => {
// Implement this method using the pupil model
console.log(req.originalUrl + "POST Received with query: ", req.body)
const {Email, Pswd} = req.body
Login.checkLogin(Email, Pswd)
if(session.AccessRole='Admin'){
res.redirect('/admin')
}
else{
}
}
Login.js (Models)
exports.checkLogin = (Email, Pswd) => {
var database = require('../dbConfig');
database.then(con => {
con.query("SELECT * FROM Pupils WHERE Email = '" + Email + "'AND Pswd= '" + Pswd + "'").then(([rows]) => {
//console.log(rows)
if(rows.length>0){
session.LoggedIn=true;
session.FirstName=rows[0].FirstName
session.LastName=rows[0].LastName
session.Email=rows[0].Email
session.CourseCode=rows[0].CourseCode
session.Pswd=rows[0].Pswd
session.AccessRole='Student'
console.log(session.Loggedin+ '1')
}
else {
con.query("SELECT * FROM Staff WHERE Email = '" + Email + "'AND Pswd= '" + Pswd + "'").then(([rows]) => {
console.log(rows)
session.LoggedIn=true;
session.staffID=rows[0].staffID
session.FirstName=rows[0].FirstName
session.LastName=rows[0].LastName
session.Email=rows[0].Email
session.Role=rows[0].Role
session.Pswd=rows[0].Pswd
if(session.Role='Admin'){
console.log(`Admin`)
session.AccessRole='Admin'
}else{
session.AccessRole='Staff'
}
})
}
})
})
}
index.js
const express = require('express');
const app = express();
const path = require('path');
const exphbs = require('express-handlebars');
var session = require('express-session');
var bodyParser = require('body-parser');
// Middlewares
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars')
app.use(express.urlencoded({extended: true}))
// Client routes
app.get('/', (req, res) => res.render('index'));
app.use('/admin', require('./routes/Admin'));
app.use('/login', require('./routes/Login'));
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true
}));
app.use(bodyParser.urlencoded({extended : true}));
app.use(bodyParser.json());
const PORT= process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server Started on port ${PORT} `));
Login.js (Routes)
const express = require('express');
const router = express.Router();
var Login_controller = require('../controllers/LoginController');
// Use the login.handlebars template
router.get('/', (req, res) => res.render("login"));
// CRUD routes
router.post("/submit-login", Login_controller.checksLogin);
module.exports = router;
Admin.js
const express = require('express');
const session = require('express-session');
const router = express.Router();
var pupils_controller = require('../controllers/PupilsController');
var staff_controller = require('../controllers/StaffController')
// Use the login.handlebars template
router.get('/', (req, res) => {
console.log(session.LoggedIn)
if(session.AccessRole=='Admin'){
res.render("admin")
}
else{
console.log(`No Entry`)
res.redirect('/')
}
});
// CRUD routes
router.post('/create-pupil', pupils_controller.createPupil);
router.post('/delete-pupil', pupils_controller.deletePupil);
router.post('/create-staff', staff_controller.createStaff)
module.exports = router;
login.handlebars
<p> Log In </p>
<form method="POST" action="/login/submit-login">
<label for="Email">Email</label><br>
<input type="text" name="Email" /><br>
<label for="Pswd">Password</label><br>
<input type="text" name="Pswd" /><br>
<input type="submit" />
</form>
Using a MYSQL database, Node js and express
Thanks

Please note that the IF statement here must have double equal sign to compare, instead of that you are doing an assignation
const session = require('express-session');
var Login = require('../models/Login');
exports.checksLogin = async (req, res) => {
// Implement this method using the pupil model
console.log(req.originalUrl + "POST Received with query: ", req.body)
const {Email, Pswd} = req.body
await Login.checkLogin(Email, Pswd)
if(session.AccessRole == 'Admin') {
res.redirect('/admin')
} else {
}
}

Related

How to send data from a form to mongodb?

I am created a nodejs project the structure of py project is:
api.js is:
const express = require('express');
const router = express.Router();
const add = require('../model/myModel');
router.get('/',function(req,res){
res.render('myForm');
});
router.post('/add', (req, res) => {
console.log(req.body)
n = req.body.name,
phone = req.body.phone,
console.log(`name = ${n}`)
let obj = new Address({
name: n,
phone: phone,
});
// add this instance to the database.
obj.save()
.then((address) => {
res.send(address);
})
.catch((err) => {
console.log(error);
});
});
module.exports = router;
and my app.js is:
const express = require('express');
const mongoose = require('mongoose');
const route = require('./route/api');
//Initialize express app
const app = express();
// Connecting to DB
const dbPath = 'mongodb://localhost:27017/testdb';
const dbOptions = {useNewUrlParser: true};
mongoose.connect(dbPath, dbOptions).then(()=>{
console.log(`We are connected to our database ${dbPath}`);
}).catch((error)=>{
console.log(`We are note able to connect to our database: ${error}`);
});
app.use(express.static('public'));
app.use(express.json());
app.set("view engine", "ejs");
// initialize routes
app.use("/api", route);
//Initialize the sever
app.listen(3000, () => {
console.log('sever listening on port:3000');
});
and myForm.ejs is:
So, I want to be able to enter the data in myForm.ejs and save this data in the database. But when I fill the form and press submit my req.Body is an empty object. Where is my error?
Server side you need additional parser middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true })); //add this line
Client side your form should use /api/add, and not /add

Save DOM manipulated variable values to mongodb database on button click

I am having problems trying to connect variables from a browser based game to store in my mongoDB database.
Basically this is a condensed example as there will be numerous additional variables I will track and save, but in the example below I want the "round" to increment on button click. On the button click, I want the round number to be saved to a mongoDB database.
index.ejs file:
<h1>Round <span id="round">1</span></h1>
<form action="/" method="POST">
<button id="endbutton" type="submit">End Turn</button>
</form>
<script src="../scripts/game.js"></script>
game.js file:
let round = 1;
function endTurn(){
round += 1;
document.querySelector("#round").innerHTML = round;
}
let endTurnButton = document.querySelector("#endbutton");
endTurnButton.addEventListener("Click", endTurn);
module.exports = {round, endTurn};
app.js file:
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const path = require('path');
const gameJS = require('./scripts/game');
mongoose.connect("mongodb://localhost/variableTest", {useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false})
.then(() => {
console.log("Mongo connection open");
})
.catch(err => {
console.log("Mongo connection error occurred:")
console.log(err)
})
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.urlencoded({extended: true}));
app.set('views', path.join(__dirname, 'views'));
app.set("view engine", "ejs");
const { Schema } = mongoose;
const gameSchema = new Schema({
date: Date,
round: Number,
});
const Game = mongoose.model("Game", gameSchema);
//=================
//ROUTES
//=================
app.get("/", async(req, res) =>{
res.render("index");
});
app.post('/', async(req, res) => {
const game = new Game({
date: Date.now(),
round: gameJS.round,
});
await game.save();
})
//=================
//SERVER
//=================
app.listen(3000, () => {
console.log("VariableTest server has started.");
})

cannot POST / Nodejs

Please help me solve the error I've been trying hard to solve it for a long time.Because of this I'm not able to add data to my database as well.
Any help would be highly appreciated.
This is my index.js code
const express = require('express');
const app = express();
const routes = require('./routes');
const path = require('path');
const fileUpload = require('express-fileupload');
const bodyParser = require('body-parser');
const session = require('express-session');
const auth = require('./routes/auth');
const {
con,
sessionStore
} = require('./config/db');
const fs = require('fs');
require('dotenv').config({
path: path.join(__dirname, '.env')
});
const port = process.env.PORT || 3000;
// parse application/json
app.use(bodyParser.json())
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
extended: false
}));
//static files
app.use(express.static('public'))
app.use('/css' , express.static(__dirname + 'public/css'))
app.use('/imgs' , express.static(__dirname + 'public/imgs'))
var sess = {
secret: 'keyboard cat',
store: sessionStore,
cookie: {
httpOnly: false,
},
resave: false,
saveUninitialized: false
}
app.use(session(sess));
app.use(fileUpload());
//set views
app.set('view engine' , 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(require('connect-flash')());
app.use((req, res, next) => {
res.locals.messages = require('express-messages')(req, res);
next();
});
app.get('/', (req,res) =>{
res.render('index22')
})
app.get('/login', (req, res) => {
res.render('login');
});
let s;
const loginRequired = (req, res, next) => {
if (req.session.username) {
s = req.session;
next();
} else {
res.redirect('/auth/login');
}
}
app.get('/new', loginRequired, routes.new);//call for main index page
app.post('/new', loginRequired, routes.new);//call for signup post
app.get('/show/:username', loginRequired, routes.show);
app.use('/auth', auth);
app.listen(port, () => console.log(`listening on http://${process.env.HOST}:${port}`));
here's my routes.js code
const {
con,
sessionStore
} = require('./config/db');
exports.new = function(req, res){
message = '';
if(req.method == "POST"){
const post = req.body;
const username= post.username;
const title= post.title;
const state= post.state;
const category= post.category;
const description= post.description;
if (!req.files)
return res.status(400).send('No files were uploaded.');
const file = req.files.uploads;
const img_name=file.name;
if(file.mimetype == "images/jpeg" ||file.mimetype == "images/png"||file.mimetype == "images/gif" ){
file.mv('public/imgs/uploads/'+file.name, function(err) {
if (err)
return res.status(500).send(err);
const sql = "INSERT INTO `nt_data`(`username`,`title`,`state`,`category`, `images` ,`description`) VALUES ('" + username + "','" + title + "','" + state + "','" + category + "','" + img_name + "','" + description + "')";
const query = con.query(sql, function(err, result) {
res.redirect('show/'+result.insertUsername);
});
});
} else {
message = "This format is not allowed , please upload file with '.png','.gif','.jpg'";
res.render('new.ejs',{message: message});
}
} else {
res.render('new');
}
};
exports.show = function(req, res){
let message = '';
const username = req.params.username;
const sql="SELECT * FROM `nt_data` WHERE `username`='"+username+"'";
con.query(sql, function(err, result){
if(result.length <= 0)
message = "show not found!";
res.render('show.ejs',{data:result, message: message});
});
};
And here's an part of my new.ejs code
<body>
<h1 class="mt-5" id="h1">New Post</h1>
<hr class="w-50">
<div class="container mt-3">
<form action="/" method="POST" class="was-validated" enctype="multipart/form-data">
<% if (message.length > 0) { %>
<div class="alert alert-success col-sm-12"><%= message %></div>
<% } %>
<div class="row">
<div class="col-6">
<select name="state" class="custom-select mb-3">
<option>Select Sate</option>
<option value="Sikkim">Sikkim</option>
<option value="Manipur">Manipur</option>
<option value="Mizoram">Mizoram</option>
</select>
</div>
please help me solve this error it's very important.
Thank you
Your index.js file doesn't contain a POST Method for the route "/". You can use the below example to add one:
app.post('/',function(req,res){
//Your function code
});

Getting a 502 Bad Gateway error when I try and require code from Node.js files

I am looking to start including my route files in my Node.js and express application. However, when I require the local route files into my server.js file, and try to run that on Nginx, I get a 502 Bad Gateway error.
The code that is giving me trouble is currently commented out. Any ideas on what might be causing this performance?
server.js
require('dotenv').config();
const express = require('express');
const bodyparser = require('body-parser');
const session = require('express-session');
const MongoDBStore = require('connect-mongodb-session')(session);
// const oidc = require('./okta');
// const searchRouter = require('./routes/search');
// const inputRouter = require('./routes/input');
// const dataRouter = require('./routes/view-all');
const app = express();
app.use(express.static('public'));
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.sendFile(__dirname + '/views/index.html');
});
app.get('/page', function(req, res) {
res.render(__dirname + '/views/optishop.ejs');
});
const listener = app.listen(8080, function() {
console.log('Your app is listening on port ' + listener.address().port);
});
Edit: This is the file being required in the searchRouter declaration.
search.js
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const oidc = require('../okta');
const router = express.Router();
router.post('/search', oidc.ensureAuthenticated(), async (req, res) => {
await MongoClient.connect(
process.env.MONGODB_URI,
{ useUnifiedTopology: true },
async (err, client) => {
assert.equal(null, err);
const db = client.db('test');
const arr = req.body.item.trim().split(/; */gi);
const user = req.session.passport.user.userinfo.sub;
const cursor = await db
.collection('test')
.find({
user
})
.toArray();
const filteredCursor = cursor.filter(obj => {
return arr.includes(obj.item);
});
res.render('index', {
cursor: filteredCursor
});
// res.send(filteredCursor);
client.close();
}
);
});
module.exports = router;

Cannot GET with nodejs?

I have a simple nodejs app with some users. I want to load a specific user profile using a URL localhost/users/(username) but I'm getting this error when I try to load the URL:
Cannot GET /users/test
Here's my user.js routes file for the user page:
var express = require('express');
var router = express.Router();
var User = require('../models/user');
// GET user by username
router.get('/users/:username', function(req, res) {
var username = req.params.username;
res.send(req.params);
res.render('user');
});
module.exports = router;
I have a user.handlebars file in my views folder so it should load the file. What am I missing in my routes file? Any help would be greatly appreciated. Thanks!!
EDIT: app.js:
console.log('Starting app.js');
const fs = require('fs');
const _ = require('lodash');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const exphbs = require('express-handlebars');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const mongo = require('mongodb');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/tipcup');
var db = mongoose.connection;
const routes = require('./routes/index');
const users = require('./routes/users');
const user = require('./routes/user');
// Init App
var app = express();
// View Engine
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout: 'layout'}));
app.set('view engine', 'handlebars');
// BodyParser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
app.use(cookieParser());
// Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));
// Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// Passport Init
app.use(passport.initialize());
app.use(passport.session());
// Express Validator
app.use(expressValidator ({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length){
formParam += '[' + namespace.shift() + ']';
}
return {
param: formParam,
msg: msg,
value: value
};
}
}));
// Connect Flash
app.use(flash());
// Global Vars
app.use(function (req, res, next){
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.user = req.user || null;
next();
});
app.use('/', routes);
app.use('/users', users);
app.use('/users/:username', user);
// Set Port
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function(){
console.log('Server started on port '+app.get('port'));
});
Render function renders a view and sends the rendered HTML string to the client.Take a look at documentation.
But what you are trying to archive is to send data first and then render and send again. So, just delete the line with send.
router.get('/users/:username', function(req, res) {
var username = req.params.username;
res.render('user');
});
And, please, edit your question by adding your code with middleware and add your error.
Update
Take a look at the way how you define your routes for users.
You have to remove /users from defining route in users.js file

Categories