HTML pages still accessible without login - javascript

I am building a site on Glitch.com for me and my friends. I already know HTML/CSS, and am learning JS.
Even though it's not that secure, I want the login system to be made out of JS since this project is just for fun and to improve my skills.
I currently have the login page with HTML/CSS, and wrote a few JS if statements for the login validation. I want the users who are logged in successfully to be redirected to another page, home.html.
However, I can still access home.html by just inserting /home.html to the end of the link, not requiring sign in. How do I fix this?
HTML code for login:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Login for Access</title>
<link rel="stylesheet" href="/login.css">
<script src="/login.js" defer></script>
</head>
<body>
<h1>Login for Access</h1>
<p id = "access-denied">Incorrect User ID/Password</p>
<form id = "login-form">
<label for="user_id">User ID:</label>
<input type="number" id="user_id" name="user_id" required><br><br>
<label for="pwd">Password:</label>
<input type="password" id="pwd" name="pwd" required><br><br>
<input type="submit" value= "Submit" id = "login-submit">
</form>
</body>
</html>
JS code:
const loginForm = document.getElementById("login-form");
const loginButton = document.getElementById("login-submit");
const loginErrorMsg = document.getElementById("access-denied");
loginButton.addEventListener("click", (e) => {
e.preventDefault();
const user_id = loginForm.user_id.value;
const password = loginForm.pwd.value;
if (user_id === "id" && password === "pass") {
window.location.href="home.html";
} else {
loginErrorMsg.style.opacity = 1;
}
})
Sorry if anything is unclear. It would be greatly appreciated if someone could edit this for more clarity.

You can't use client-side code to stop people accessing pages. Client-side code is ultimately under the console of the owner of the browser.
Authentication/Authorisation has to be done server-side.

Related

how can i protect my index.html website by js so i can only open it on my pc?

i want to make my local static html website password protected with some js, so that when i open my local html file in my pc, it comes with a form to fill up my user id and my own password, which i have saved and when i hit enter that should open my index.html file only when password is correct.
currently my code is
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<Form>
<!-- user-id -->
<input type="text">
<!-- user-password -->
<input type="password">
<button onclick="window.open('./index.html')"> Enter
</button>
</Form>
<script>
// pls-help-me-idk-how-to-code-js
</script>
</body>
</html> ``
Its not a proper way to do it. You need a backend for that inorder to properly execute that. But if it just to play around you can have an alert box and just compare their value : if right it displays.
First, you have to add an id or a class to that inputs in order to select them within the script section. Afterward, you can select them and add any value you want.
Such as:
<form>
<!-- user-id -->
<input id="user" type="text" />
<!-- user-password -->
<input id="pass" type="password" />
<button onclick="window.open('./index.html')">Enter</button>
</form>
<script>
document.getElementById("user").value = "UsernameOrId";
document.getElementById("pass").value = "SomePassword";
</script>
In order to compare, you should get the right password from somewhere like a database or some service, but since this is purely for learning purposes you can hardcode it in the script for checking. So, the final solution can be similar to this:
<body>
<form>
<!-- user-id -->
<input id="user" type="text" />
<!-- user-password -->
<input id="pass" type="password" />
<button id="btn">Enter</button>
</form>
<script>
const myPass = "SomePassword";
document.getElementById("user").value = "UsernameOrId"; // predefining the value simulating is saved and by default filled up
document.getElementById("pass").value = myPass; // predefining the value simulating is saved and by default filled up
const btn = document.getElementById("btn"); // getting the button to control its behavior on click event
btn.addEventListener("click", function () {
const passWhenClickingTheBtn = document.getElementById("pass").value;
if (myPass === passWhenClickingTheBtn) { // checking the value entered for pass
window.open("./index.html");
}
});
</script>

Im new with call api , can someone help me with this . Call Api link shortener with javascript

