Compare if password is correct

3

How to create a simple JavaScript that only asks the user to enter the password 1234 so that the message released appears, if it fails 3 times to appear blocked account.

My code so far:

var senha; 
var senha=1234;
senha=parseFloat(prompt("Entre com sua senha: ")); 

if(senha=senha==1234){ 
   document.write("Acesso Liberado"); 
}
    
asked by anonymous 16.12.2018 / 13:09

4 answers

2

It does not make sense to do this in real code because it does not give any security but it's very simple to do this:

if (prompt("Entre com sua senha: ") == "1234") document.write("Acesso Liberado");

A password is descriptive and therefore should be a text and not a number, it does not make sense to turn it into number. You just have to make a comparison, you do not have to give anything away. It does not even need a variable in this case. And even if you needed it, it does not make sense to create the way you created it. Try to simplify your code. And do not use anything you do not know why you are using it. In this case you used 6 things without need.

To block the account when you miss 3 times:

function validaSenha() {
    var erros = 0;
    while (true) {
        if (prompt("Entre com sua senha: ") == "1234") {
            document.write("Acesso Liberado");
            break;
        } else if (++erros == 3) {
            document.write("Conta bloqueada");
            return;
        } 
    }
    //aqui faz algo para o caso da liberação
}
validaSenha();
    
16.12.2018 / 13:31
1

As the @Maniero already mentioned:

  

It does not make sense to do this in real code because it does not give any security

But taking it as an exercise, you can do it like this:

errou = 0;
while (errou <= 3) {
		if (errou == 3) {
    		document.write('Conta bloqueada');
        break;
    } 
    if (prompt('Digite sua senha:') == 1234) {
        document.write('Acesso liberado');
        break;
    } else
        errou++;
}

Respecting the statement:

  

Create a simple javascript that only asks the user to enter the password 1234 so that the password message is displayed, if it fails 3 times to appear blocked account

    
16.12.2018 / 15:24
0

You can do this exercise as well if you want to:

  

If you enter the password 3 times wrong the blocked account message is shown, otherwise the Free access message will be displayed. >

var btn = document.getElementsByTagName("button")[0];
var p = document.getElementsByTagName("p")[0];
var respostas = [];

function obterSenha() {
  var senhas = prompt("Entre com sua senha: ");
  respostas.push(senhas);

  if (senhas == "1234") {
    p.innerHTML = "Acesso Liberado";
    p.style.backgroundColor = "green";
    p.style.color = "white";
    btn.disabled = true;
  } else if (senhas != "1234" && respostas.length == 3) {
    p.innerHTML = "Conta Bloqueada";
    p.style.backgroundColor = "red";
    p.style.color = "white";
    btn.disabled = true;
  }
}
<button onclick="obterSenha()">Senha</button>
<p></p>
    
16.12.2018 / 14:34
-1

Friend, it is ideal to work with password encryption, so even we developers, who have access to the source code, could not find the password.

One of the safe ways to do this is to use the SHA256 encoding, but calm down, it's very interesting to work with and it's nothing out of this world!

It shuffles the password in a way that can not be decrypted, it is a one-way encryption, it is impossible to get the generated hash (so it calls) and find the original content only with it.

Then you ask "u and what do I want it for?", that's where the interesting part comes in!

You encrypt your password with Sha256 (for example) and it will generate hash (a small text), when the person enters the password on the page, we will encrypt the password that the person typed, generating the hash of that password typed, and we'll get that hash and compare it with the hash of the original password, if the 2 hashs are the same it means that the password placed is the same! And even if you have the hash (which is the case for us developers who know how to access the source code), you can not know the password! Even if you put the hash in place of the password, it would again encrypt the hash and generate a different hash, and when you compare it would not equal your password.

This is basically the method that most secure sites do, maybe they use other methods than Sha256, but the principle is the same, on their server they do not have their password saved, but their hash, so they your privacy, because even if someone has your hash, you can not do much with it. There is also how to generate thousands of possibilities and the hash of each to see if it is equal to your hash, but this is very time consuming, and even with powerful computers it can take days or even weeks (if not months or years) until you find your password , but until then the server has already blocked access after so many attempts.

I made an example of how to use this in an HTML page, the code is very simple, I commented every line to be very easy to understand, so it's a bit big, I'll put here:

<!-- Chama a biblioteca Crypto-JS 3.1.2 da Google -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/sha256.js"></script><script>//COMOCOLOCARSENHA////-Abraestesite://https://www.xorbin.com/tools/sha256-hash-calculator//-Coloquesuasenhadentrodaárea"Data"
// -Clique em "Calculate SHA256 hash"
// -Copie o "SHA-256 hash"
// -coloque na váriavel "SenhaOriginalCodificada" abaixo
// 
// OBS: A senha atual é "asd", não coloque a senha final aqui como eu fiz
var SenhaOriginalCodificada = "688787d8ff144c502c7f5cffaafe2cc588d86079f9de88304c26b0cb99ce91c6";

