Form input comparison to sqlite3 database in node.js - javascript

I'm relatively new to using node.js and sqlite3. I'm trying to check to see if a users name and password entered thorough a form matches ones saved in an sqlite3 db. I want to raise an error if the username/password entered doesn't match those in the db, otherwise send the user to another page.
Relevant form:
<form action="/account" method="post">
<div class="form-group">
<label for="user">Name:</label>
<input type="text" id="user" name="name">
</div>
<div class="form-group">
<label for="pass">Password:</label>
<input type="password" id="pass" name="password">
</div>
<button type="submit">Submit</button>
Database create and comparison to form:
var db = new sqlite3.Database(':memory:');
db.serialize(function() {
db.run("CREATE TABLE Accounts (id INTEGER, username TEXT, password TEXT, fullname TEXT");
db.run(`INSERT INTO Accounts VALUES (1, "bob", "password", "Bob Bobson")`);
});
});
db.close();
app.get('/account', function (req, res) {
db.all('SELECT * FROM Accounts', function(err, rows){
rows.forEach(function (row){
if (row.username == req.body.user)
//go to success page
if (row.username != req.body.usr)
//list error
});
res.send();
});
});

It is not wise to run a query and retrieve all the rows from accounts table. If the table is too big it will take a lot of time.
It's better to do a "get" query with parameters and retrieve the specific row if it exists. If it exists the row parameter in the function callback will NOT be undefined.
db.get("SELECT * from ACCOUNTS where username=? and password=?",
[req.body.user,req.body.password],function(err,row){
if(typeof row!=='undefined' && row!=null){ console.log('user exists'); }
});

Related

Why am I getting a JSON error and how do I fix it

I am trying got take the value that is inserted into the first and last name fields and then take that and insert it into a MySQL database backend that I have running using restAPI. I got some help to fix the form but I am trying to find the error when I try to take the input form the form and enter it in the database
The table code is this
<div class="superhero">
<h1>Lets add our first name </h1>
<form action="/add_user" method="post">
<input type = "text" firstname = "firstname">
<h1>Lets add our last name </h1>
<form action="/add_user" method="post">
<input type = "text" lastname = "lastname">
<input type="submit" class="btn btn-primary">
</form>
Then this is taken into the nodeJS server with this command
app.post('/add_people', function(req, res){
axios.get('http://127.0.0.1:5000/api/adduser')
.then((response)=>{
var restlist = response.data.results;
console.log(restlist);
// Now we will execute the results in the page named thanks
});
});
Then at the end it is going to be taken to the RestAPI with that is using this route
#app.route('/api/adduser', methods = ['POST']) # This is a post method because the user needs to be able to add info
def adding_stuff():
request_data = request.get_json() # Gets the info from the table and converts to JSON format
new_fname = request_data['firstname']
new_lname = request_data['lastname']
conn = create_connection("", "", "", "")
sql = "INSERT INTO restaurantusers (firstname, lastname) VALUES ('%s', '%s');" % (new_fname, new_lname) # This sql statement will then be uploaded to the databse to add a new record
execute_query(conn, sql) # This will execute the query
return 'Post worked'
Sorry if what I am asking sounds really complicated. Professor goes too fast in class and I've been trying to find out how to do this for sometime with no luck.
UDATE: I later changed the two items as suggested. The route is
app.post('/add_people', function(req, res){
axios.post('http://127.0.0.1:5000/api/adduser')
.then((response)=>{
var restlist = response.data.results;
console.log(restlist);
// Now we will execute the results in the page named thanks
});
});
and the form is now
<form action="/add_people" method="post">
<input type = "text" firstname = "firstname">
<h1>Lets add our last name </h1>
<input type = "text" lastname = "lastname">
<input type="submit" class="btn btn-primary">
</form>
I get the error that
},
isAxiosError: true,
toJSON: [Function: toJSON]
}
and also this error on the restAPI window
TypeError: 'NoneType' object is not subscriptable
First, you'll need to update your form and inputs to accept user input properly by using the value attribute on the <input> so instead of
<input type = "text" firstname = "firstname">
<input type = "text" lastname = "lastname">
Do this
<input type="text" value="firstname">
<input type="text" value="lastname">
this will send the values firstname and lastname to your API.
If you need to dynamically accept user input you'll need to watch input changes using javascript and handle the form submit with it too. Check
input value attribute and Javascript form.
To send the data from your node server to your python server you'll need to update
axios.post('http://127.0.0.1:5000/api/adduser')
To
axios.post('http://127.0.0.1:5000/api/adduser', { first_name: req.body.firstname, last_name: req.body.last_name })
Because that way you're passing the form data inside req.body to your python server

