Simple Login Form - javascript

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

Related

JavaScript Login Form Not Validating

Good Evening,
I am trying to create a simple JavaScript login form that will validate by checking only 1 specific email address which has been declared and 1 password that has been declared.
However, no matter what is typed into the fields, even if nothing is present, once the submit button is clicked, the user is directed to the desired page.
I need it to only allow the desired page if the email address and password are the correct. Otherwise, notify them that it is incorrect.
Here is a link to [codepen][1] so you can see the page and script.
https://codepen.io/m0rrisim0/pen/bmzyqj
Any help is appreciated in figuring out why the script is not validating.
You have to use the attribute value from document.getElementById method,
like the following example: document.getElementById("UserName").value
function validate() {
'use strict';
var UserName = document.getElementById('UserName').value;
var email = "adrian#tissue.com";
var Password = document.getElementById('Password').value;
var pass = "welcome1";
if ((UserName == email) && (Password == pass)) {
return true;
} else {
alert("UserName and/or Password Do Not Match");
return false;
}
}
Your form's inputs lack the id atrribute and should return the function on submit event.
<form action="Issues.html" method="post" id="loginform" onsubmit="return validate()">
UserName:
<input type="text" name="UserName" id="UserName">
<br>
<br>
Password:
<input type="password" name="Password" id="Password">
<hr>
<input type="submit" value="Submit">
</form>
Your problem was getElementById(), this function requires a argument and cause a error. Because of this error the line loginform.onsubmit = validate; was never reached so the submit button submit the form without calling a validate function.
There is no need to put this line inside the if statement, but if you want you can change a little bit to getElementById without the parentesis, this way it evaluates to a function that in js is truthy.
You can check a working version of you code here:
if (document && document.getElementById) {
var loginform = document.getElementById('loginform');
loginform.onsubmit = validate;
}
https://codepen.io/francispires/pen/mzvYKX
You can improve this validation

Javascript change password by using an input

I am new in Javascript and I want to make a code where a window will be open asking the user to type a specific password. If the password is correct then he "enters" the page. In the page, he can find an input and a button. He can change the password by filling the input and then pressing the Submit button. Basically to change the value of the variable. The problem is that I don't know how can I "pass" the input with id="changePass" to the variable pass1 and then I am not sure if the new password will be saved. Thank you in advance! Bellow you can find my code:
<html>
<body>
<script>
var entered = false;
var password;
var pass1="pass";
if (entered == false) {
password = prompt('Enter your password in order to view this page!', ' ');
if (password == pass1) {
alert('Correct Password, Enter the Club');
entered = true;
} else {
window.location = "";
}
} else if (entered == true) {
alert('You have already entered the password. Click OK to enter!');
}
</script>
<input id="changePass"/>
<button id="subimt" type"Submit">Submit</button>
</body>
</html>
My friend you can't rely on browser storage and cookies for logging in users and keeping passwords. The least of your problems is that if a user clears his cookies and history you are going to lose it all. :)
This is why I asked if it is a homework or at least something that you don't really care to hold on to user credentials, and your users won't have any problem to re-enter the default password every once a while.
With that being said below is the code you want to store the password to local storage
<input id="changePass"/>
<button id="changePassBtn" type"Button" onclick='changePassBtnClick()'>Change Password</button>
<input id="login"/>
<button id="loginBtn" type"Button" onclick='loginBtnClick()'>Login</button>
<script>
if(!localStorage.getItem('password')){
localStorage.setItem('password', 'pass');
}
function changePassBtnClick(){
localStorage.setItem('password', document.getElementById('changePass').value);
alert('Password changed');
}
function loginBtnClick(){
if(document.getElementById('login').value == localStorage.getItem('password')){
alert('Correct Login');
}else{
alert('Wrong Password');
}
}
</script>

How to submit a form with JavaScript using python Requests?

I have a page as follows.
www.pict.ethdigitalcampus.com
I wish to submit the form data on this page using python Requests.
But unfortunately on this website, when the Submit button is clicked it calls a validate function.
<input type="submit" value="Sign In" onclick="return validate();" style="font-family: Verdana">
Now this validate function actually encrypts the password using some algorithm and then submits it to the server.
This is how the validate function works:
function validate()
{
if(isBlank(document.loginForm.loginid.value) || isNull(document.loginForm.loginid.value))
{
alert('Please Enter Login Id.');
document.loginForm.loginid.focus();
return false;
}
if(isBlank(document.loginForm.password.value) || isNull(document.loginForm.password.value))
{
alert('Please Enter Password.');
document.loginForm.password.focus();
return false;
}
var hashObj = new jsSHA("mySuperPassword", "ASCII");
var password = hashObj.getHash("SHA-512", "HEX");
var textval =document.loginForm.password.value; //The actual password entered by the user
var encryptedString = $.jCryption.encrypt(textval, password); //The password is encrypted and stored
document.loginForm.password.value = encryptedString; //The password field of the form is updated with "encrypedString"
document.loginForm.hiddenfield.value=password;
document.loginForm.service_id.value=get_cookie(document.loginForm.loginid.value.toUpperCase());
document.loginForm.action="http://pict.ethdigitalcampus.com:80/DCWeb/authenticate.do";
return true;
}
Now since I cannot directly submit form data to the action page, I have no choice but to click that button and execute this JavaScript function.
I have tried using urllib and still no luck. What do I do?

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.

Facebook Accountkit JAVASCRIPT Implementation

I am trying to implement the facebook accountkit using javascript. I followed the documentation on https://developers.facebook.com/docs/accountkit/web/integrating.
AccountKit login form
Enter country code (e.g. +1):
<input type="text" id="country_code" />
Enter phone number without spaces (e.g. 444555666):
<input type="text" id="phone_num"/>
<button onclick="phone_btn_onclick();">Login via SMS</button>
Enter email address
<input type="text" id="email"/>
<button onclick="email_btn_onclick();">Login via Email</button>
Below is the javascript code on my app
<script src="https://sdk.accountkit.com/en_US/sdk.js"></script>
<script>
// initialize Account Kit with CSRF protection
AccountKit_OnInteractive = function(){
AccountKit.init(
{
appId:'facebook_app_id',
state:"csrf",
version:"accountkit_version"
}
);
};
// login callback
function loginCallback(response) {
console.log(response);
if (response.status === "PARTIALLY_AUTHENTICATED") {
document.getElementById("code").value = response.code;
document.getElementById("csrf_nonce").value = response.state;
document.getElementById("my_form").submit();
}
else if (response.status === "NOT_AUTHENTICATED") {
// handle authentication failure
}
else if (response.status === "BAD_PARAMS") {
// handle bad parameters
}
}
// phone form submission handler
function phone_btn_onclick() {
var country_code = document.getElementById("country_code").value;
var ph_num = document.getElementById("phone_num").value;
AccountKit.login('PHONE',
{countryCode: country_code, phoneNumber: ph_num}, // will use default values if this is not specified
loginCallback);
}
// email form submission handler
function email_btn_onclick() {
var email_address = document.getElementById("email").value;
AccountKit.login('EMAIL', {emailAddress: email_address}, loginCallback);
}
</script>
After setting the required values for appId, state and version. I tried filling the form but I was redirecting to account kit page saying
we are sorry, something went wrong, try again
Any help in the implementation will be highly appreciated. Thanks in advance
The problem has been resolved. On account kit page on facebook developer site, I pointed the server url on web login settings to all occurrence of the domain i.e http://domain.com, http://www.domain.com including https if available. This resolved the problem. THANKS ALL.

Categories

Resources