Show welcome page when correct credentials are entered? - javascript

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.

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

Having error with simple login form,please resolve my issue and also mention the problem

I am trying to make an simple login form using javascript,also don't able to find any error,please help me to succesfully implement it.Here is code
function validate()
{
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username == "admin" && password == "user")
{
alert("login successfully");
return false;
}
else
{
alert("login failed");
}
}
It seems like your code should be working fine, unless you've incorrectly trying to access the "username" and "password" elements. In which case, your program will not throw an error. I would suggest handling that error appropriately, which you can see in the following answer: https://stackoverflow.com/a/20378738/8222441.
If an error does exist with trying to reference your desired elements by its ID, you can console.log something to debug further!
Nothing here seems to be broken. I'm guessing something is wrong with your html, but I can't tell since it's not included.
Here's a way of doing it, this works:
<form id="loginForm">
<input placeholder="username" id="username" />
<input placeholder="password" id="password" />
<button type="submit" id="submitButton">Submit</button>
</form>
const form = document.getElementById("loginForm")
form.addEventListener("submit", (e) => {
e.preventDefault();
if(form.elements["username"].value == "admin" && form.elements["password"].value == "user"){
alert("login successful")
} else {
alert("nope")
}
})

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;

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.

Parsing user data into &body attribute of mailto form

I have this script:
function calculate(){
passworda = document.password1.user1.value.toLowerCase()
passwordb = document.password1.pass1.value.toLowerCase()
var user = 1
var pass = 1
for(d=0;d<passwordb.length;d++) {
pass*= passwordb.charCodeAt(d);
}
for(e=0;e< passworda.length; e++) {
user *= passworda.charCodeAt(e);
}
document.password1.outputuser1.value = user;
document.password1.outputpass1.value = pass;
}
and this form:
<form name="password1" enctype="text/plain" method="get" action="mailto:myemail#mydomain.com?subject=Register&body=A new user has registered with your form. Their username is ' +outputuser1+ ' and their password is ' +outputpass1+ '">
Username:<input type="text" name="user1" />
Password:<input type="password" name="pass1" />
<input type="submit" value="Register" onclick="calculate()" />
<input type="reset" value="Reset" />
</form>
What I want to do is when a user fills out this form and hits submit, it emails me with their encrypted username and password, replacing
&body=A new user has registered with your form. Their username is ' +outputuser1+ ' and their password is ' +outputpass1+ '"
with
&body=A new user has registered with your form. Their user name is JOHNSMITH and their password is 123456"
when the form gets submitted. I'm not getting any javascript errors, but when the email window opens, the body and subject are blank.
Can anyone help get this working please? Many thanks in advance!
Forms with mailto: uris are too poorly supported for use on the WWW.
If you want to collect data with a form then you need to use an HTTP(S) URI as the action, and process submitted data on the server.

Categories

Resources