So I have a mission is call api to this website : https://shrtco.de/ and using link shortener like them. But I don't know how to call it . Can someone explain how to call this or maybe help me , thank you guys so much
This is my HTML code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<p>Enter a link</p>
<input type="text">
<button>Enter</button> <br>
<p>Short domain</p>
<input type="radio" id="domain1" name="fav_language" value="domain1">
<label for="html">shrtco.de</label><br>
<input type="radio" id="css" name="fav_language" value="CSS">
<label for="css">9qr.de</label><br>
<input type="radio" id="javascript" name="fav_language" value="JavaScript">
<label for="javascript">shiny.link</label>
<p>Link generated</p>
ZZZZZ
</div>
<script src="getAPI.js"></script>
</body>
</html>
Following the example from the interface documentation, I have programmed a minimal illustrative example here.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>shortcode example</title>
</head>
<body>
<input type="text" name="url" id="url" value="" required>
<button id="submit" type="submit">shorten</button>
<p id="result"></p>
<script>
const button = document.querySelector('button');
const input = document.querySelector('input');
const result = document.getElementById('result');
const shorten = (event) => {
let value = input.value.trim();
while (result.firstChild) {
result.removeChild(result.firstChild);
}
if (!value.length) {
throw new Error('well! you have to type in something!');
}
let promise = fetch('https://api.shrtco.de/v2/shorten?url=' + value);
promise.then(response => {
if (response.status !== 201) {
console.log('Looks like there was a problem: ' + response.status);
return;
}
response.json().then(data => {
let link = document.createTextNode(data.result.full_short_link);
result.appendChild(link);
}).catch(error => {
console.log(error.message);
})
});
}
button.addEventListener('click', shorten, false);
</script>
</body>
</html>
What is happening in this example?
First there are three elements - an input element for typing in the url to shorten, a button element for submitting the data and a paragraph for displaying the results of the api call.
The submit button gets an javascript event listener, that handles click events. Everytime you click on that button, the input element will be checked, if something was typed in. If the value of the input element has a length, it will be send to the shortening service. For that reason we produce a promise with the javascript fetch api.
The call with the fetch api returns a javascript promise, which we check for the response status code. The api returns a 201 "Created" status code, that says everything is alright. The api needs a little time for the response, but then we can decode the json response and print out the shortened link in the result paragraph.
What you should do
Try to understand the given example. Please read the interface documentation to get informations about what could be returned in a success case and whats happening when the request fails? The javascript fetch api is elemental for that.
Try to transfer the given example to your application. If you encounter problems, explain these problems in detail and ask for a solution.

How do you make a submit button redirect to another page after the user has inputted the correct password?

could you please help me find out what's wrong? After login, it is supposed to redirect you to another page, but nothing happens. The user name is: Joshua and the password is: Joshua#123.
<html>
<head>
<title>Login: MessengerX</title>
<link rel="stylesheet" type="text/css" href="C:\Users\Tania\Documents\Website\style.css">
<meta charset="UTF-8">
<meta name="description" content="HTML website called MessengerX. Send messages to anyone who has logged in.">
<meta name="author" content="Joshua Hurley">
<meta name="keywords" content="HTML, MessengerX, Joshua Hurley, Website, Supremefilms">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/style.css" />
<script type="text/javascript">
var attempt = 3; // Variable to count number of attempts.
// Below function Executes on click of login button.
function validate() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username == "Joshua" && password == "Joshua#123") {
alert("Login successfully");
location.replace("www.youtube.com"); // Redirecting to other page.
} else {
attempt--; // Decrementing by one.
alert("You have " + attempt + " attempt left;");
// Disabling fields after 3 attempts.
if (attempt == 0) {
document.getElementById("username").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
}
}
</script>
<script src="js/login.js"></script>
</head>
<body>
<div class="imgcontainer">
<img src="C:\Users\Tania\Documents\Website\Screenshots\face.jpg" height="500" alt="Avatar" class="avatar">
</div>
<div class="container">
<div class="main">
<h1 style="color:"><b><i>Login: MessengerX</i></b></h1>
<form id="form_id" method="post" name="myform">
<label>User Name :</label>
<input type="text" name="username" id="username" />
<label>Password :</label>
<input type="password" name="password" id="password" />
<button type="submit" value="Login" id="submit" onclick="validate()" />
</form>
<b><i>Submit</i></b>
</div>
</div>
</body>
</html>
Try this:
window.location.replace("https://www.youtube.com")
You can move code inside window.addEventListener('load' or you can move script after dom at the end
Suggestion: use the entire URL with HTTP or HTTPS.
location.replace("https://www.youtube.com");
<script type="text/javascript">
window.addEventListener('load', (event) => {
var attempt = 3; // Variable to count number of attempts.
/// code here
});
</script>
As leonardofmed mentioned, better place your script just befor </body> closing tag,
because you need to load html first, so script can see elements, otherwise at it's start there is no elements yet, so this will cause error, as for redirecting you can use:
// Simulate a mouse click:
window.location.href = "http://www.w3schools.com";
// Simulate an HTTP redirect:
window.location.replace("http://www.w3schools.com");
use <form><button type="button" ... instead
<form><button type="submit" ... has its own logic ("magic"), which is doing the problem.
use protocol in url location.replace("https://www.youtube.com"), otherwise it's relative path
BTW never validate password on client!!!

How to disable HTML/JavaScript form if JavaScript is disabled in browser

First off the bat I am new to this an really trying my best to understand how this works. I have the following simple login form that leads to a homepage if the right login credentials are submitted. However when run in Firefox with JavaScript disabled the login credentials are ignored and my homepage is displayed anyway no matter what login details I provide. I have created a message in between <noscript></noscript> which fires when JavaScript is disabled. What I would like to achieve is that the warning message displays only and that the form etc. is disabled and not displayed until the login page is reloaded with JavaScript enabled. Can someone please help me with this? It is much appreciated!! My code is
<!doctype html>
<!-- This is is the main start page saved in index.html -->
<html lang="en-US">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body>
<h2>Login details</h2>
<noscript>
<h3>Before you login</h3>
<p>JavaScript needs to run for this site to work properly.<br />
Please activate JavaScript in your browser<br />
and reload this page to login.
</p>
</noscript>
<form id="myForm" name="login" onsubmit="return validateFormOnSubmit()" action="http://localhost:8080/index.html" method="post">
<fieldset>
<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">
</fieldset>
</form>
</body>
</html>
<script>
function validateFormOnSubmit() {
var un = document.login.username.value;
var pw = document.login.password.value;
var username = "username"
var password = "password"
if ((un == username) && (pw == password)) {
return true;
}
else {
alert ("Login was unsuccessful, please check your username and password");
return false;
}
}
</script>
You can achieve this without adding extra JavaScript. You can use a <noscript> tag also in the <head>, so you are able to hide this with CSS:
…
<head>
…
<noscript>
<style>
#myForm {
display: none
}
</style>
</noscript>
</head>
…

