JavaScript Prevent accessing restricted page without login in - javascript

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.
}

Related

How to reload page in the same window?

I made 3 pages - one for Login, one for Register and one for Home. After I press the submit button, I am redirectioned to a new window. I want to be in the same window, but redirectioned to the home page, not a new tab, only one page. After the Login/Register page -> Home page. I have tried location.assign, location.reload, window.location.reload etc., but it did not work. Maybe there is something wrong in my code but I honestly dont know what. HTML and JS code for Login form:
<form name="LoginForm">
<p>Username</p>
<input type="text" name="user" placeholder="Enter Username">
<p>Password</p>
<input type="password" name="pass" placeholder="Enter Password">
<input type="submit" name="" value="Login" onclick="return redirect_home1();">
Forgot your password?<br>
Register here for a new account.
</form>
function redirect_home1() {
var x = document.forms["LoginForm"]["user"].value;
var y = document.forms["LoginForm"]["pass"].value;
if (x == "" && y == "")
alert("Must complete Username and Password");
else if (x == "" && y != "")
alert("Must complete Username");
else if (y == "" && x != "")
alert("Must complete Password.");
else {
alert("Sumbited. You will be redirected in a few seconds...");
location.assign('location.html');
}
return true;
}
You can use the window object to change your page location.
window.location.href = "filename.html"

onBlur causes infinite loop of alert messages in Chrome

I have to make a HTML page, with a form containing an email address and a URL. I should check whether the email is a legitimate Gmail or Yahoo! format, and if the URL is correct as well. However, on Chrome, when I type a wrong email, then without correcting it I click into the URL's input, I get infinite alert messages.
Here's the HTML file
<form action="/index.html" method="POST" name="form">
<p>Full name: <input type="text" pattern="[A-Z][a-z]+ [A-Z][a-z]+"></p>
<p>Date: <input type="date"></p>
<p>Email: <input type="email" id="email" onblur="validateEmail(document)"></p>
<p>Favourite website: <input type="url" id="url" onblur="validateFavURL(document)"></p>
</form>
And heres the JS file:
function validateEmail(document) {
let email = document.getElementById("email").value
let regexGmail = /\S+#gmail\.\S+/
let regexYahoo = /\S+#yahoo\.\S+/
if (!regexGmail.test(email) || regexYahoo.test(email)) {
alert("Incorrect email address!")
}
}
function validateFavURL(document) {
let url = document.getElementById("url").value
let regexURL = /https?:\/\/www\.[A-Za-z1-9_-]+\.[A-Za-z1-9_-]+\.[A-Za-z1-9_-]+/
let regextwodots = /^((?!\.\.).)+/
let regexdots = /\..+\./
if (!regexURL.test(url) || !regextwodots.test(url) || regexdots.test(url)) {
alert("Incorrect webpage!")
}
}
I have changed some of your code and added some of mine, now the alert will be triggered with smart.
/*
hasAlreadyAlerted is a boolean variable, from it's name you know that
this variable will be false only if the elementy currently focusing on
has not been alerted last time.
alwertedElement is a reference to the last element that triggered the alert
*/
var hasAlreadyAlerted = false, alertedElement;
document.querySelector("form").addEventListener('focus', (event) =>
hasAlreadyAlerted = event.target == alertedElement, true);
function validateEmail(emailElement) {
let email = emailElement.value,
regexGmail = /\S+#gmail\.\S+/,
regexYahoo = /\S+#yahoo\.\S+/;
if(!hasAlreadyAlerted && (!regexGmail.test(email) || regexYahoo.test(email))) {
hasAlreadyAlerted = true;
alertedElement = emailElement;
alert("Incorrect email address!")
}
}
function validateFavURL(urlElement) {
let url = urlElement.value,
regexURL = /https?:\/\/www\.[A-Za-z1-9_-]+\.[A-Za-z1-9_-]+\.[A-Za-z1-9_-]+/,
regextwodots = /^((?!\.\.).)+/,
regexdots = /\..+\./;
if (!hasAlreadyAlerted && (!regexURL.test(url) || !regextwodots.test(url) || regexdots.test(url))) {
hasAlreadyAlerted = true;
alertedElement = document.getElementById("url");
alert("Incorrect webpage!")
}
}
/*
So if the user types a wrong email or url that triggers the alert and
stores the reference of the element and that an alert has already triggerd,
and no other alerts should be triggered from the same element unless the user
has clicked in another one, this is all to avoid getting in an infinite loop
like you have already seen, and the cause of that loop is just the way the
events are being handled, I thinks when the user types something and clicks
outside the input element the blur event is triggered and that triggers an
alert and once you click on the alert button the blur event is triggered once
again and so on making a an infinite number of alerts
*/
<form action="/index.html" method="POST" name="form">
<p>Full name: <input type="text" pattern="[A-Z][a-z]+ [A-Z][a-z]+"></p>
<p>Dátum: <input type="date"></p>
<p>Email: <input type="email" id="email" onblur="validateEmail(this)"></p>
<p>Kedvenc weboldal: <input type="url" id="url" onblur="validateFavURL(this)"></p>
</form>