displaying string in html after js executes something

So, im trying to create a accounts system, i made a login system that works, but when you enter wrong credentials i want it to display "wrong username or password" in the value of ab empty tag, the thing is that i dont know how to access the tag from app.js (node.js project)
<div class="form">
<form class="login-form" action="/account" method="post">
<p id = "check"></p>
<h1 id = "login-text">Login</h1>
<label style="color:white;">Username:</label>
<input type="text" id = "username" placeholder="Enter Username" name="username" required>
<label style="color:white;">Password:</label>
<input type="password" id = "password" placeholder="Enter Password" name="password" required>
<button type="submit">Login</button>
<h5>register</h5>
</form>
</div>
</div>
app.post('/account', (req, res) => {
const username = req.body.username;
const password = req.body.password;
con.query("USE discbin")
con.query('SELECT * FROM accounts WHERE username = ?', [username], function (err, result, fields) {
if (err) throw err;
if (result.length > 0 && result[0].password === password) {
console.log(result[0].username + " logged in!")
res.render('account');
}
else {
console.log("a user tried to login using the username: " + username)
//set <p> to "wrong username or password"
}
});
});
document.getElementById("check").textContent = "wrong username or password";
Get the element you want to update document.getElementById("check")
Set its textContent property to the text you want to use
I think this is an XY problem.
As far as I know, it is not possible to access a DOM element directly from the server, however, you can achieve the same result with a little JavaScript on the client side.
For example the server response could be on authentication success a JSON object like that:
{
auth: true,
//some token I guess...
}
and on authentication fail:
{ auth: false }
Then, you can use JavaScript to access the element you want and modify its content using the innerHTML method.
In your case, you could store the string to be displayed and modify it according to the server response.
let checkStringVariable = "";
On server response:
checkStringVariable = response.auth ? "" : "wrong username or password";
document.getElementbById("check").innerHTML = checkStringVariable;

Don't allow empty textbox in asp.net mvc 3.1