Cannot set property innerHTML error

I am trying to automate the process of opening an external site from a button of an internal site that I created, but I can not reference the document I created, follow the code below, tried several times and could not, any help is valid, thank you so much.
<!DOCTYPE html>
<head>
<title>Principal</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="\\fswcorp\ceic\ssoa\gaacc\System\JQuery\jquery-3.2.1.min.js"></script>
<script src="\\fswcorp\ceic\ssoa\gaacc\System\jQueryMask\dist\jquery.mask.min.js"></script>
<script src="\\fswcorp\ceic\ssoa\gaacc\System\jQueryUI\jquery-ui.js"></script>
<script>
$(document).ready(function() {
$("#dateBegin").mask('00/00/0000');
$("#dateEnd").mask('00/00/0000');
$("#buttonDownloadBRScan").click(function() {
$windowopen = window.open();
$windowopen.location.href = "https://www.fdibr.com.br/autenticacao/autenticacao/login";
$test = $windowopen.document.getElementById("usuario").innerHTML = "7478704";
})
});
</script>
</head>
<body>
<div class="dataInput">
<label id="labelDateBegin">Data Inicial</label>
<input id="dateBegin" type="date" />
<label id="labelDateEnd">Data Final</label>
<input id="dateEnd" type="date" />
</div>
<br><br>
<button id="buttonDownload">Download</button>
<button id="buttonDownloadBRScan">Download BRScan</button>
</body>
Assuming you have access to that domain in the window you're opening (same origin policy), you have to wait for the window to finish opening first before accessing elements inside.
$("#buttonDownloadBRScan").click(function(){
const w = window.open('https://www.fdibr.com.br/autenticacao/autenticacao/login');
w.addEventListener('DOMContentLoaded', () => {
w.document.getElementById("usuario").innerHTML = "7478704";
});
})
Try something like this:
<input id="yourID" type="button" onclick="open_page()" value="Your Message Here"/>
<script>
function open_page () {
window.open('Your Webpage');
}
</script>
the external site and your internal site have different domain,you can't modify the external site content from your internal site directly.you can use window.postMessage,maybe it would resolve your problem

Categories

Resources