How do i encrypt password before send to php script? - javascript

I want to send the password encrypted to the server side script, and after match the pasword encrypted with the password on the database, if the passords match, redirect the user to the home page.
My Jquery function:
jQuery('#login_form').submit(function(){
var form_data = new FormData();
form_data.append('login', $('#lg-user').val());
form_data.append('password', CryptoJS.MD5($('#lg-password').val()));
jQuery.ajax({
type: "POST",
url: "processa.php",
data: dados,
success: function( data )
{
alert( data );
}
});
return false;
});
The form:
<form action="" id="login_form" method="post">
<?php
session_start();
if (isset($_SESSION['message']))
{
echo $_SESSION['message'];
unset($_SESSION['message']);
}
?>
<div class="input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text"></span>
</div>
<input type="text" name="username" class="form-control"
placeholder="usuario">
</div>
<div class="input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text"></span>
</div>
<input type="password" name="password" class="form-control"
placeholder="senha">
</div>
<div class="col-md-12">
<div class="text-center">
<input type="submit" value="Entrar" class="btn login_btn">
</div>
</div>
</form>
The problem is that everytime i send the form, the page reload.

Your approach is highly insecure.
By encrypting it client-side and matching what it sent with the DB, you are sending the data that "proves" the user is who they say they are to the server, so if someone were to get hold the database they would know what to send.
Also, MD5 is far too weak to secure a password today.
To keep the password safe in transmission to the server: Use HTTPS.
To keep the passwords in your database safe: hash them server-side as described in the Safe Password Hashing FAQ in the PHP manual.
To stop the regular form submission when you use the submit event to intercept it and use Ajax:
Capture the event object
Call preventDefault on it
Such:
jQuery('#login_form').submit(function(e){
e.preventDefault()

Related

custom error message shows and disappears on submit

I am using flask, html, css and javascript. So what I did was enter a error message in my login form as a new and set display: none. I validate the input credential by comparing values from a SQLite database i set previously. This validation is done inside the flask. When the form is submitted, it is validated inside the flask, however I created a javascript that changes the styling for the error message to display: block. This would show the error message for incorrect fields and the correct input users will be redirected to a new page and hence they wont see the error.
So I was hoping that the error message shows after the form is submitted for the login and the users that key in the right information will be redirected.
Flask:
#app.route('/', methods=['POST', 'GET'])
def tutor_login():
tutor_login_form = LoginAccount(request.form)
if request.method == 'POST' and tutor_login_form.validate():
session.pop('user', None)
admin_account = Admin.query.all()
tutor_account = Tutor.query.all()
for i in admin_account:
admin_id = i.admin_id_num
for j in tutor_account:
tutor_id = j.tutor_id_num
if admin_id == tutor_login_form.id_num.data:
admin_info = Admin.query.filter_by(admin_id_num=tutor_login_form.id_num.data).first()
admin_pass = admin_info.admin_password
if admin_pass == tutor_login_form.password.data:
session['user'] = tutor_login_form.id_num.data
return redirect(url_for('admin_main'))
elif tutor_id == tutor_login_form.id_num.data:
tutor_info = Tutor.query.filter_by(id_num=tutor_login_form.id_num.data).first()
tutor_pass = tutor_info.tutor_password
if tutor_pass == tutor_login_form.password.data:
session['user'] = tutor_login_form.id_num.data
return redirect(url_for('retrieve_tutor_account'))
return render_template('tutorlogin.html')
HTML:
<form class="" action="" method="POST" onsubmit="validate()">
<!-- Input fields -->
<div class="form-group mt-3">
<label for="id_num">Enter Tutor ID:</label>
<input type="text" class="form-control" id="id_num" placeholder="Enter Tutor ID" name="id_num">
</div>
<div class="form-group my-3">
<label for="password">Enter Password:</label>
<input type="password" class="form-control password" id="password" placeholder="Enter Password" name="password">
</div>
<div class="mb-3 text-center" id="error">
ID or Password entered is invalid! Please try again.
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary btn-customized">Login</button>
</div>
<div>
<p class="text-center my-3">Forgot your password? <br> Click here to reset</p>
</div>
</form>
Javascript:
<script>
var error = document.getElementById('error');
function validate(){
error.style.display = "block";
}
</script>
If you want to validate the credentials without a page reload, you need to use Ajax requests.
Where on clicking Submit, the JavaScript will first check if all fields all valid and filled and then send an Ajax request to the Flask app.
Depending on the response of the query you can either show a error message or redirect user to the page you want.
Here's a YouTube video for reference - https://www.youtube.com/watch?v=UmC26YXExJ4

button type submit refreshes page instead of triggering ajax network request [duplicate]

Alright, I have a simple form comprising of only a text field. Data written in the text field is stored in DB when we hit submit (Stored via ajax). The ajax works fine and data is submitted, however, the page get's refreshed automatically and the URL contains the content of the input field.
My Form :-
<form class="form-horizontal">
<fieldset>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="message"></label>
<div class="col-md-5">
<input id="message" name="message" type="text" placeholder="message" class="form-control input-md" required="">
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="submit_message"></label>
<div class="col-md-4">
<button id="submit_message" name="submit_message" class="btn btn-success">Enter</button>
</div>
</div>
</fieldset>
</form>
Ajax :-
$("#submit_message").click(function() {
var message = $("#message").val();
$.ajax({
type: "POST",
url: "ajax_getter.php?requestid=2",
data: { message: message, c: c },
dataType: "html"
}).done(function( msg ) {
//load_content();
alert(msg);
});
});
PHP :-
//...
if($chat->insert("chat_threads", $arr))
{
echo 1;
}
else
{
echo 0;
}
After the result is show in the popup, the page refresh and the URL becomes something like :- chat.php?message=454545&submit_message=
Why is the page being refreshed ?
Seems that your form is being submitted. Try preventing the default event (i.e. submission):
$("#submit_message").click(function(e) {
e.preventDefault(); // This prevents form from being sumbitted
// the rest of your code
});

Laravel timeout on auth login

Laravel 5.3 - My goal is to send login form via ajax to login controller (AuthenticatesUsers trait), and to get a response (json would be ok), so i could set timeout before redirect to "dashboard" section (authenticated). I need that timeout for some frontend stuff.
So could it be done? If it could, hint would suffice.
Thanks in advance.
Javascript example:
$("#login-form").submit(function (e) {
var url = "/login"; // the script where you handle the form input.
$.ajax({
type: "POST",
cache : false,
url: url,
data: $("#login-form").serialize(), // serializes the form's elements.
success: function ()
{ //Do the timeout part, then redirect
topbar.addClass('success');
form.addClass('goAway');
article.addClass('active');
tries = 0;
},
error: function () {
location.reload();
input.addClass('disabled');
topbar.addClass('error');
}
});});
Login form is sent via post, and i would like to do a redirect by myself, not via controller, and my main concern is the csrf token on javascript redirect would change.
edit:
Another thing that I discovered is including token inside ajax setup:
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': _token}
});
and prevent form default action:
$("#login-form").submit(function (e) {
e.preventDefault();
Here's my login form (all js and css is included in parent view):
#extends('layouts.app')
#section('content')
<form class="form form-horizontal" id="login-form" role="form" method="POST" action="{{ url('/login') }}">
{{ csrf_field() }}
<div class="forceColor"></div>
<div id="logosm_wrapper">
<img id="logosm_login" src="img/ipism_100x50.png" alt="logo" >
</div>
<div class="forceColor"></div>
#if (count($errors))
<div class="topbar error">
#else
<div class="topbar">
#endif
<div class="spanColor"></div>
<input id="email" type="email" class="input form-control" name="email" placeholder="E-mail" value="{{ old('email') }}">
</div>
#if (count($errors))
<div class="topbar error">
#else
<div class="topbar">
#endif
<div class="spanColor"></div>
<input id="password" type="password" class="input form-control" name="password" placeholder="Password"/>
</div>
<button class="submit" id="submit">Login</button>
<!--input class="submit" id="submit" type="submit" value="Login"-->
</form>
#endsection
This is working as intended by Laravel Auth, my intention was to green out input fields on authorisation via JS, and then redirect user to dashboard...
I suggest u add this in your ajax:
$.ajax({
....
async : false,
....

How to validate coupon using Stripe's JavaScript API?

I am using Stripe's API (v2) - https://stripe.com/docs/stripe.js
This is being implemented using Laravel's cashier, a package that ships with Laravel, with docs.
I have a very basic form at the moment, collecting the user's card info, which is then passed over to Stripe who will validate it and return a token. This token is placed in my form and is what I store and use in my system (again, all handled cleanly by Laravel).
I need to use coupons as part of this checkout process. I assumed it would be a simple case of adding the coupon field and Stripe would do the rest, but unfortunately that isn't the case - there is no validation taking place of the coupon when it is entered and the form is submitted.
Processing the coupon after submit is fine, as Laravel handles that.
My question: How can I get Stripe to validate an entered coupon using their JavaScript API?
Below is my form and the accompanying JS:
Form:
<form method="POST" action="/subscribe/individual" accept-charset="UTF-8" class="form-horizontal" role="form" id="subscription-form">
<input name="_token" type="hidden" value="ep1tcaWMRGrPOLSkBCBJQo1USynWW6aTjDh9xN3W">
<div class="payment-errors"></div>
<div id="signupalert" style="display:none" class="alert alert-danger">
<p>Error:</p>
<span></span>
</div>
<div class="form-group">
<label for="ccn" class="col-md-3 control-label">Credit card number</label>
<div class="col-md-9">
<input class="form-control" data-stripe="number" name="ccn" type="text" value="" id="ccn">
</div>
</div>
<div class="form-group">
<label for="expiration" class="col-md-3 control-label">Expiration date</label>
<div class="col-md-6">
<select class="form-control" data-stripe="exp-month" name="month"><option value="1">January</option><option value="2">February</option><option value="3">March</option><option value="4">April</option><option value="5">May</option><option value="6">June</option><option value="7">July</option><option value="8">August</option><option value="9">September</option><option value="10">October</option><option value="11">November</option><option value="12">December</option></select>
</div>
<div class="col-md-3">
<select class="form-control" data-stripe="exp-year" name="year"><option value="2014" selected="selected">2014</option><option value="2015">2015</option><option value="2016">2016</option><option value="2017">2017</option><option value="2018">2018</option><option value="2019">2019</option><option value="2020">2020</option><option value="2021">2021</option><option value="2022">2022</option><option value="2023">2023</option><option value="2024">2024</option><option value="2025">2025</option><option value="2026">2026</option><option value="2027">2027</option><option value="2028">2028</option><option value="2029">2029</option></select>
</div>
</div>
<div class="form-group">
<label for="cvc" class="col-md-3 control-label">CVC number</label>
<div class="col-md-3">
<input class="form-control" data-stripe="cvc" name="cvc" type="text" value="" id="cvc">
</div>
</div>
<div class="form-group">
<label for="coupon" class="col-md-3 control-label">Coupon</label>
<div class="col-md-3">
<input class="form-control" data-stripe="coupon" name="coupon" type="text" value="" id="coupon">
</div>
</div>
<div class="form-group">
<!-- Button -->
<div class="col-md-offset-3 col-md-9">
<button type="submit" id="btn-signup" class="btn btn-info">Sign Up</button>
</div>
</div>
JavaScript:
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<script>
Stripe.setPublishableKey('*** removed ***');
jQuery(function($) {
$('#subscription-form').submit(function(event) {
var $form = $(this);
// Disable the submit button to prevent repeated clicks
$form.find('button').prop('disabled', true);
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from submitting with the default action
return false;
});
});
var stripeResponseHandler = function(status, response) {
var $form = $('#subscription-form');
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
// token contains id, last4, and card type
var token = response.id;
// Insert the token into the form so it gets submitted to the server
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
// and submit
$form.get(0).submit();
}
};
</script>
I'm pretty sure you can't.
I'm validating the coupon via ajax, and make a server side call to Stripe. You can then apply the coupon to any purchase transactions on the server side when you accept the POST.
The solution I found is to
create a coupon on the Stripe dashboard
use the same value for the coupon id and code
Then by calling the coupons retrieve method you get a boolean attribute "valid" in the coupon response returned.
Here's a response example from Stripe Docs:
{
"id": "25_5OFF",
"object": "coupon",
"amount_off": null,
"created": 1617028691,
"currency": "usd",
"duration": "repeating",
"duration_in_months": 3,
"livemode": false,
"max_redemptions": null,
"metadata": {},
"name": "25.5% off",
"percent_off": 25.5,
"redeem_by": null,
"times_redeemed": 0,
"valid": true
}

How Login page is working in Jquery mobile?

I made a login page, i got the jquery code Can anybody explain me this CODE!??
Line by line! so that i know how the hell it is working! i have the code but i dont know how its work.. i am not that good in service integration and stuff
$(document).ready(function() {
$('#loginForm').submit(function() {
$('#output').html('Connecting....');
var postTo = 'login.php';
$.post(postTo,{username: $('[name=username]').val() , password: $('[name=password]').val()} , `
function(data) {
if(data.message) {
$('#output').html(data.message);
} else {
$('#output').html('Could not connect');
}
},'json');
return false;
});
});
`
In my html :
<!-- Start of first page -->
<div data-role="header">
<h1>Foo</h1>
</div><!-- /header -->
<div data-role="content">
<p id="output"></p>
<p>
<form method="post" id="loginForm">
Username: <input type="text" name="username"><br /><br />
Password: <input type="password" name="password"><br />
<input type="submit" value="Login">
</form>
</p>
</div><!-- /content -->
<div data-role="footer">
<h4>Page Footer</h4>
</div><!-- /header -->
I basically wanna know what $.post is doing? and how?
$.post posts a request to a URL with optional parameters and returns a response.
Let's go through your example.
$.post(postTo,......
The first parameter is the URL to which you are posting the request. This is stored in the postTo variable. In this case it has been set to login.php.
$.post(postTo,{username: $('[name=username]').val() , password: $('[name=password]').val()},......
The next part contains the data you are passing to this script. You are passing values for "username" and "password" which are being retrieved from the value of an element with the name "username" $('[name=username]') and an element with the name "password" $(name=password) which in this case are your inputs for username and password.
A successful response from login.php will trigger the callback function. Any data returned will also be available to your function(data). This data can be JSON, XML or a string
It works the same as a standard form (except for the callback).
<form action="login.php" method="post">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" />
</form>
In the above code, the whole page will redirect to login.php where you would capture the username and password and process it to perform some action. With $.post, you do the same thing without actually redirecting the page. In your login.php script, you capture the posted username and password and return a value.
For instance, you could take the username and password, query your database and if you find a match return "success" or if it does not match you could return "failure". In your ..function(data).. you check to see if the returned value is "success" and perform an action otherwise you perform another action

Categories