//Pergunta a senha
var SenhaDigitada = prompt("Digite a senha");

//Codifica a senha digitada
var SenhaDigitadaCodificada  = CryptoJS.SHA256(SenhaDigitada);

//Se a SenhaDigitadaCodificada for igual a SenhaOriginalCodificada
if(SenhaDigitadaCodificada == SenhaOriginalCodificada)
	
	//Se estiver certa
	{
		//mostra um alerta
		alert("acerto mizeravi");
	}
	
	else
	
	//Se estiver errada
	{
		//mostra um alerta
		alert("errrrrrrroooo, vai pro google vai..");
		//redireciona para outra página
		window.location.href = "http://www.google.com";
	}
</script>


<b>Pagina normal</b>

For you to put use of 3 attempts and then wait some time, it gets much more complex, then you would have to use those famous cookies (I used the HTML5 version of them, call localStorage ), and save the blocking information in the browser, and do the part of the count and the time that the person can try again, it's quite complex, but I I also did, it's basically the same thing as the above code, but with some additions, here it is:

<!-- Chama a biblioteca Crypto-JS 3.1.2 da Google -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/sha256.js"></script><script>//COMOCOLOCARSENHA////-Abraestesite://https://www.xorbin.com/tools/sha256-hash-calculator//-Coloquesuasenhadentrodaárea"Data"
// -Clique em "Calculate SHA256 hash"
// -Copie o "SHA-256 hash"
// -coloque na váriavel "SenhaOriginalCodificada" abaixo
// 
// OBS: A senha atual é "asd", não coloque a senha final aqui como eu fiz
var SenhaOriginalCodificada = "688787d8ff144c502c7f5cffaafe2cc588d86079f9de88304c26b0cb99ce91c6";



/*Modelo de ERROS*/
	//Quantidade de erros permitida
	var QntErros = 3;
	//Se não tem qntErros cria no localStorage
	if (!localStorage.QntErros) {
	  localStorage.QntErros = QntErros;
	}
	//Quantia de horas a bloquear a pessoa depois de consumir todos os erros permitidos
	var HorasPenalidade = 1;
	
	//Se não tem dataPermitida anterior salvas, salva 1 segundo atras no localStorage
	if (!localStorage.dataPermitida) {
	  localStorage.dataPermitida = Date.parse(new Date())-1;
	}
	//Pega a data atual
	var DataAtual = Date.parse(new Date());
	//Pega a dataPermitida no localStorage
	var DataPermitida = parseInt(localStorage.dataPermitida);
/* modelo de ERROS*/



//Pergunta a senha
var SenhaDigitada = "";
if(DataAtual >= DataPermitida){
	SenhaDigitada = prompt("Digite a senha");
}

//Codifica a senha digitada
var SenhaDigitadaCodificada  = CryptoJS.SHA256(SenhaDigitada);

//Se a SenhaDigitadaCodificada for igual a SenhaOriginalCodificada E a dataAtual for maior ou igual a Permitida
if(SenhaDigitadaCodificada == SenhaOriginalCodificada && DataAtual >= DataPermitida)
	
	//Se estiver certa
	{
		//mostra um alerta
		alert("acerto mizeravi");
		//Reseta os erros
		localStorage.QntErros = QntErros;
	}
	
	//Se a dataPermitida estiver a frente da atual
	else if (DataAtual < DataPermitida){
		let date = new Date(parseInt(localStorage.dataPermitida));
		let month = date.getMonth();
		let day = date.getDate();
		let year = date.getFullYear();
		let hour= date.getHours();
		let min= date.getMinutes();
		let sec= date.getSeconds();
		let allDate = hour+":"+min+":"+sec+" "+day+"/"+month+"/"+year
		alert("Ixe amigo, só poderá tentar novamente em "+allDate);
		//redireciona para outra página
		window.location.href = "http://www.google.com";
	}
	
	
	//Se acabaram os erros, agora só permite depois das horas de penalidade estabelecidas
	else if(localStorage.QntErros <= 1){
		//Reseta os erros
		localStorage.QntErros = 0;
		//Coloca o tempo de penalidade
		//localStorage.dataPermitida = Date.parse(new Date())+60*1000;
		localStorage.dataPermitida = Date.parse(new Date())+60*60*1000*HorasPenalidade;
		//redireciona para outra página
		window.location.href = "http://www.google.com";
		alert("Ixe amigo, você nao pode mais tentar durante um tempo");
	}
	
	
	else
	
	//Se estiver errada
	{
		//contabiliza o erro
		localStorage.QntErros = parseInt(localStorage.QntErros)-1;
		//mostra um alerta
		alert("errrrrrrroooo, você só tem mais "+localStorage.QntErros+" tentativas");
		//redireciona para outra página
		window.location.href = "http://www.google.com";
	}
	
	
</script>


<b>Pagina normal</b>

Search on these terms, it's a very interesting area!

I hope I have helped!

    
17.12.2018 / 01:48