displaying string in html after js executes something - javascript

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;

Related

Simple Login Form

I am trying to implement a simple login form using JavaScript and HTML. When I submit the form, I want to check the username and password against a list of valid credentials.
If the credentials are valid, I want to redirect the user to the home page. Otherwise, I want to show an error message. I have written the following code, but it is not working as expected. Can someone please help me debug this issue?
<form id="login-form">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
<script>
const form = document.getElementById('login-form');
const username = document.getElementById('username');
const password = document.getElementById('password');
form.addEventListener('submit', function(event) {
event.preventDefault();
const validCredentials = [
{ username: 'user1', password: 'pass1' },
{ username: 'user2', password: 'pass2' }
];
for (const credential of validCredentials) {
if (credential.username === username.value && credential.password === password.value) {
window.location.href = '/home';
} else {
alert('Invalid username or password');
}
}
});
</script>
I am implement a simple login form using JavaScript and HTML.
The expected outcome of the code is that when the user enters a valid username and password and clicks the submit button, they will be redirected to the home page. If the username and password are invalid, an error message should be displayed.
First of all, don't do this if you want to use this code for real users and production web app. It's not a good approach to hardcore users or passwords in a JavaScript script. If you are using this code for learning purposes, it's okay!
Secondly, the code has two meaningful problems. The alert inside the else block is running after every iteration of the for loop. You have to add a return statement to stop the loop and exists the function. Place the alert after the for loop, because the intention of the alert (I guess) is: if you don't find any coincidence, show to the user that the username and password are invalid.
for (const credential of validCredentials) {
if (credential.username === username.value && credential.password === password.value) {
return window.location.href = '/home';
}
} //end of the loop
alert('Invalid username or password');
}); //end of the callback function
});
On the other hand, in window.location.href = '/home', the string is a malformed URI. You have to send user to a completed URI like, https://google.com/ or http:/yoursite.com/home

Getting [Object Object] in local storage

I am currently busy with a registration form, I got everything set up nicely, however, I am running into 2 local storage issues.
I get the VM6858:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse (<anonymous>) error
When I click register, something stores in the local storage, but not sure what.
The reason I want to make the information stored in local storage is so that it can be checked when the user signs in on the sign in page.
I am aware PHP is a good combination to do this for server-side, but for now, I am just focusing on storing it on the web browser, this is not being used for people to actually register this is just to practice using local storage in various ways.
HTML
<main>
<div class="heading">
<h1>User Registration</h1>
</div>
<form class="form-container">
<ul>
<li><label for="name">Name</label>
<input class="name" type="text" name="name" required />
</li>
<li><label for="surname">Surname</label>
<input class="surname" type="text" name="surname" required />
</li>
<li><label for="phone">Phone</label>
<input class="phone" type="text" name="phone" />
</li>
<li><label for="email">Email</label>
<input class="email" type="text" name="email" required /></li>
<li><label for="password">Password</label>
<input class="password" type="text" name="password" required /></li>
</ul>
<button class="reg" onclick="validate()">Register</button>
</form>
</main>
JS
//storage key
let STORAGE_KEY ="store-user-reg"
//generate ID
const createId = () =>
`${Math.floor(Math.random() * 10000)}${new Date().getTime()}`;
//get html elements
const formEl = {
id:createId(),
name: document.querySelector(".name"),
surname: document.querySelector(".surname").value,
phone: document.querySelector(".phone").value,
email: document.querySelector(".email").value,
password: document.querySelector(".password").value,
};
//Array for stored registered users
usersArray = JSON.parse(localStorage.getItem(STORAGE_KEY)) ?? [];
//function to set local storage
function store(){
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(usersArray));
}
//register button clicked
function validate() {
let name = formEl.name.value;
let surname = formEl.name.value;
let email = formEl.name.value;
let password = formEl.name.value;
if (!name) {
alert("Please fill in name");
}
if (!surname) {
alert("Please fill in Surname");
}
if (!email) {
alert("Please fill in email");
}
if (!password) {
alert("Please create a password");
}
usersArray.push(formEl);
store();
}
I added screenshots so you can see both errors
You are creating your formEl object on page load, and all the fields will be blank, you need to move your declaration inside of your validate() function to actually populate formEl with the data you want.
The other issue is what Ryan mentioned, I suggest clearing your local storage.
Updating the validate function to:
function validate() {
const formEl = {
id: createId(),
name: document.querySelector(".name").value,
surname: document.querySelector(".surname").value,
phone: document.querySelector(".phone").value,
email: document.querySelector(".email").value,
password: document.querySelector(".password").value,
};
if (!formEl.name) {
alert("Please fill in name");
}
if (!formEl.surname) {
alert("Please fill in Surname");
}
if (!formEl.email) {
alert("Please fill in email");
}
if (!formEl.password) {
alert("Please create a password");
}
usersArray.push(formEl);
store();
}
should also help!
I fixed the issue. This was they issue
let name = formEl.name.value;
let surname = formEl.name.value;
let email = formEl.name.value;
let password = formEl.name.value;
So I updated the code to this
let name = formEl.name;
let surname = formEl.surname;
let email = formEl.email;
let password = formEl.password;
which stopped the 1 Uncaught SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse (<anonymous>)
only thing left to do now is to figured out why the inputs are seen as empty even though I put in the information
Try clearing your localStorage. Otherwise JSON.parse will continuing parsing that string into '[object Object]'. It looks like in a previous attempt you did not stringify the object before calling setItem, so it got saved as the string '"[object Object]"'. You will need to clear that out in order for it to get reinitialized.
Once clear, your initialization logic should work fine.

Form input comparison to sqlite3 database in node.js

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'); }
});

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

Show welcome page when correct credentials are entered?

I have this code that logs a user in:
function logUserIn(){
var email = document.getElementById('username').value;
var password = document.getElementById('password').value;
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorMessage)
console.log('didnt log in')
});
};
this is the html:
username:<br>
<input id="username" type="text" name="username" ><br>
password:<br>
<input id="password" type="text" name="password" ><br><br>
<input type="submit" onclick=logUserIn() value="Log in">
<input type="submit" onclick=submitToDatabase() value="Sign Up">
<input type="submit" onclick=getUsers() value="Get Users">
how can I then submit this data using only javascript so if they enter the right credentials it takes them to page such as welcome.html?
I understand I may need to use a form and submitting, but I wasn't sure how this is done in JS alone and not using PHP.
I want it to say Welcome User (user being the email they signed in with)
In order to do this, you need to check for errors, and then proceed to a redirection.
Here is the sample code from Firebase documentation:
// Sign in with email and pass.
// [START authwithemail]
firebase.auth().signInWithEmailAndPassword(email, password)
.then(function(user) {
console.log(user);
// DO YOUR REDIRECTION HERE
}).catch(function(error) {
if(error) throw error;
});
For more informations. The signInWithEmailAndPassword method returns a firebase.Promise.
signInWithEmailAndPassword(email, password) returns firebase.Promise containing non-null firebase.User
You can read more here : https://firebase.google.com/docs/reference/js/firebase.Promise#then
For the redirection you can use Location.replace(). Here is a doc. link : https://developer.mozilla.org/en-US/docs/Web/API/Location/replace
Hope this helps !
Always use onAuthStateChanged() to keep track of the user's login or logout status.
//Handle Account Status
firebase.auth().onAuthStateChanged(user => {
if(user) {
window.location = 'welcome.html'; //If User is logged in, redirect to welcome page
}
});
The above code will make sure that if a user successfully signs in, they are redirected to welcome page.

Categories

Resources