I am creating a login/signup form for my html blog website. I've managed to create the user information using localStorage or sessionStorage. I would store it whenever someone creates an account, and get it whenever someone wants to log in.
I haven't made the sign out or actual user page yet, but that is not my problem. The problem is that it is too easy for someone to steal passwords or clear all the account data using localStorage.clear()
Here is an HTML example:
<html>
<head>
<script src="index.js"></script>
<link rel="stylesheet" href="style.css">
<title>Accounts</title>
</head>
<body>
<article>
<h1>Log In</h1>
<input type="text" id="signin-username" placeholder="Username" value="">
<input type="password" id="signin-password" placeholder="Password" value="">
<button type="submit" onclick="signin()">Sign In</button>
<!------------------------------------>
<h1>Create Account</h1>
<input type="text" id="create-username" placeholder="Username" value="">
<input type="password" id="create-password" placeholder="Password" value="">
<button type="submit" onclick="create()">Create Account</button>
</article>
</body>
</html>
And here is the javascript for it:
var a = localStorage.length;
function signin() {
var name = document.getElementById('signin-username').value;
var pass = document.getElementById('signin-password').value;
if (name === '' && pass === '') {
console.log('Please provide your account details')
}
else if (name === '') {
console.log('Please provide your username!');
}
else if (pass === '') {
console.log('Please provide your password!');
}
else {
var ii;
for (ii = 0; ii < a; ii++) {
if (name === localStorage.key(ii)) {
console.log('Logged in as ' + name);
ii > a
}
else {
console.log('Account Does Not Exist!')
}
}
}
};
function create() {
var username = document.getElementById('create-username').value;
var password = document.getElementById('create-password').value;
if (username === '' && password === '') {
console.log('Invalid Username and Password')
}
else if (username === '') {
console.log('Invalid Username');
}
else if (password === '') {
console.log('Invalid Password');
}
else {
var i;
for (i = 0; i < a; i++) {
if (username === localStorage.key(i)) {
console.log('Username Exists!');
}
else {
localStorage.setItem(username, password)
}
};
}
}
I had to post The Full thing in order for it to make sense.
Anyone have suggestions, like user cookies, for storing data?
You can even redirect me to a login example!
I've managed to create the user information using localStorage or sessionStorage.
LocalStorage is "local" to the web browser. Data stored in LocalStorage is not shared with the web server, or with other web browsers viewing the site. It makes no sense to store account data in these locations, because doing so will result in an "account" that only exists on one computer.
(SessionStorage works similarly, except it disappears when the browser is closed -- so it's even less useful for your purposes.)
If you want to allow users to create accounts on your web site, you will need some sort of code running on the web server to implement these accounts. There is no way to implement this functionality entirely in client-side Javascript.
Related
I am trying to build a login.js script that listens for the login form submit event. When I try to run my code, it's not logging in or working properly
I' working with JavaScript, which is requested to use. I built the login form in HTML and have worked on the login function within JavaScript. It can;t be inline JavaScript, it has to be a separate script from HTML.
var count = 2;
function validate() {
var un = document.login.username.value;
var pw = document.login.password.value;
var valid = false;
var usernameArray = ["adrian#tissue.com",
"dduzen1#live.spcollege.edu",
"deannaduzen#gmail.com"
]
var passwordArray = ["welcome1", "w3lc0m3", "ch1c#g0"]
for (var i = 0; i < usernameArray.length; i++) {
if ((un == usernameArray[i]) && (pw == passwordArray[i])) {
valid = true;
break;
}
}
if (valid) {
alert("Login is successful");
window.location = "index.html";
return false;
}
var again = "tries";
if (count == 1) {
again = "try"
}
if (count >= 1) {
alert("Wrong username or password")
count--;
} else {
alert("Incorrect username or password, you are now blocked");
document.login.username.value = "You are now blocked";
document.login.password.value = "You are now blocked";
document.login.username.disabled = true;
document.login.password.disabled = true;
return false;
}
}
<!-- start of login form -->
<div class="login-page">
<div class="form">
<form class="register-form" onsubmit="return validate() ;" method="post">
<input type="text" placeholder="username" />
<input type="text" placeholder="password" />
<input type="text" placeholder="email id" />
<button>Create</button>
<p class="message">Already registered? Login
</p>
</form>
<form class="login-form">
<input type="text" placeholder="username" />
<input type="text" placeholder="password" />
<button>login</button>
<p class="message">Not registered? Register
</p>
</form>
</div>
</div>
It needs to allow the three login information I put into the code to log into the site. When logging in, it blinks as if it's doing something, but isn't going anywhere nor does it show that the person is logged in.
You are not validating correctly with the return sentence, also your onsubmit attribute was in the register form.
Use name attribute on forms
This will help you to identify your forms and inputs easily with JavaScript, otherwise you might have problems identifying which input is which in larger forms.
<form name="login" class="login-form">
<input name="user" type="text" placeholder="username" />
<input name="pass" type="text" placeholder="password" />
<button>login</button>
<p class="message">Not registered? Register
</p>
</form>
With this applied to your login form, you can reference it by doing document.login.
Take advantage over native HTML events in JavaScript
The way you are retrieving the username and password is a lot complex that it should, you can add an event listener in JavaScript and handle everything there:
const loginForm = document.login;
loginForm.addEventListener("submit", validate);
This will call validate every time the form is submitted. Also, it sends the event as a parameter, so you can receive it like this in your function:
function validate(event) {
event.preventDefault(); // Stop form redirection
let user = event.target.user.value,
pass = event.target.pass.value;
// REST OF THE CODE ...
}
This is easier since we added name attributes to the inputs, so we can identify them by user and pass.
Validation
NOTE: I do not recommend validating username:password data directly in the browser, since this is a big vulnerability and must be validated server-side.
You can simplify this validation by binding the username with its password in an object, instead of creating two arrays:
const accounts = {
"adrian#tissue.com": "welcome1",
"dduzen1#live.spcollege.edu": "w3lc0m3",
"deannaduzen#gmail.com": "ch1c#g0"
};
And then, having the inputs value saved in user and pass variables, you can do:
if (accounts[user] == pass) {
//SUCCESSFUL LOGIN
console.log('Correct. Logged in!');
} else {
//WRONG LOGIN CREDENTIALS
attempts--;
validateAttempts();
}
With the purpose of not having a lot of code in sight, you should create another function that its only job is to validate if you should block the user or not.
The result
I should mention that this will only work to validate the user form, if you need to save a session and keep an user logged in, you must use a server-side language.
I leave you a snippet with all of this changes working, see it for yourself:
const accounts = {
"adrian#tissue.com": "welcome1",
"dduzen1#live.spcollege.edu": "w3lc0m3",
"deannaduzen#gmail.com": "ch1c#g0"
};
const loginForm = document.login;
let attempts = 3;
loginForm.addEventListener("submit", validate);
function validate(event) {
event.preventDefault();
let user = event.target.user.value,
pass = event.target.pass.value;
if (accounts[user] == pass) {
//SUCCESSFUL LOGIN
console.log('Correct. Logged in!');
} else {
console.log('Wrong username or password.');
attempts--;
validateAttempts()
}
}
function validateAttempts() {
if (attempts <= 0) {
console.log("You are now blocked");
loginForm.user.value = "You are now blocked";
loginForm.pass.value = "You are now blocked";
loginForm.user.disabled = true;
loginForm.pass.disabled = true;
}
}
<form name="login" class="login-form">
<input name="user" type="text" placeholder="username" />
<input name="pass" type="text" placeholder="password" />
<button>login</button>
<p class="message">Not registered? Register
</p>
</form>
I am using WebStorage to make a simple login system with username/password. (I don't know if this is the best way.)
It is working, but the problem is, it only works with one username and password. How do I make it so that it can store multiple usernames/passwords? Or perhaps I should be using a different system to do this?
Code:
<html>
<head>
</head>
<body>
<input type="text" placeholder="input username here" id="textbox">
<input type="text" placeholder="input password here" id="textbox2">
<input type="button" value="sign up" onclick="signup()">
<br>
<input type="text" placeholder="input username here" id="textbox3">
<input type="text" placeholder="input password here" id="textbox4">
<input type="button" value="login" onclick="login()">
<p id="result"></p>
<br>
<br>
<div id="settings">
<h1>Settings</h1>
<br>
<input type="text" placeholder="background color" id="bgc">
<br>
<input type="button" onclick="changeSettings()" value="Change settings">
</div>
<script>
function changeSettings() {
if(loggedIn == true) {
if(typeof(Storage)!= "undefined") {
var backg = document.getElementById("bgc").value;
if(backg!="") {
localStorage.setItem("backgroundColor", backg);
document.body.style.background = localStorage.getItem("backgroundColor");
} else {
alert("Enter a color.")
}
} else {
alert("No support.")
}
} else {
alert("You must be logged in to do that.")
}
}
function loadSettings() {
if(typeof(Storage)!="undefined") {
document.body.style.background = localStorage.getItem("backgroundColor");
} else {
alert("No support.")
}
}
function signup() {
if(typeof(Storage)!= "undefined") {
var username = document.getElementById("textbox").value;
var password = document.getElementById("textbox2").value;
if(username!="" && password!="") {
localStorage.setItem("username", username);
localStorage.setItem("password", password);
} else {
alert("Please enter a valid username and password.")
}
} else {
alert("No support.")
}
}
function login() {
if(typeof(Storage)!= "undefined") {
var username = localStorage.getItem("username");
var password = localStorage.getItem("password");
var usernameInput = document.getElementById("textbox3").value;
var passwordInput = document.getElementById("textbox4").value;
if(usernameInput!="" && passwordInput!="") {
if(usernameInput == username && passwordInput == password) {
document.getElementById("result").innerHTML = "Logged in!";
loggedIn = true;
loadSettings();
} else {
document.getElementById("result").innerHTML = "Wrong password/username!";
}
} else {
alert("Please enter a valid username and password.")
}
} else {
alert("No support.")
}
}
</script>
</body>
</html>
ps: sorry if it's messy :p
You should probably be using SQL if you want to store user inputs such as Usernames and Passwords.
Hashing & Password Storage
Good video to watch if your trying to learn Databases!
:)
Not a good way to store the plain username/password in localStorage. anyone can change those value. Since you check the login using
localStorage.setItem("username", username);
localStorage.setItem("password", password);
var username = localStorage.getItem("username");
var password = localStorage.getItem("password");
usernameInput == username && passwordInput == password
This login condition can make true using different ways.
Found this article from the Google, Hope you'll get some idea to do in
secure way :)
I have a login page after being logged to page I move to my next-page (welcome).
The problem is that if I copy and paste the URL of the next-page (welcome) my page also open, I want to restrict to open the next page without login access.
Guide me What to do.
Script
function click() {
inputname = $('#name').val();
inputpassword =$('#pass').val();
for (i in data.username ) //to match username with provided array
{
name = data.username[i];
for ( i in data.password){
pass = data.password[i];
if (inputname == name & inputpassword == pass ){
window.open('welcome1.html','_self');
}
}
}
if (inputname != name & inputpassword != pass ){
alert("Wrong Password");
}
}
HTML
<input type="mail" id="name">
<input type="password" id="pass">
<input type="submit" id="submit" value="log In" onclick= "click()">
This is not a secure method of authentication. This solutions should not be on any system which you want to make secure. Authentication should happen on the server, not the client.
In your question, you never check on the second page if the user authenticated on the first page. In order to check this, you should use session storage.
// LOGIN.js
function click() {
inputname = $('#name').val();
inputpassword =$('#pass').val();
for (i in data.username ) //to match username with provided array
{
name = data.username[i];
for ( i in data.password){
pass = data.password[i];
if (inputname == name & inputpassword == pass ){
//The user has successfully authenticated. We need to store this information
//for the next page.
sessionStorage.setItem("AuthenticationState", "Authenticated");
//This authentication key will expire in 1 hour.
sessionStorage.setItem("AuthenticationExpires", Date.now.addHours(1));
//Push the user over to the next page.
window.open('welcome1.html','_self');
}
}
}
if (inputname != name & inputpassword != pass ){
alert("Wrong Password");
}
}
//addHours to a date.
//Credit to: Kennebec
//https://stackoverflow.com/questions/1050720/adding-hours-to-javascript-date-object
Date.prototype.addHours = function(h) {
this.setTime(this.getTime() + (h*60*60*1000));
return this;
}
<!-- LOGIN.html --->
<input type="text" id="name" name="name" />
<input type="text" id="pass" name="pass" />
<input type="submit" id="sub" name="sub" onclick="click();" />
And then on your second page, check to see if the user is authenticated. If not, push them over to an Access Denied page.
//Is the user authenticated?
if (sessionStorage.getItem('AuthenticationState') === null) {
window.open("AccessDenied.html", "_self");
}
//Is their authentication token still valid?
else if (Date.now > new Date(sessionStorage.getItem('AuthenticationExpires'))) {
window.open("AccessDenied.html", "_self");
}
else {
//The user is authenticated and the authentication has not expired.
}
I made register and login options in an empty html (not on a webpage) just to see if I could and how I could do it. Now I ran into a problem - I can register multiple usernames that have the same value (for example I can register "test username" as many times as I want to).
I want to know how I can check if the value that the user puts in to register has already been registered.
Here is my code :
HTML :
<!-- Login -->
<div class="login">
<label>Login</label>
<input type="text" id="login-username" class="textbox" placeholder="Username"/>
<input type="password" id="login-password" class="textbox" placeholder="Password"/>
<button type="submit" onclick="login()">Login</button>
</div>
<!-- Register -->
<div class="register">
<label>Register</label>
<input type="text" id="register-username" class="textbox" placeholder="Username"/>
<input type="password" id="register-password" class="textbox" placeholder="Password"/>
<button type="submit" onclick="register()">Register</button>
</div>
JavaScript :
function login() {
if(document.getElementById("login-username").value == username1 && document.getElementById("login-password").value == password1) {
alert("Hi " + username1 + " you are now logged in.");
} else if(document.getElementById("login-username").value == username2 && document.getElementById("login-password").value == password2) {
alert("Hi " + username2 + " you are now logged in.");
} else {alert("Wrong username or password");}
function register() {
if (username1 == null && password1 == null) {
localStorage.removeItem("username1");
localStorage.setItem("username1", document.getElementById("register-username").value);
localStorage.removeItem("password1");
localStorage.setItem("password1", document.getElementById("register-password").value);
alert("Hi, " + document.getElementById("register-username").value + " is now registered.");
location.reload();
} else if (username2 == null && password2 == null) {
localStorage.removeItem("username2");
localStorage.setItem("username2", document.getElementById("register-username").value);
localStorage.removeItem("password2");
localStorage.setItem("password2", document.getElementById("register-password").value);
alert("Hi, " + document.getElementById("register-username").value + " is now registered.");
location.reload();
}
var username1 = localStorage.getItem("username1");
var username2 = localStorage.getItem("username2");
var usernameAlpha = [username1, username2]; //This is a list of all usernames
//and it's what I want to look through when I'm checking if the value/username already exists
var password1 = localStorage.getItem("password1");
var password2 = localStorage.getItem("password2");
try this
function register(){
var users = JSON.parse(localStorage.getItem('users')) || [];
var username = document.getElementById("register-username").value;
var password= document.getElementById("register-password").value;
var toBeRegister= true;
for(i=0;i<users.length;i++){
if(users[i].username === username){
toBeRegister = false
}
}
if(toBeRegister){
users.push({username:username,password:password})
localStorage.setItem('users', JSON.stringify(users));
}
}
Thanks to Rajesh I was able to make it work and here is how :
I just used his method to check if the username that the user typed in was in usernameAlpha. If it was I displayed an alert message "Username taken" and if it was not I simply registered the user like normal.
Here is the code :
function register() {
if(usernameAlpha.indexOf(document.getElementById("register-username").value) > -1) {alert("Username taken")
} else if (username1 == null && password1 == null && document.getElementById("register-username").value != "" && document.getElementById("register-password").value != "") {
localStorage.removeItem("username1");
localStorage.setItem("username1", document.getElementById("register-username").value);
localStorage.removeItem("password1");
localStorage.setItem("password1", document.getElementById("register-password").value);
alert("Hi, " + document.getElementById("register-username").value + " is now registered.");
location.reload();
} else if (username2 == null && password2 == null && document.getElementById("register-username").value != "" && document.getElementById("register-password").value != "") {
localStorage.removeItem("username2");
localStorage.setItem("username2", document.getElementById("register-username").value);
localStorage.removeItem("password2");
localStorage.setItem("password2", document.getElementById("register-password").value);
alert("Hi, " + document.getElementById("register-username").value + " is now registered.");
location.reload();
}
}
You mention 'array', but don't use them well. You still have variables username1 and username2, which means you have to copy a bunch of code (again) if you want to introduce username3. If you build an array of users, or an object where the username is the key/propertyname, then you can build a more dynamic user database.
You can save and load the entire object in a serialized way to and from localStorage.
Do note that although it's a fun exercise, localStorage is not a safe place for this, and storing passwords (either in plain text or encrypted) is not a good practice either.
Anyway, it could look something like this:
var
userDatabase = null;
function loadUserDatabase() {
// Load the user database only if it wasn't loaded yet. This way, various functions can
// always call this function 'to be sure'.
if (userDatabase === null)
userDatabase = JSON.parse(localStorage.getItem("userDatabase"));
}
function saveUserDatabase() {
// Save the entire database back to local storage.
localStorage.setItem("userDatabase", JSON.stringify(userDatabase));
}
function normalizeUsername(username) {
// "Normalize" the username by converting different styles of writing to
// a base form.
// In this case, trim and convert to lowercase to effectively make user
// names case insensitive while still usings keys/properties.
return username.trim().toLowerCase();
}
function findUser(username) {
// Check if user database is loaded
loadUserDatabase();
// Find the user by username.
username = normalizeUsername(username);
if (userDatabase.hasOwnProperty(username)) {
return userDatabase[username];
}
return false;
}
function isValidUsername(username) {
// Implement any limits you want (or need) to impose here.
// A length check of, say <1000 would be a nice addition.
return username != '';
}
function setUser(username, password) {
loadUserDatabase();
username = normalizeUsername(username);
// Set/overwrite the user
userDatabase[username] = {password: password};
// Save the database to disk.
saveUserDatabase();
}
function login() {
var username = document.getElementById("login-username").value;
var password = document.getElementById("login-password").value;
if (user = findUser(username)) {
if (user.password == password) {
// There is a match, log in
alert('login successful as user ' + username);
} else {
// Password incorrect
alert('Invalid password for username ' + username);
}
} else {
// User not found
alert('User ' + username + ' not found');
}
}
function register() {
var username = document.getElementById("register-username").value;
var password = document.getElementById("register-password").value;
if (!isValidUsername(username)) {
alert('invalid username')
} else if (user = findUser(username)) {
alert('user ' + username + ' already exists');
} else {
setUser(username, password);
alert('user ' + username + ' created');
}
}
<!-- Login -->
<div class="login">
<label>Login</label>
<input type="text" id="login-username" class="textbox" placeholder="Username"/>
<input type="password" id="login-password" class="textbox" placeholder="Password"/>
<button type="submit" onclick="login()">Login</button>
</div>
<!-- Register -->
<div class="register">
<label>Register</label>
<input type="text" id="register-username" class="textbox" placeholder="Username"/>
<input type="password" id="register-password" class="textbox" placeholder="Password"/>
<button type="submit" onclick="register()">Register</button>
</div>
use the toString method from Object.prototype.
if( Object.prototype.toString.call( Variable ) === '[object Array]' ) {
alert( 'Array!' );
}
I use the following code to validate a password in a form. If the password is correct - Move the user to site X. If it's incorrect (after 3 tries), move the user to site Y.
For some reason, it works only for site Y.
My code:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form>
Enter password to continue: <br>
<input type="text" id="user"/>
<input type="button" id="myButton" value="Enter site"/>
</form>
<script>
let tries = 0;
let error = 0;
let password = 'tiesto';
document.querySelector("#myButton").onclick = ()=> {
let passwordValue = document.querySelector('#user').value;
if (password === passwordValue) {
window.location.href = 'http://maariv.co.il';
} else {
tries++;
alert('Try again please.');
}
if (tries === 3) { // 3 is the border.
error++;
}
if (error === 1) {
window.location.href = 'http://microsoft.com';
}
};
</script>
</body>
</html>
I tried doing:
Checking for syntax errors all over the code.
Changing === to == (I thought, maybe due to it being a string, the quote marks counted as well, of course I was mistaken).
window.location.href = 'http://maariv.co.il', true;
Adding return false right under window.location.href
As a beginner I ask, why would the condition works only in a half? That is, the positive part (than) doesn't work but the negative part (else) does work.
Update:
This is just an exercise. Indeed. This isn't going to production. In production I should store and request the password from a database.
Put the following line let passwordValue = document.querySelector('#user').value; inside onclick of "mybutton".
let tries = 0;
let error = 0;
let password = 'tiesto';
document.querySelector("#myButton").onclick = ()=> {
let passwordInput = document.querySelector('#passwordInput').value;
if (password === passwordValue) {
window.location.href = 'http://maariv.co.il';
} else {
tries++;
alert('Try again please.');
}
if (tries === 3) { // 3 is the border.
error++;
}
if (error === 1) {
window.location.href = 'http://microsoft.com';
}
};
<form>
Enter password to continue: <br>
<input type="text" id="user" />
<input type="button" id="myButton" value="Enter site" />
</form>
Use return :
if (password === passwordValue) {
return window.location.href = 'http://maariv.co.il';
}
Otherwise, the function will execute to the end, and you will reach the second redirection, that will then override the first one.