I have this express server and whenever you post username or password 1 or 1=1 it will not respond. there will be no console output or errors. And it will keep working after that.
I have tried adding app.post("*") at the top of the code and it won't even fire the event (so its not sql or the app.use).
If you want to test it go to https://speedcubing.top/login
index.js
const cubing = require('./cubing.js')
const mysql = require('./SQL.js')
const express = require('express')
const cookies = require('cookie-parser')
const uuid = require('uuid')
const app = express()
app.use(express.urlencoded({ extended: false }))
app.use(express.json())
app.use(cookies())
app.use(express.static('static'))
//database
const sql = new mysql('localhost', 'user', 'pass')
const systemdb = sql.database('speedcubingsystem')
//use
app.use(async (req, res, next) => {
cubing.info("use")
let redir = false
if (req.url.endsWith('/') && req.url != '/') {
redir = true
req.url = req.url.slice(0, -1)
}
if (req.subdomains[0] == 'www') {
redir = true
}
if (req.url.includes('?')) {
redir = true
req.url = req.url.split('?')[0]
}
if (redir)
res.redirect('https://speedcubing.top' + req.url)
else {
if (req.url != 'myip') {
req.loginName = ''
req.admin = false
if (req.cookies.login !== undefined) {
const result = await systemdb.query("SELECT user,admin FROM web_user WHERE token='" + req.cookies.login.token + "'")
if (result.length > 0) {
req.loginName = result[0].user
req.admin = result[0].admin.lastIndexOf(1) !== -1
}
}
}
next()
}
})
//index page
app.get('/', async (req, res) => {
res.render('index.ejs', {
loginName: req.loginName,
})
})
//login page
app.post('/login', async (req, res) => {
cubing.info("post login")
const name = mysql.validateString(req.body.username)
const pw = mysql.validateString(req.body.password)
if ((await systemdb.query('SELECT * FROM web_user WHERE user=' + name + ' AND password=' + pw)).length > 0) {
const token = uuid.v4()
systemdb.query("UPDATE web_user SET token='" + token + "' WHERE user=" + name + ' AND password=' + pw)
res.cookie('login', { token: token }, { httpOnly: false })
res.redirect('/')
} else res.render('login.ejs', {
loginName: req.loginName,
error: true,
})
})
app.get('/login', async (req, res) => {
cubing.info("get login")
if (req.loginName != '')
res.redirect('https://speedcubing.top')
else res.render('login.ejs', {
loginName: '',
error: false
})
})
//logout
app.get('/logout', async (req, res) => {
res.clearCookie('login')
res.redirect('/')
})
app.listen(25080, function () {
cubing.info('Listening on /0.0.0.0:25080')
})
login.ejs
<title>speedcubing.top</title>
<html>
<head>
<link rel="stylesheet" href="/a.css">
</head>
<body><div class="wrapper">
<%- include("./global/header.ejs") %>
<table width="200" border="0" align="center">
<tr><td>
<form action="login" method="post">
<% if(error !== undefined && error){%>
<p><%= "invalid usr/pw" %></p>
<% } %>
username: <input type="text" name="username" ><br/>
password: <input type="password" name="password" ><br/>
<input type="submit" value="login">
</form>
</td></tr>
</table>
</div>
<%- include("./global/footer.ejs") %>
</body>
</html>
Related
I'm developing an application with Node.js and EJS but there is an error. It says "msg_type is not defined". When I'm using handlebars, there is no problem. What is my mistake. Actually, when url goes to /auth/login , the message is displaying but it's not displaying in /login routing.
my users.js file (controllers)
exports.login = async (req, res,next) => {
try {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).render("login", {
msg: "Kullanıcı Adınız veya Parolanız Hatalı",
msg_type: "error",
},
next()
);
}
await login_db.query(
"select * from users where email=?",
[email],
async (error, result) => {
console.log(result);
if (result.length <= 0) {
return res.status(401).render("login", {
msg: "E-mailiniz veya Parolanız Hatalı",
msg_type: "error",
});
} else {
if (!(await bcrypt.compare(password, result[0].PASS))) {
return res.status(401).render("login", {
msg: "E-mailiniz veya Parolanız Hatalı",
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,
};
res.cookie("joes", token, cookieOptions);
res.status(200).redirect("/anasayfa");
}
}
}
);
} catch (error) {
console.log(error);
}
};
my auth.js file
const express = require("express");
const userController = require("../controllers/users");
const router = express.Router();
router.post("/login", userController.login);
my login.ejs file
<% if (true) { %>
<p class="<%= msg_type %>"><%= msg %> </p>
<% } %>
<form action="/auth/login" method="post">
<div class="data">
<label for="email">Email</label>
<input type="email" name="email" id="email" />
</div>
<div class="data">
<label for="password">Şifre</label>
<input type="password" name="password" id="password" />
</div>
<div class="forgot-pass">
Şifrenizi mi unuttunuz?
</div>
<div class="btn">
<button type="submit">Giriş Yap</button>
</div>
<div class="signup-link">
Kayıtlı değil misin? Şimdi Kayıt Ol!
</div>
</form>
my app.js file
app.use("/", require("./routes/pages"));
app.use("/auth", require("./routes/auth"))
;
my pages.js file
router.get(["/", "/login"], (req, res) => {
//res.send("<h1>Hello Tutor Joes Salem</h1>");
res.render("login");
});
The variable should be exported from the original file(users.js) and also should be imported in login.ejs, so you can use it without problems, this is how things work in Javascript.
When the login button is pressed I send a POST request successfully to my app.js file and just to test try to redirect it with (as instructed) used code 302.
My get request '/' is called and logged
Exist!
did we work? Why does my sendFile not work as I expected? I am relatively new to this so I may be off base on how to do this. My goal is to after submitting a POST transition the client to a new HTML file
const express = require('express');
const { json } = require('express/lib/response');
const app = express();
const fs = require('fs');
app.use(express.json());
app.get('/Register', (req, res) => {
res.sendFile(__dirname + '/Register.html');
});
app.get('/Login', (req, res) => {
res.sendFile(__dirname + '/Login.html');
});
app.get('/RegisterComplete', (req, res) => {
res.sendFile(__dirname + '/RegisterComplete.html');
});
app.get('/', (req, res) => {
console.log('did we work?')
res.sendFile(__dirname + '/Home.html');
});
app.post('/', (req, res) => {
const { username, password } = req.body;
const { authorization } = req.headers;
res.send({
username,
password,
authorization,
});
// fs.readFile('helloworld.txt', 'utf8' , (err, data) => {
// fs.writeFile('helloworld.txt', JSON.stringify(req.body) + data, function (err) {
// if (err) return console.log(err);
// });
// })
console.log(req.body + 'i am not what we need');
});
app.post('/Register', (req, res) => {
fs.readFile('Logins.Json', 'utf8' , (err, data) => {
const obj = req.body;
const testObj = JSON.stringify(obj)
const fileContent = JSON.parse(data)
const newContent = fileContent['User Info']
let test = new Boolean(false)
for (let i = 0; i < newContent.length; i++) {
if(JSON.stringify(newContent[i]) == testObj){
//console.log('Exist!')
test = true
break
}
}
//console.log(req.body);
if (test == true) {
console.log('Exist!')
}else{
newContent.push(obj);
const newData = JSON.stringify(fileContent)
fs.writeFile('Logins.Json', newData, function (err) {
console.log('Created Account!')
if (err) return console.log(err);
})
}
if (err) return console.log(err);
})
res.end()
//console.log(req.body);
});
app.post('/Login', (req, res) => {
res.redirect(302,'/');
fs.readFile('Logins.Json', 'utf8' , (err, data) => {
const obj = req.body;
const testObj = JSON.stringify(obj)
const fileContent = JSON.parse(data)
const newContent = fileContent['User Info']
let test = new Boolean(false)
for (let i = 0; i < newContent.length; i++) {
if(JSON.stringify(newContent[i]) == testObj){
//console.log('Exist!')
test = true
break
}
}
//console.log(req.body);
if (test == true) {
console.log('Exist!')
//login successful
}else{
console.log('Failed')
// login failed
}
if (err) return console.log(err);
})
});
app.listen(7777, () => {
console.log('Our express server is up on port 1000');
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>eV Login</title>
</head>
<body>
<form>
<div>
<label>Username</label>
<input type="text" id="user" />
</div>
<div>
<label>Password</label>
<input type="password" id="pass" />
</div>
<button type="submit">Login</button>
</form>
<script>
document.querySelector('button')
.addEventListener('click', (e) => {
e.preventDefault();
const username = document
.querySelector('#user').value;
const password = document
.querySelector('#pass').value;
fetch('/Login', {
method: 'POST',
headers: {
Authorization: 'Vital Gaming',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username,
password,
}),
})
.then((res) => {
return res.json();
})
.then((data) => console.log(data));
});
</script>
</body>
</html>
my index.js file and views/products/edit.ejs files :
const express = require('express')
const path = require('path')
const mongoose = require('mongoose');
const methodOverride = require('method-override')
const app = express()
app.set('view engine', 'ejs')
app.set('views', path.join(__dirname, "views"))
app.use(express.urlencoded({
extended: true
}))
app.use(methodOverride('_method'))
mongoose.connect('mongodb://localhost:27017/farmStand')
.then((data) => {
console.log("successfully connected to database")
console.log(data)
}).catch(error => {
console.log("error occured")
console.log(error)
})
function wrapperASync(fn) {
return function(req, resp, next) {
fn(req, resp, next).catch((e) => {
next(e)
})
}
}
let categories = ['fruits', 'vegetables', 'dairy']
const Product = require('./models/product');
const {
param
} = require('express/lib/request');
app.get('/', (req, resp) => {
resp.send("getting data")
})
app.get('/products', async(req, resp) => {
const {
category
} = req.query
const selectedcategory = category
console.log(selectedcategory)
if (selectedcategory) {
let products = await Product.find({
category: selectedcategory
})
resp.render("products/index", {
products,
selectedcategory
})
} else {
let products = await Product.find({})
// console.log("found products")
resp.render("products/index", {
products,
selectedcategory: "All"
})
}
})
app.get('/products/:id', async(req, resp, next) => {
const {
id
} = req.params
let myproduct = await Product.findById(id)
if (!myproduct) {
return next(new AppError("product not found", 404))
}
// console.log(myproduct)
resp.render('products/details', {
myproduct
})
})
app.get('/product/new', (req, resp) => {
resp.render('products/new', {
categories
})
})
app.get('/products/:id/edit', wrapperASync(async(req, resp, next) => {
const {
id
} = req.params
const product = await Product.findById(id)
if (!product) {
throw new AppError("product not found", 404)
}
resp.render('products/edit', {
product,
categories
})
}))
app.put('/products/:id', wrapperASync(async(req, resp, next) => {
const {
id
} = req.params
const updatedValues = req.body
const newvalue = await Product.findByIdAndUpdate(id, updatedValues, {
runValidators: true,
new: true
})
// console.log(newvalue)
resp.redirect(`/products/${newvalue._id}`)
}))
app.post('/products', wrapperASync(async(req, resp) => {
const newdoc = req.body
const myproduct = new Product(newdoc)
console.log(myproduct)
await myproduct.save()
resp.redirect(`/products/${myproduct._id}`)
}))
app.delete('/products/:id', async(req, resp, next) => {
try {
const {
id
} = req.params
const deleted_product = await Product.findOneAndDelete(id)
resp.redirect('/products')
} catch (error) {
next(error)
}
})
app.use((err, req, resp, next) => {
console.log(err.name)
next(err)
})
app.use((err, req, resp, next) => {
const {
status = 404, message = "something went wrong"
} = err
resp.status(status).send(message)
})
app.listen(3000, () => {
console.log("server started successfully")
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1> enter product details</h1>
<form action="/products/<%= product.id %>?_method=PUT " method="POST">
<label for="name">enter the name of the product : </label>
<input type="text" name="name" id="name" placeholder="name" value="<%= product.name %> ">
<label for="price">enter the price in dollars : </label>
<input type="number" name="price" id="price" placeholder="price" value="<%= product.price %>">
<label for="category">category : </label>
<select name="category" id="category">
<% for(category of categories) { %>
<option value="<%= category %>" <%=p roduct.category===c ategory ? "selected": '' %> >
<%= category %>
</option>
<% } %>
</select>
<button>add new details</button>
</form>
<section>
exit
</section>
</body>
</html>
my models/product.js file :
const mongoose = require('mongoose')
const productSchema = new mongoose.Schema({
name : {
type : String,
required : true
},
price:{
type : Number,
required : true,
min : 0
},
category:{
type:String,
lowercase :true,
enum : ["fruits","vegetables","dairy"]
}
})
const Product = new mongoose.model('Product',productSchema);
module.exports = Product;
my problem : I have installed all the dependencies my problem is when I am entering in to the edit page and then when I type my id incorrect and of different length in the url for which Iam listening for I get the CastError printed out on my console and when I keep my name Field as blank and edit then I get the ValidationError printed out on my console but after getting the validation error when I change the id of the product which is incorrect again and which is of different length in the url after getting validation error response and send the request in chrome my server gets error and breaks even though I handle the error of my /products/:id put route
please help me
I am new to programming so I don't know why this happens. Users are reporting app crashes when logging in. The app is hosted on the Heroku platform with MongoDB. Can anyone tell me what the problem might be? P.S. I don't know if there is any other way to show the code, so I'll just paste it below. The user and password for the MongoDB connection string are changed for obvious reasons.
//jshint esversion:6
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const MongoClient = require("mongodb").MongoClient;
const app = express();
const uri =
"mongodb+srv://user:password#cluster0.4wwjt.mongodb.net/anketa?retryWrites=true&w=majority";
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
app.set("view engine", "ejs");
app.use(
bodyParser.urlencoded({
extended: true,
})
);
app.use(express.static("public"));
app.get("/", (req, res) => {
res.render("login");
});
app.get("/link", (req, res) => {
res.render("link");
});
app.get("/confirm", (req, res) => {
res.render("confirm");
});
app.get("/noMoreLinks", (req, res) => {
res.render("noMoreLinks");
});
app.post("/link", (req, res) => {
const username = req.body.username;
const password = req.body.password;
client.connect((err) => {
const users = client.db("anketa").collection("users");
const links = client.db("anketa").collection("links");
users.findOne({ user: username }, (err, foundUser) => {
if (err) {
console.log(err);
} else {
if (foundUser && foundUser.pass === password) {
const unvisitedLinksLength = foundUser.unvisitedLinks.length;
const currentTime = Date.now();
if (
foundUser.timeFinished &&
currentTime - foundUser.timeFinished < 18 * 60 * 60 * 1000
) {
res.render("comeTomorrow", {
headline: "Probajte opet za nekoliko sati",
});
return;
}
if (unvisitedLinksLength === 20) {
links.findOne({ id: 1 }, (err, foundLink) => {
if (err) {
console.log(err);
} else {
res.render("link", {
link: foundLink.path,
});
users.update(
{ user: foundUser.user },
{ $set: { currentLink: foundLink.id } }
);
}
});
return;
}
if (unvisitedLinksLength < 20 && unvisitedLinksLength > 0) {
let randomNumber = Math.floor(Math.random() * unvisitedLinksLength);
links.findOne(
{ id: foundUser.unvisitedLinks[randomNumber] },
(err, foundLink) => {
res.render("link", {
link: foundLink.path,
});
users.update(
{ user: foundUser.user },
{ $set: { currentLink: foundLink.id } }
);
}
);
return;
}
if (unvisitedLinksLength === 0 && foundUser.currentLink < 21) {
links.findOne({ id: foundUser.currentLink }, (err, foundLink) => {
res.render("link", {
link: foundLink.path,
});
});
return;
}
if (foundUser.currentLink === 0 && unvisitedLinksLength === 0) {
res.render("noMoreLinks");
return;
}
}
}
});
});
});
app.post("/confirm", (req, res) => {
const username = req.body.username;
client.connect((err) => {
const users = client.db("anketa").collection("users");
users.findOne({ user: username }, (err, foundUser) => {
const currentLinkId = foundUser.currentLink;
const unvisitedLinks = foundUser.unvisitedLinks;
const newUnvisitedLinks = unvisitedLinks.filter(
(linkId) => linkId !== currentLinkId
);
users.update(
{ user: foundUser.user },
{
$set: { unvisitedLinks: newUnvisitedLinks, timeFinished: Date.now() },
}
);
if (unvisitedLinks.length === 0) {
users.update({ user: foundUser.user }, { $set: { currentLink: 0 } });
return;
}
});
});
res.render("login");
});
let port = process.env.PORT;
if (port == null || port == "") {
port = 3000;
}
app.listen(port, () => {
console.log("server started successfully");
});
Problem is that in my second post request I cannot get req.body. Neither console.log nor req.body show something.
In the first post request, everything seems to work just fine. And it was also working before I start to re-arrange code. I even change the type of the reply to send, but receiving the old message (status ok).
I do not understand what's going on. Any help, please?
Glitch: https://uatyroni-exercise-tracker.glitch.me - live app
code: https://glitch.com/~uatyroni-exercise-tracker
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const shortid = require('shortid');
const cors = require("cors");
//Setting MongoDB
const mongoose = require("mongoose");
mongoose.connect(process.env.MONGO_URI);
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static("public"));
app.get("/", (req, res) => {
res.sendFile(__dirname + "/views/index.html");
});
//Defining Schema & Model
let Schema = mongoose.Schema;
let userSchema = new Schema({
id: { type: String, unique: true, default: shortid.generate },
user: String,
exercise: [{
description: String,
duration: Number,
date: {}
}]
});
let userModel = mongoose.model("Users", userSchema);
let exerciseSchema = new Schema({
userId: String,
description: String,
duration: Number,
date: String
});
let exerciseModel = mongoose.model("Exercies", exerciseSchema);
//THE POST PROCESS
app.post("/api/exercise/new-user", (req, res) => {
let userName = req.body.username;
let userNew = new userModel({ user: userName });
userModel
.find()
.exec()
.then(data => {
data = data.filter(obj => obj["user"] === userName);
console.log("I am the data: " + data);
if (data.length === 0) {
userNew
.save()
.then(result => {
res.json(result);
})
.catch(err => {
console.log(err);
res.json({ error: err });
});
} else {
res.json({ Error: "User is already registered in the database" });
}
});
});
app.post("/api/exercise/add", (req, res) => {
console.log('reqbody is: ' + req.body.description)
let newDate = '';
if (req.body.date == '') {
newDate = new Date().getFullYear() + '-' + new Date().getMonth() + '-' + new Date().getDate();
}
let newExercise = {
description: req.body.description,
duration: req.body.duration,
date: newDate
}
userModel.findById(req.body.userid, (err, data) => {
if (data.length == null)
res.json({
error: "User is not registered. Please register a user first."
});
else {
res.json(data)
}
});
});
// Not found middleware
app.use((req, res, next) => {
return next({ status: 404, message: "not found" });
});
// Error Handling middleware
app.use((err, req, res, next) => {
let errCode, errMessage;
if (err.errors) {
// mongoose validation error
errCode = 400; // bad request
const keys = Object.keys(err.errors);
// report the first validation error
errMessage = err.errors[keys[0]].message;
} else {
// generic or custom error
errCode = err.status || 500;
errMessage = err.message || "Internal Server Error";
}
res
.status(errCode)
.type("txt")
.send(errMessage);
});
const listener = app.listen(process.env.PORT || 4000, () => {
console.log("Your app is listening on port " + listener.address().port);
});