Below is html code for login form
<h2 class="title">Sign in</h2>
<div class="input-field">
<i class="fas fa-user"></i>
<input type="email" id="email" placeholder="Email"/>
</div>
<div class="input-field">
<i class="fas fa-lock"></i>
<input type="password" id="password" placeholder="New Password" />
</div>
<input type="submit" value="Login" class="btn solid" onclick="login()" />
Below is .js file code for login function
function login () {
alert('Login Function')
// Get all our input fields
email = document.getElementById('email').value
password = document.getElementById('password').value
// Validate input fields
if (validate_email(email) == false || validate_password(password) == false) {
alert('Email or Password is Outta Line!!')
return
// Don't continue running the code
}
auth.signInWithEmailAndPassword(email, password)
.then(function() {
// Declare user variable
var user = auth.currentUser
// Add this user to Firebase Database
var database_ref = database.ref()
// Create User data
var user_data = {
last_login : Date.now()
}
// Push to Firebase Database
database_ref.child('users/' + user.uid).update(user_data)
// DOne
alert('User Logged In!!')
})
.catch(function(error) {
// Firebase will use this to alert of its errors
var error_code = error.code
var error_message = error.message
alert(error_message)
})
}
everything is working fine but my web app is not connected to a database of firebase
Note I've already required library or dependencies whatever you want to call in both HTML and js files.
Related
This question already has answers here:
What is the difference between post api call and form submission with post method?
(2 answers)
Closed 11 months ago.
I have a login/signup system using nodeJS. now the problem is when i use fetch() method on the client javascript side the res.redirect() method does not work. what could be the problem with fetch() API thats stopping the res.redirect method on the server.js ? the last line does not work the res.redirect('/index.html');
maybe there is another way to submit my form on the client javascript without using the fetch() method?
here is my code for my client javascript
const MyForm = document.getElementById("myform"); const username = document.getElementById("username") const email = document.getElementById("email"); const password=document.getElementById("password"); const confirmPassword = document.getElementById("confirm-password-input"); const alertMessege = document.getElementById("message");
MyForm.addEventListener('submit' , function(event) { event.preventDefault();
MatchingPassword();
});
function MatchingPassword(){
let pass = password.value.trim();
let confpass = confirmPassword.value.trim();
if(pass != 0) {
if(pass == confpass){
alertMessege.textContent = "";
console.log("Password Match");
fetch('SignUp.html' , {
method: 'POST',
headers:{
'content-Type': 'application/json',
},
body: JSON.stringify({
username: username.value,
email: email.value,
password: password.value,
}),
});
console.log("Fetched and posted");
}
else{
alertMessege.textContent = "Password doesn't match! ";
console.log("Password Does not Match!");
}
}
}
and here is the server.js
the last line does not work the
res.redirect('/index.html');
that is in this piece of code
// app.post sign up form
app.post("/SignUp.html", async function(req, res){ const {username, email, password} = req.body;
let user = await UserModel.findOne({email});
if (user){
console.log("User Already Exists");
return res.redirect("/SignUp.html");
}
user = new UserModel({
username,
email,
password,
});
await user.save();
console.log(user)
res.redirect('/index.html');
});
my html body
<body>
<form id="myform" action="SignUp.html" method="POST"> Create an account <div class="card"> <div class="card-body">
<!-- full name input-->
<div class="form-group">
<label for="fullname-input">Full name</label>
<input type="text" class="form-control" id="username" placeholder="Enter full name" name="username" maxlength="50" required>
</div>
<!-- email input-->
<div class="form-group">
<label for="email-input">Email address</label>
<input type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email" name="email" pattern="^[\w]{1,}[\w.+-]{0,}#[\w-]{2,}([.][a-zA-Z]{2,}|[.][\w-]{2,}[.][a-zA-Z]{2,})$" title="Must be a valid email. example#example.com" required>
</div>
<!-- password input
minimum set to 8 chars(must have one letter,one number and a symbol)
-->
<div class="form-group">
<label for="password-input">Password</label>
<input type="password" class="form-control" id="password" placeholder="Password" name="password" pattern="(?=.*\d)(?=.*[!##\$%\^&\*])(?=.*[A-Za-z]).{8,}" title="Password must be at least 8 characters and at least one number, one letter and one symbol" required>
</div>
<!--Confirm password must match password input-->
<div class="form-group">
<label for="confirm-password-input">Confirm password</label>
<input type="password" class="form-control" id="confirm-password-input" placeholder="Confirm password" required>
</div>
<div>
<small id="message"> </small>
</div>
<br>
<input type="submit" class="btn btn-primary btn-block" id="sign-up-button" value="Register">
<br>
<p>Already have an account? Sign In </p>
</div>
</div>
</form>
</body>
the fetch api is not capable to change your browser url, that is why you should redirect on the front-end rather than the backend
on your back-end instead of:
res.redirect('/index.html')
use
res.json({success : true}) //if signup successfully
and on the front end just add some callback functions to your fetch
fetch('SignUp.html' , {
method: 'POST',
headers:{
'content-Type': 'application/json',
},
body: JSON.stringify({
username: username.value,
email: email.value,
password: password.value,
})
})
.then(result => result.json())
.then(data => {
if(data.success)
window.location.href = "/index.html"
})
I am trying to make a login page using firebase, I am very new to this and have been reading through the firebase documentation to find a solution to my problem.
This is my function using the firebase.auth().signInWithEmailAndPassword() method from the firebase auth SDK.
function toggleSignIn() {
var email = document.getElementById('inputEmail').value;
var password = document.getElementById('inputPass').value;
if (email.length < 1) {
alert('Please enter an email address.');
return;
}
if (password.length < 1) {
alert('Please enter a password.');
return;
}
// Sign in with email and pass.
firebase.auth().signInWithEmailAndPassword(email, password).catch(function (error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode === 'auth/wrong-password') {
alert('Wrong password.');
} else {
alert(errorMessage);
}
console.log(error);
});
}
This will run once in a blue moon, but will stop running after that.
I click my 'Login_buton' on my HTML page, and it just clears the input email, and input password boxes.
Nothing happens after that, I check my console window and there is no user signed in.
This is what the HTML looks like
<div id="Login-google" class="input-group-google">
<button id="Logout_buton" type="submit" class="submit-buton" onclick="toggleSignOut()"> Test Logout </button>
</div>
<form id="Login" class="input-group">
<input id="inputEmail" type="text" class="input-field" placeholder="Email" required>
<input id="inputPass" type="text" class="input-field" placeholder="Password" required>
<input type="checkbox" class="check-box"> <span> Remember Password </span>
<button id="Login_buton" type="submit" class="submit-buton" onclick="toggleSignIn()"> Test Login </button>
</form>
Any help on this will be greatly appreciated, I am very new to this please be easy on me.
You are submitting a form, the default browser behaviour submits the form by making a POST request to the given URL. If you want to prevent the default behaviour you need to write e.preventDefault() in your submit method. Here is the updated code.
Use forms onsubmit event to submit the form
Javascript
function toggleSignIn(e) {
e.preventDefault(); // prevent the default behaviour
var email = document.getElementById('inputEmail').value;
var password = document.getElementById('inputPass').value;
if (email.length < 1) {
alert('Please enter an email address.');
return;
}
if (password.length < 1) {
alert('Please enter a password.');
return;
}
// Sign in with email and pass.
firebase.auth().signInWithEmailAndPassword(email, password).then((response) => {
console.log(response);
// do something when sign in is successful
}).catch(function (error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode === 'auth/wrong-password') {
alert('Wrong password.');
} else {
alert(errorMessage);
}
console.log(error);
});
}
HTML
<div id="Login-google" class="input-group-google">
<button id="Logout_buton" type="submit" class="submit-buton" onclick="toggleSignOut()"> Test Logout </button>
</div>
<form id="Login" class="input-group" onsubmit="return toggleSignIn(event)">
<input id="inputEmail" type="text" class="input-field" placeholder="Email" required>
<input id="inputPass" type="text" class="input-field" placeholder="Password" required>
<input type="checkbox" class="check-box"> <span> Remember Password </span>
<button id="Login_button" type="submit" class="submit-button"> Test Login </button>
</form>
</div>
I have a problem and it's hard, too hard for me as a beginner. Can you please help me. I know this is kinda strange creating this with javascript but it's just my own project, nothing i will put on web. But i need this problem solved by using pure Vanilla Javascript, i have
users as shown below on .js and i have a page where i need to create i new user that can be logged in as same as other two(admin and guest), i need another guest user and created based on input values...Thanks in advance, i am still learning and comments would be appreciated as well..
var el = document.getElementById("login");
if (el) {
el.addEventListener('click', state);
}
function state() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username == "admin" && password == "admin") {
sessionStorage.setItem("isAdmin", "yes");
alert("You are logged in as ADMIN !");
window.location.href = "../index.html";
} else if (username == "guest" && password == "guest") {
sessionStorage.setItem("isAdmin", "no");
alert("You are logged in as GUEST !");
window.location.href = "../index.html";
} else {
alert("Incorrect username or password, try again !")
}
}
<header>
<div class="container">
<div id="branding">
<h1><span id="logo">mov</span>BLANK</h1>
</div>
<nav>
<ul>
<li>Home</li>
<li><a id="newprojection" href="newprojection.html">New projection</a></li>
<li><a id="buyticket" href="buyticket.html">Buy a ticket</a></li>
<li class="current"><a id="newuser" href="newuser.html">New user</a></li>
<li><a id="loginbtn" href="login.html">Log in</a></li>
<li>
<a id="nameofuser" href="#"></a>
</li>
</ul>
</nav>
</div>
</header>
<div class="container">
<form>
<p>Username</p>
<input type="text" name="username" required>
<p>Password</p>
<input type="password" name="password" required>
<p>Repeat Password</p>
<input type="password" name="password" required>
<p>Function(admin/guest)</p>
<input type="text" name="function" required>
<a id="adduser" href="#">Add User</a>
</form>
</div>
you can save two data: value and key so add this function in your code.
function saveData() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if(!sessionStorage.getItem(username) == username) {
sessionStorage.setItem(username, password);
}else {
alert(username + "already registered");
}
}
update this
<input type="text" name="username" required id="username">
<p>Password</p>
<input type="password" name="password" required id="password">
<p>Repeat Password</p>
<input type="password" name="password" required>
<p>Function(admin/guest)</p>
<input type="text" name="function" required>
<a id="adduser" href="#" onclick="saveData();">Add User</a>
This is the logic, I hope I have helped
Try creating an array of valid users, rather than using if-else statements to check against each individual user (which can't be adapted to additional users).
const users = [
{ username: 'admin', password: 'admin' },
{ username: 'guest', password: 'guest' },
];
Then when you want to create a new user, push to that array. Verify logins with with:
function state() {
const username = document.getElementById("username").value;
const password = document.getElementById("password").value;
const foundUser = users.find(user => user.username === username && user.password === password);
if (!foundUser) {
console.log('Invalid user!');
} else {
// Log the user in
}
}
Problem is, your current code validates a user login attempt (for which there isn't a button for), which can't (or shouldn't) be the same form as the form used to register, at least not without changing things around significantly.
I made a working example, see below. The example is just for testing/learning purposes. I would recommend you to validate user and password using http requests and preventing sql injections.
PS: here is jsfiddle: https://jsfiddle.net/xdLey6cp/24/
PS2: you can use sweet alert instead of alert: https://sweetalert.js.org/guides/
<input type="text" id="txt_user" placeholder="user">
<!--you should use type=password here, but set as text for test purposes-->
<input type="text" id="txt_password" placeholder="password">
<input type="submit" id="createuser" value="create user">
<input type="submit" id="validateuser" value="validate new user">
<script>
//adding event handlers
document.querySelector('#createuser').onclick = create_user;
document.querySelector('#validateuser').onclick = validate_user;
function create_user()
{
//assign values for username and password
var username = document.querySelector("#txt_user").value;
var password = document.querySelector("#txt_password").value;
//using sessionstorage to keep user and password values
sessionStorage.setItem("username", username);
sessionStorage.setItem("password", password);
alert('new user is created');
}
function validate_user()
{
//getting previously recorded username and password
var recorded_username = sessionStorage.getItem("username");
var recorded_password = sessionStorage.getItem("password");
//assign values for username and password
var username = document.querySelector("#txt_user").value;
var password = document.querySelector("#txt_password").value;
//doing it as simple as possible, no filters (trim, lowercase) at all
if (username==recorded_username && password==recorded_password)
{alert('user and password are valid');}
else
{alert('validation error');}
}
</script>
I am currently trying to create a user login page where the user information is stored on a json file. I have created my GET method to the file but I cannot seem to redirect after the user has logged in successfully. Can you help me out?
I know that user login and validation done on the client side is A BAD IDEA but that is how I want to do it, without using a database.
Here is my HTML code:
<body ng-controller="myCtrl">
<form id="login-form">
<h3>User Login</h3>
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" id="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd">
</div>
<button type="submit" class="btn btn-default" id="login-button" ng-click="LogOn()">Login</button>
</form>
</body>
My JavaScript code:
var app = angular.module('myApp', [ ]);
app.controller("myCtrl",['$scope', '$http', function($scope, $http){
$scope.LogOn = function(){
$http.get('data.json').then(function(data){
$scope.users = data;
});
if (data.email == email) && (data.password = password{
window.location.href = 'www.google.com';
}
};
}]);
My JSON File:
[
{
"email":"something#yahoo.com",
"Password":"password"
},
{
"email":"test#yahoo.com",
"password":"test999"
},
{
"email":"xxx#mail.xx",
"password":"xxx"
}
]
Please try to open the link and check and run the code which is deployed in w3 schools
https://www.w3schools.com/code/tryit.asp?filename=FDVZY3NXVYG6
Put redirection code inside then
$http.get('data.json').then(function(data){
$scope.users = data;
if (data.email == email && data.password == password) {
window.location.href = 'www.google.com';
}
});
Obviously the if bellow has to be inside the .then( callback
if (data.email == email && data.password == password) {
window.location.href = 'www.google.com';
}
I am new to meteor and I am trying to do recover password and change password in Meteor. I will post below the code I have used to do this. I do get the template rendered, but the passwords do not change. Can anyone please help me with this? I am using the package accounts-password.
Custom-useraccounts.html:
<template name="RecoverPassword">
<form id="set-new-password">
<label for="new-password">New Password</label>
<input type="password" id="new-password" placeholder="Try not to forget this one.">
<input type="submit" value="Set New Password">
<p id="form-messages"></p>
</form>
<form id="forgot-password">
<label for="user-email">Email</label>
<input type="text" id="user-email" placeholder="Email">
<input type="submit" value="Get Reset Password Instructions">
<p id="form-messages"></p>
</form>
</template>
<template name="ChangePassword">
<form id="change-password">
<label for="current-password">Current Password</label>
<input type="password" id="current-password" placeholder="Current Password">
<label for="new-password">New Password</label>
<input type="password" id="new-password" placeholder="New Password">
<label for="new-password-repeated">Repeat New Password</label>
<input type="password" id="new-password-repeated" placeholder="Repeat New Password">
<input type="submit" value="Update Password">
<p id="form-messages"></p>
</form>
</template>
custom user-accounts.js:
if (Meteor.isServer) {
Template.RecoverPassword.events({
'submit #change-password': function(event, template) {
var currentPassword,
newPassword,
newPasswordRepeated;
currentPassword = template.find('#current-password');
newPassword = template.find('#new-password');
newPasswordRepeated = template.find('#new-password-repeated');
if (newPassword !== newPasswordRepeated) {
template.find('#form-messages').html("The new passwords don't match!");
return false;
}
if (Meteor.isServer) {
if (Accounts._resetPasswordToken) {
Session.set('resetPasswordToken', Accounts._resetPasswordToken);
}
Template.RecoverPassword.helpers({
resetPassword: function() {
return Session.get('resetPasswordToken');
}
});
Template.RecoverPassword.events({
'submit #forgot-password': function(event, template) {
event.preventDefault();
var email = template.find('#user-email'),
message;
alert(email);
if (email) {
Accounts.forgotPassword(email);
message = 'Sent a reset password link to ' + email + '.';
} else {
message = 'Please enter a valid email address.'
}
template.find('#form-messages').html(message);
return false;
},
'submit #set-new-password': function(event, template) {
event.preventDefault();
// Proper decoupled validation would be much nicer than this
var password = template.find('#new-password').value,
passwordTest = new RegExp("(?=.{6,}).*", "g");
if (passwordTest.test(password)) {
Accounts.resetPassword(
Session.get('resetPasswordToken'),
password,
function(error) {
if (err) {
template.find('#form-messages').html('There was a problem resetting your password.');
} else {
Session.set('resetPasswordToken', null);
}
});
} else {
template.find('#form-messages').html('Your password is too weak!');
}
return false;
}
});
}
I have already removed the insecure and autopublish options and I have published the userdata. I just cannot understand why template to change password does not work.
Well, the issue is you're running that code on the server with if (Meteor.isServer)
All your client code needs to be in if (Meteor.isClient) which is anything template level. You also get that for free if it's in a folder called client.