Hello I am developing an OTP device verification system.
How does it works:
user enters his credentials, like phone number and password and after that ajax calls /signin
function from backend which verifies the credentials and along with that checks if user device is trusted or not.If user device is trusted , it simply returns to dashboard, it not trusted it return str(0)
and if credentials are wrong then str(2)
.
What I wanna do is javaScript should handle these backend returned values and do something like, if device is not trusted then OTP field appears and mobile, password screens hides, and if returned value is 2, then it simply displays the flash MSG of input credentials and render index.html template
Here is my code
<div id="signin" tabindex="-1" role="dialog"
aria-labelledby="myExtraLargeModalLabel" aria-modal="true">
<div >
<div >
<a href="#" data-dismiss="modal">✖</a>
<div >
<h2> Sign In to your Account </h2>
<div >
<form method="POST" action="/signin">
<div >
<div >
<div >
<input id="lmobileno" placeholder="Mobile Number" type="number" required
name="lmobileno">
<span for="lmobileno">Mobile Number</span>
</div>
</div>
</div>
<div >
<div >
<div >
<input id="password" placeholder="Password" type="password" required
name="password">
<span for="password">Password</span>
</div>
</div>
</div>
<div id="row_otp">
<div data-wow-delay="0.3s">
<div >
<input placeholder="OTP" id="otp" onchange="validateOTP()" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
maxlength="6" type="number" name="otp" pattern="^[0-9]{6,6}$" title="Enter OTP sent to you on your above given mobile number">
<label id="label_otp" for="otp">OTP</label>
<input id="otpbtn" type="button" value="Didn't Receive an OTP? Click Here to Resend" onclick="resendFinjaOTP('mobileno',null);"/>
<div><span id="time"></span></div>
</div>
</div>
</div>
<div >
<div >
<button type="submit" onclick="$('#overlay').fadeIn();" > Sign In </button>
<p> Don't have an account? <a href="/investor_sign_up#register"> Sign Up </a>
</p>
<p> Or <a href="/finja_sign_up">Sign Up </a> using your <a href="/finja_sign_up"> <img
src="https://finja.pk/assets/images/logo.svg" width="9%"> </a> account </p>
<p> <a href="/reset_password"> Forgot Password? </a> </p>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>
<script src="../static/assets/js/header.js"></script>
<script>
$('#signin').ready(function(){
$('#otp').hide();
$('#otpbtn').hide();
$('#label_otp').hide();
});
function validatePassword() {
var mobile = $('#lmobileno').val();
var password = $('#password').val();
if (mobileno != 0 && password !=0) {
$('#overlay').fadeIn();
$.ajax({
type: "POST",
url: "/signin",
data : {lmobileno: mobile, password: password},
}).done(function (data) {
$('#overlay').fadeOut();
if (data == 0) {
$('#otp').show();
$('#lmobileno').hide();
$('#password').hide();
}
else if (data == 2) {
Swal.fire({
icon: 'error',
title: 'INVALID PASSWORD OR MOBILE NUMBER',
text: 'Sign in again',
width: 500,
showConfirmButton: false,
showCloseButton: true
})
}
});
}
};
function validateOTP() {
const label_otp = document.getElementById('label_otp');
const row_mobileno = document.getElementById('row_mobileno');
const row_otp = document.getElementById('row_otp');
var str = document.forms["Form"]["otp"].value;
var n = str.length;
var otp = { otp: str };
if (n == 6) {
$('#overlay').fadeIn();
$.ajax({
type: "POST",
url: "/verify_otp",
contentType: 'application/json',
data: JSON.stringify(otp),
dataType: 'json'
}).done(function (data) {
$('#overlay').fadeOut();
if (data == 1) {
Swal.fire({
icon: 'success',
title: 'OTP Verified Successfully',
text: 'You can proceed to signup now',
width: 500,
showConfirmButton: false,
showCloseButton: true
})
}
else if (data == 0) {
Swal.fire({
icon: 'error',
title: 'INVALID OTP',
text: 'Enter the OTP sent to you on your phone',
width: 500,
showConfirmButton: false,
showCloseButton: true
})
}
});
}
};
</script>
backend code for signin
@accounts_blueprint.route('/signin', methods=['POST'])
@limiter.limit('10 per minute')
def signin_post():
mobileno = format_mobileno(request.form.get('lmobileno'))
password = request.form.get('password')
# retrieve user's data from database's user table
existing_user = sessiondb.query(User).filter(User.mobileno == mobileno).first()
# validate user's mobile number and password
if existing_user is None:
flash('Invalid Mobileno.', 'signin')
return redirect(url_for('main.index'))
elif existing_user.state.name != State.Active.name or existing_user.status.name != Status.Verified.name:
flash('Account is not verified yet.', 'notVerified')
return redirect(url_for('main.index'))
elif Hash.verify_password(existing_user.password, password):
user = sessiondb.query(User).filter(User.mobileno==mobileno).first()
verifyDevice = device_verified(user)
if verifyDevice == str(1):
login_user(existing_user)
add_last_login()
add_investor_status()
return redirect(url_for('dashboard_blueprint.dashboard'))
else:
return str(0)
else:
return str(2)
I am very new to javascript and ajax, I am getting a white screen with zero and two written on it.
CodePudding user response:
First remove that form tags in sign-in form and then replace the javascript function with this
function ValidatePassword() {
var mobileno = $('#lmobileno').val();
var password = $('#password').val();
if (validate_mobile(mobileno)==true && password != null) {
$('#overlay').fadeIn();
$.ajax({
type: "POST",
url: "/signin",
contentType: 'application/json',
data: JSON.stringify({
"lmobileno": mobileno,
"password": password
}),
dataType: 'json'
}).done(function (data) {
$('#overlay').fadeOut();
if (data == 1) {
$('#otp').show();
$('#lmobileno').hide();
$('#password').hide();
}
else if(data==2) {
$('#overlay').fadeOut();
Swal.fire({
icon: 'error',
title: 'Invalid password or phone number',
text: 'Sign in again',
width: 500,
showConfirmButton: false,
showCloseButton: true
})
}
});
}
};
CodePudding user response:
I believe you are using python-flask therefore, Use jsonify instead of returning directly.
from flask import jsonify # import this in top
Then
return jsonify({"msg": "0"}) # do same for 1 and 2 as well
Now on frontend read it like that
if(data.msg == 0)