Built a login form script but it's not working using JavaScript

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>

How to prevent users from easily accessing localStorage

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.

Can't submit form through javascript to php

I have a form in html which I want to run verification in Javascript first before POST ing to PHP. However the link up to the PHP section does not seem to be working despite the fact that I have assigned names to each input tag and specified an action attribute in the form tag.
Here is the HTML code for the form:
<form id="signupform" action="signupform.php" method="post">
<input type="text" name="Email" placeholder="Email Address" class="signupinput" id="email" />
<br />
<input type="password" name="Password" placeholder="Password" class="signupinput" id="passwordone" />
<br />
<input type="password" placeholder="Repeat Password" class="signupinput" id="passwordtwo" />
<br />
<input type="button" value="Sign Up" class="signupinput" onClick="verifypass()" id="submit" />
</form>
The button calls the javascript function which I use to verify the values of my form before sending to php:
function verifypass() {
var form = document.getElementById("signupform");
var email = document.getElementById("email").value;
var password1 = document.getElementById("passwordone").value;
var password2 = document.getElementById("passwordtwo").value;
var emailcode = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (emailcode.test(email)) {
if (password1.length > 6) {
if (password1 == password2) {
form.submit(); //this statement does not execute
} else {
$("#passwordone").notify("Passwords do not match!", {
position: "right"
})
}
} else {
$("#passwordone").notify("Password is too short!", {
position: "right"
})
}
} else {
$("#email").notify("The email address you have entered is invalid.", {
position: "right"
})
}
}
For some reason, some JavaScript implementations mix up HTML element IDs and code. If you use a different ID for your submit button it will work (id="somethingelse" instead of id="submit"):
<input type="button" value="Sign Up" class="signupinput" onClick="verifypass()" id="somethingelse" />
(I think id="submit" has the effect that the submit method is overwritten on the form node, using the button node. I never figured out why, perhaps to allow shortcuts like form.buttonid.value etc. I just avoid using possible method names as IDs.)
I'm not sure why that's not working, but you get around having to call form.submit(); if you use a <input type="submit"/> instead of <input type="button"/> and then use the onsubmit event instead of onclick. That way, IIRC, all you have to do is return true or false.
I think it would be better if you do it real time, for send error when the user leave each input. For example, there is an input, where you set the email address. When the onfocusout event occured in Javascript you can add an eventlistener which is call a checker function to the email input.
There is a quick example for handling form inputs. (Code below)
It is not protect you against the serious attacks, because in a perfect system you have to check on the both side.
Description for the Javascript example:
There is two input email, and password and there is a hidden button which is shown if everything is correct.
The email check and the password check functions are checking the input field values and if it isn't 3 mark length then show error for user.
The showIt funciton get a boolean if it is true it show the button to submit.
The last function is iterate through the fields object where we store the input fields status, and if there is a false it return false else its true. This is the boolean what the showIt function get.
Hope it is understandable.
<style>
#send {
display: none;
}
</style>
<form>
<input type="text" id="email"/>
<input type="password" id="password"/>
<button id="send" type="submit">Send</button>
</form>
<div id="error"></div>
<script>
var fields = {
email: false,
password: false
};
var email = document.getElementById("email");
email.addEventListener("focusout", emailCheck, false);
var password = document.getElementById("password");
password.addEventListener("focusout", passwordCheck, false);
function emailCheck(){
if(email.value.length < 3) {
document.getElementById("error").innerHTML = "Bad Email";
fields.email = false;
} else {
fields.email = true;
document.getElementById("error").innerHTML = "";
}
show = checkFields();
console.log("asdasd"+show);
showIt(show);
}
function passwordCheck(){
if(password.value.length < 3) {
document.getElementById("error").innerHTML = "Bad Password";
fields.password = false;
} else {
fields.password = true;
document.getElementById("error").innerHTML = "";
}
show = checkFields();
console.log(show);
showIt(show);
}
function showIt(show) {
if (show) {
document.getElementById("send").style.display = "block";
} else {
document.getElementById("send").style.display = "none";
}
}
function checkFields(){
isFalse = Object.keys(fields).map(function(objectKey, index) {
if (fields[objectKey] === false) {
return false;
}
});
console.log(isFalse);
if (isFalse.indexOf(false) >= 0) {
return false;
}
return true;
}
</script>

Categories