I've got 2 HTML input textbox: "Email" and "Password". Whenever I submit these textboxes with no value I get this SQL exception: SqlException: The parameterized query '(#email nvarchar(4000),#password nvarchar(4000))SELECT Email,Pas' expects the parameter '#email', which was not supplied.
I just want an message that says that I need to fill in a email and password. I've already an JS function that checks these textboxes for empty value and it works. But it still redirects to the SQL Exception page afterwards. I think I've done something stupid with my database properties. How can I fix this?
string sqlquery = "SELECT Email,Password FROM [dbo].[User] WHERE Email = #email and Password = #password;";
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
sqlcomm.Parameters.AddWithValue("#email", user.Email);
sqlcomm.Parameters.AddWithValue("#password", user.Password);
SqlDataReader sdr = sqlcomm.ExecuteReader();
if (sdr.Read())
{
return RedirectToAction("Index", "Home");
}
else
{
ViewData["Message"] = "Fout";
}
sqlconn.Close();
return View();
Login
<form asp-action="Login" method="post">
<input id="loginEmail" type="text" name="Email" asp-for="#Model.Email" />
<input id="loginWachtwoord" type="password" name="Password" asp-for="#Model.Password" />
<input type="submit" onclick="CheckNullOrEmpty()" value="Login" />
<h1>#Html.ViewData["Message"]</h1>
</form>
just check the parameters before you try to query the database
if(string.IsNullOrEmpty(user.Email) || string.IsNullOrEmpty(user.Password)) {
ViewData["Message"] = "Fout";
return View();
}
//... validate first then try to create the statement.
You could also try/catch the errors and return the View in the catch block if you don't want the error page popping up. There's also ModelState.IsValid which you can read about

How do you save data from an html form to a mysql database using javascript?

I am trying to save data from an html form into a mysql database. Obviously I am new to this so I know I am doing something wrong but after doing a lot of research I still can't figure it out. I created a simple version of my form for testing purposes.
<!DOCTYPE html>
<html>
</head>
<body>
<script src="scripts/test.js"></script>
<form>
<input id="firstName" type="text" class="form-control" name="firstName" placeholder="First Name">
<input id="lastName" type="text" class="form-control" name="lastName" placeholder="Last Name">
<input id="userName" type="text" class="form-control" name="userName" placeholder="Username">
<input id="inputText" type="text" class="form-control" name="email" placeholder="Email">
<input id="currentPassword" type="password" class="form-control" name="currentPassword" placeholder="Current Password">
<input type="submit" onclick="saveAccount()" id="createAccountButton" class="button2" value="Create Account"></input>
</form>
</body>
</html>
My javascript code is:
function saveAccount(){
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "abc123",
database: "PBSC_Parking_DB"
});
con.connect(function(err) {
if (err) throw err;
console.log("connected");
});
var firstName = document.getElementById("firstName");
var lastName = document.getElementById("lastName");
var psw = document.getElementById("psw");
var userName = document.getElementById("userName");
var email = document.getElementById("inputText");
var sql = "INSERT INTO accounts (UserName, FirstName, LastName, Email, UserPassword) VALUES ('"+userName+ "', '"+firstName+"','"+lastName+"','"+email+"','"+psw+"')";
con.query(sql, function (err, result) {
if (err) {
throw err;
}
console.log(result.affectedRows + " record(s) updated");
});
}
I've read that you're suppose connect to the database outside of a function but moving it outside the function does not seem to solve my problem.
I've also been told that I shouldn't be using 'document.' but I'm not sure how else to pull the data from the form to be used in my sql statement.
I tried hard coding values into an INSERT statement, not using a function and just running the js file through the command prompt. This works to update my database so I know I'm doing the connection correctly... I just don't know how to make it work with the form.
note: I also tried looking up tutorials using nodejs and ejs but after following the tutorials carefully I still couldn't get them to work.
You are just retrieving the DOM elements from the form. What you want to query are the values of the inputs.
var firstName = document.getElementById("firstName").value;
And the same for the other variables.

How can I make put and delete requests from a form using node.js and express.js?

So I'm trying to make a put request using
My put form
<form id="for" action="/people" method="post">
<div class="">
<input type="text" name="Name" value=<%= data[0].name %> >
</div>
<div class="">
<input type="text" name="City" value="" placeholder=<%= data[0].favorite_city %>>
</div>
<input type="hidden" name="_method" value="put"/>
<input type="submit" name="" value="Edit">
</form>
My server side scripts
var methodOverride = require('method-override');
app.use(methodOverride('_method'));
app.put('/people', function(req,res){
pg.connect(DATABASE_URL, function(err, client, done){
var pid = parseInt(req.params.id);
var name = req.query.Name;
var city = req.query.City;
var client_query = '';
if(name = ''){
client_query = `update persons set favorite_city =${city} where id = ${pid}`;
}
else{
client_query = `update persons set name = ${name}, favorite_city= ${city} where id= ${pid}`;
}
client.query(client_query, function(err, result){
res.redirect(`/people/${pid}`)
done();
pg.end();
})
})
});
I am using method override but it only seems to do a post with the new data
The problem is similar with delete so I'm not going to put the code here because it may be a little redundant. But if anyone wants to see it I don't mind
methodOverride('_method') returns a middleware that looks for the key _method in the query string (see method-override docs). By including the _method variable in the form and sending the form with the POST method, _method is not included in the query string, but in the request body. Probably you want to use the body-parser middleware before the methodOverride middleware and then do something like:
app.use(methodOverride(req => req.body._method));
In addition, you probably want to replace query with body in:
var name = req.query.Name;
var city = req.query.City;

Categories

Resources