I am creating authentication module with prompt in javascript.
Here is my code:
var pass1 = prompt('Please Enter Your Password',' ');
var originalPass = "mypassword";
if(pass1 == "mypassword"){
return;
}
else{
pass1 = prompt('Wrong Password. Please Enter Valid Password',' ');
}
HTML
<html>
<head></head>
<body>
<p>Hello, You are logged in </p>
</body>
</html>
In my code, if I enter the wrong password, the program control goes to else loop and display another prompt password field, when I enter the wrong password again at the second time, it loads the page and displays the HTML content.
What I want to do is, I don't want to get load the page until the user enters the right password.
If you get the correct password either use a innerHTML to write the content to your dom, or here I have used document.write.
To ask the password continuously from user, add a while loop and break it only if the condition is true.
var pass1 = prompt('Please Enter Your Password');
var originalPass = "mypassword";
while (1) {
if (pass1 == "mypassword") {
document.write("<html><head></head><body><p>Hello, You are logged in</p></body></html>");
break;
} else {
pass1 = prompt('Wrong Password. Please Enter Valid Password');
}
}
Related
I am creating a very simple login site for a school project, and the site is therefore the most basic you can make it.
When the window.location.assing link is activated, it will only work if the current url I am on has a # at the end. E.G. ... project/test.html#.
The rest of the script is perfectly fine. It is only the linking that does not work.
I am working in a local file so I am trying to go from
C:\Users\Tord\Documents\IT\Skryteprosjekt\test.html
to
C:\Users\Tord\Documents\IT\Skryteprosjekt\1.html
I have searched around a lot, but can not find an answer that fits my problem.
The function is being called by an onclick in a button in HTML.
function login() {
var x = document.getElementById("username").value;
if (x == "example") {
var y = document.getElementById("psw").value;
if (y == "example2") {
window.location.assign("1.html");
}
else {
alert("Incorrect username or password. Try again.");
}
}
else if (x == "") {
alert("Please write in a username and password");
}
else {
alert("Incorrect username or password. Try again");
}
}
When I activate the script with the correct username and password, the site just blinks as if it just reloads. Everything else works perfectly.
Basically I have 2 files... register.html and login.js.... I am able to store user's registration details into local storage and then parsed it as objects in array.... I need to log in properly(when user and pass match, alert box indicates login successful and then PHP file will redirect user, and if no match, alert box will indicate for that separately) and then second alert box as you have successfully signed in and then it will not redirect me as the PHP file is meant to do so when the user and pass match local storage... Any clues??
You are just not iterating correctly through credentials, you have to wait until you are sure that the current login credentials are not equal to any of the stored credentials, so you have to get this part of code out of the for loop:
alert('Invalid Username or Password! Please try again.');
event.preventDefault();
window.location="Login.html";
try this code for validating the login:
function validlogin(event) {
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
var entriesJSON = localStorage.getItem('allEntries');
if (!entriesJSON) {
event.preventDefault();
alert("Nothing stored!");
return;
}
var allEntries = JSON.parse(entriesJSON);
var isCorrectCredentials=false;
for (var i = 0; i < allEntries.length; i++) {
var entry = allEntries[i];
var storedUserName = entry.user;
var storedPassWord = entry.pass;
var storedEmailAddress = entry.email;
if (username == storedUserName && password == storedPassWord) {
isCorrectCredentials=true;
alert("Successfully logged in!");
return;
} }
if(!isCorrectCredentials){
alert('Invalid Username or Password! Please try again.');
event.preventDefault();
window.location="Login.html";
}
}
this way you will login if the current username and password are correct and notify the rest of the code using:
isCorrectCredentials=true;
that the login info was true and you are successfully logged in.
and the part of code that should be executed if the login info is not true will be executed 1 time max.
I have a php file stored remotely. It uses post to take 2 variables, "username" and "password", which will then echo either Valid or Invalid depending on it's existence in my database. I currently use this with my android application to log users in.
I would like to use this same script for logging into my website that I am building. I need to be able to pass 2 variables that I have obtained from an HTML form to a javascript function which will take the variables, run them though the php query, read the echoed output and decide to return true or false to the form. Below is the code I currently have for the script
Javascript code:
<script type="text/javascript">
function Login(){
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
if (username == "" || password == "") {
alert ("Please fill in username and password fields");
return false;
}
$.post("my_query_url.php",{username:username, password:password}, function(data) {
if (data.toLowerCase == "valid")
return true;
else
return false;
});
}
</script>
HTML form:
<form action="Main.html" method="post" onsubmit=" return Login();">
Username: <br>
<input type="text" name="username" id="username"><br>
Password: <br>
<input type="password" name="password" id="password"><br><br>
<input type="submit" value="Login">
</form>
Currently, it always sends the user to my Main.html page with any non-empty username/password input.
I'm not very well versed in these two languages, but I need to learn quickly as they are important for my Senior Project class semester, and especially these next two weeks. Is this possible to do with Javascript and HTML only? Some pointers will be much appreciated! Thank you!
You actually are almost all the way there. You just need to return false from your Login function to prevent the default action of the form from triggering (which is to redirect to main.html). Then, instead of relying on the form to redirect the user, you will need to do so yourself via javascript.
<script type="text/javascript">
function Login(){
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
if (username == "" || password == "") {
alert ("Please fill in username and password fields");
return false;
}
$.post("my_query_url.php",{username:username, password:password}, function(data) {
if (data.toLowerCase() === "valid")
window.location.href = "./Main.html"; //redirect the user
else
return false;
});
return false
}
</script>
I have a javascript file within my website how can I store the code in a separate file on the same server but it still activates with the password function the code is
<script>
function passWord() {
var testV = 1;
var pass1 = prompt('Please Enter Your School Code',' ');
while (testV < 3) {
if (!pass1)
history.go(-1);
if (pass1.toLowerCase() == "0000") {
window.open('Discussion.html','_self')
break;
}
testV+=1;
var pass1 =
prompt('Access Denied - Password Incorrect, Please Try Again.','Password');
}
if (pass1.toLowerCase()!="password" & testV ==3)
history.go(-1);
return " ";
}
It runs with
<input type="button" value="Enter page" onClick="passWord()">
No matter how you store the password, it will always be accessible to the client if you send it to the client.
That is, you cannot have a secure password verification that is done in JavaScript, short of using a one-way hash function. Even if you did use a one-way hash function, someone could just bypass your JavaScript password verification. Do password verification server-side.
I have two javascript files that I am using to validate an email address.
validate.js:
function checkEmail(userEmail) {
var email = userEmail
var emailFilter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (emailFilter.test(email.value)) {
//alert('Please provide a valid email address');
//email.focus;
return true;
}
else{
return false
}
}
navigation.js EDIT:
$(document).ready(function() {
//ADDED IMPORTS
var imported = document.createElement('script');
imported.src = 'lib/validation.js';
document.head.appendChild(imported);
console.log("DOCUMENT IS READY!");
var viewsWrapper = $("#views-wrapper");
var loginButton = $("#login-button");
var registerButton = $("#register-button");
// Login Link
// TODO: Unclear if needed
$("ul li.login").click(function() {
$.get('/login', function(data) {
viewsWrapper.html(data);
});
});
$('#usernamefield').blur(function() {
var sEmail = $('#usernamefield').val();
if ($.trim(sEmail).length == 0) {
alert('Please enter valid email address');
e.preventDefault();
}
if (checkEmail(sEmail)) {
alert('Email is valid');
}
else {
alert('Invalid Email Address');
e.preventDefault();
}
});
...(more code follows but not relevant)
I am also using this jade template:
login.jade:
form(action="")
key EMAIL
input(type="text", name="username", id="usernamefield")
p hello world
br
key PASSWORD
input(type="text", name="password", id="passwordfield")
p hello world
br
input(type="submit", name="loginButton", id="login-button", value="LOGIN")
My issue is that when I input something into my email field, I do not get an alert message in any case. Am I allowed to just have to separate javascript files and call the methods I defined in validate.js within navigation.js? I tried putting the validate.js code in navigation.js, but even then it did not work. I would like to keep the files separate. Am I missing something obvious? I want it so that once the user inputs the email, and leaves the field, a message should appear warning if the email is valid or not.
Your help is appreciated.
Is it the blur Event or the checkEmail the problem? try to put a alert() or console.log() just after your blur (and make sure to lose focus on your input). Seperate file shouldn't be a problem. And also have you check for errors in your console ?
JavaScript string has no "value" field
After
var sEmail = $('#username').val();
sEmail becomes a string.
You are passing this string to checkEmail method and try to get "value" from a string:
if(!emailFilter.test(email.value)) {//...}
Replace to
if (!emailFilter.test(email)) {//...}
You are already sending the value of email into checkemail function. So in checkEmail function in validate.js remove email.value in second line of function checkEmail
function checkEmail(userEmail) {
var email = userEmail
var emailFilter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!emailFilter.test(email)) {
//alert('Please provide a valid email address');
email.focus;
return false;
}
}