Kendo UI login functionality - javascript

I am currently making a iPhone application using Kendo UI which i am running through phone gap to test on my iPhone.
The design is all mapped out nicely and I am getting to grips with the Kendo framework. I am trying to make some functionality whereby they log into an account.
My external PHP file which runs the query and returns JSON:
<?php
$arr = array();
//Takes the username and password from the login form and queries the database to find out if they have access to the site.
//Cleanse inputs
$username = $_GET['username'];
$password = md5_base64($_GET['password']);
$stmt = $memberMysqli->prepare("SELECT id, firstname, dob, sex, recordingWeight, blocked, enabled FROM member WHERE email = ? AND password = ?");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($memberid, $firstname, $dob, $sex, $recordingWeight, $blocked, $enabled);
$stmt->store_result();
session_start();
while ($stmt->fetch())
{
$userIsBlocked = $blocked;
$enabled = $enabled;
}
if(($numRows = $stmt->num_rows) > 0) //If num rows is 1 the combination exists therefore it is a succesful login
{
if($userIsBlocked)
{
$arr['status'] = "error";
$arr['message'] = "Sorry, your account isnt active. Please contact us to re-activate it.";
}
else if(!$enabled)
{
$arr['status'] = "error";
$arr['message'] = "Sorry, your account isn't enabled. Please contact us.";
}
else
{
$_SESSION['memberid'] = $memberid;
$_SESSION['memberFirstname'] = $firstname;
$_SESSION['dob'] = $dob;
$_SESSION['sex'] = $sex;
$_SESSION['recordingWeight'] = $recordingWeight;
$arr['status'] = "success";
$arr['message'] = "Logged in";
}
}
else
{
$arr['status'] = "error";
$arr['message'] = "Sorry, Wrong Username/Password Combination";
}
header("Content-type: application/json");
echo json_encode($arr);
/* close connection */
function md5_base64 ( $data )
{
return preg_replace('/=+$/','',base64_encode(md5($data,true)));
}
?>
So this returns success, logged in or sorry wrong username/password combination..
Here is my form code:
<form>
<fieldset>
<p><label style="color:white;" for="email">E-mail address</label></p>
<p><input type="email" id="email" value=""></p>
<p><label style="color:white; font" for="password">Password</label></p>
<p><input type="password" id="password" value=""></p>
<p><input type="submit" value="Sign In"></p>
</fieldset>
and the JS:
<script>
$("form").on("submit", function() {
var username = document.getElementById('email').value;
var password = document.getElementById('password').value;
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: 'http://myurl.co.uk/appqueries/login.php?username='+username+'&password='+password,
dataType: "json"
}
}
});
//alert("Your username is "+username+" and your password is: "+password);
});
</script>
Can anybody help me getting what the JSON that the PHP file returns and then letting the user into the app if login is successful, or displaying a message if they were not.

I don't think you want a DataSource for this (it could be done, but the DataSource expects an array of objects from the read operation), unless there are additional requirements.
If this is your HTML:
<input id='username' type='text' value='user'></input>
<input id='password' type='text' value='password'></input>
<button id='loginbutton'>Login</button>
<div id='loginresult'></div>
Then you can use jQuery (which I assume you're using since it's a requirement for Kendo UI):
function loginClick() {
var username = $("#username").val();
var password = $("#password").val();
var loginUrl = 'http://myurl.co.uk/appqueries/login.php?username='+username+'&password='+password;
$.ajax({
url: loginUrl,
type: 'GET',
dataType: 'json',
success: function (data) {
handleLoginResult(data);
}
});
}
$(document).on("click", "#loginbutton", loginClick);
function handleLoginResult(data) {
var status = data.status;
var message = data.message;
if (status === "success") {
// do whatever needs to be done after successful login
$("#loginresult").html(message);
}
}
See a working example here (there are a few differences because this is using jsfiddle's echo api): http://jsfiddle.net/lhoeppner/9TGJd/
This works almost the same for Kendo Mobile, except you'd use the mobile button and the data-click binding:
<a id="loginbutton" data-role="button" data-click="loginClick">Login!</a>

You should not use form submit in Kendo Mobile application as a Kendo mobile application is basically a Single Page Application. What you need to do is to have a Kendo button and on the click event handler, fire the JSON call. You can see the demo of Kendo Button click event here: http://demos.kendoui.com/mobile/button/events.html#/

Related

Why is this simple PHP login script not working?

I am very new to PHP and JavaScript and I have made a PHP and Javascript login script. However, it just shoots out Incorrect username or password. even though it's correct. Here are my scripts:
PHP:
<?php
header('Access-Control-Allow-Origin: *');
$username = $_POST['username'];
$password = $_POST['password'];
if($username == "axqua" && $password == "abc")
{
$loggedin = true;
echo "Logged in as axqua";
}
else
{
$loggedin = false;
echo "Incorrect username or password.";
}
?>
Javascript:
<script>
var username = document.getElementById("usernameform").value.toString();
var password = document.getElementById("passwordform").value.toString();
var formData = {'username':username, 'password':password}
function posttourl() {
var posts = $.ajax({
'url': 'http://example.com/',
'type': 'POST',
'data': formData
})
posts.done(function (res) {
console.log(res)
})
}
</script>
HTML:
<p class="text">Username</p>
<input class="inputstyle" maxlength="12" id="usernameform">
<br>
<p class="text">Password</p>
<input class="inputstyle" type="password" maxlength="16" id="passwordform">
<br>
Login
I do not see a problem with this so I am not sure what is going on but if you can help then please do.
As confirmed by the comment, this is because the JS section run before the user entered the text (likely on page load), so
var username = document.getElementById("usernameform").value.toString();
var password = document.getElementById("passwordform").value.toString();
var formData = {'username':username, 'password':password}
are executed when the text boxes are empty, ignoring later input. Moving them into posttourl() ensure the values taken are current.

Do I need to sanitize user inputs when using Ajax?

I am creating a login form that does not require the page to reload on submit. I am doing this using Ajax. Below is my code:
HTML:
<form id="myForm" method="post">
Username: <input name="username" id="username" type="text"/><br/>
Password: <input name="password" id="password" type="password"/><br/>
<input type="button" id="submitFormData" onclick="SubmitFormData();" value="Submit" />
</form>
JS/Ajax:
function SubmitFormData() {
var username = $("#username").val();
var password = $("#password").val();
$.post("submit.php", { username: username, password: password},
function(data) {
$('#results').html(data);
$('#myForm')[0].reset();
});
}
PHP (submit.php):
$username = mysqli_real_escape_string($connect, $_POST["username"]);
$password = mysqli_real_escape_string($connect, $_POST["password"]);
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
if(password_verify($password, $row["password"]))
{
//return true;
$_SESSION["username"] = $username;
$_SESSION["uuid"] = $row["uuid"];
echo "success";
header ("location: https://durzst.com/main");
}
else
{
//return false;
echo '<script>alert("Wrong User Details")</script>';
}
}
}
I am already sanitizing the inputs in my PHP (Yes, I will be switching to prepared statements later), but do I need to do anything with the Ajax, such as sanitizing inputs, in order to prevent any kind of attacks. If so, how?
Yes, always Sanitize & Validate your data. Both Client Side and Server Side.
Sanitize your data, so you don't get unexpected formats, symbols etc.
Validate your data, to ensure it's data your program expects/accepts. An email address vs some random string, a date vs a string or phone number etc.
I suggest, reading up on the subject, a quick google will get you started, also StackOverflow has tones of articles on the subject, here is one.
I say always, and both Client Side and Server Side, not because you should trust your Client Side sanitization and validation, on the server, but you want to ensure both of your applications operate on correctly formatted and valid data.

Decode JSON package from PHP using AJAX

I am building a simple login system. I do not want the page to reload when the user submits the form, in case there is an error, and I need to seamlessly display an error message (Like wrong password). When the users submits the data, AJAX passes it onto the submit.php script. This script validates the data and then sets a JSON object to a number 1-3 based on what is wrong or right with the submitted credentials. I don't know how to have the AJAX call, decode the JSON, and then have some if statements that decide what to do based on the value of that JSON.
Below is the code I am using for the form.
HTML:
<form method="post" id="myForm">
<h1 class="title" unselectable="on">Login</h1>
<input placeholder="Username" type="text" name="username" class="form" id="username"/>
</br>
<input placeholder="Password" type="password" name="password" class="form" id="password"/>
</br>
<input class="button" type="button" id="submitFormData" onclick="SubmitFormData();" value="Submit"/>
</br>
</form>
JS/AJAX (Same page):
function SubmitFormData() {
var username = $("#username").val();
var password = $("#password").val();
$.post("submit.php", { username: username, password: password},
function(data) {
$('#results').html(data);
$('#myForm')[0].reset();
});
}
Next is the PHP (submit.php). The PHP will look at the incoming data from the AJAX script, and then assign an error number to a JSON object depending on what is wrong with the credentials.
$username = mysqli_real_escape_string($connect, $_POST["username"]);
$password = mysqli_real_escape_string($connect, $_POST["password"]);
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
if(password_verify($password, $row["password"]))
{
$Obj->error = "three";
$myJSON = json_encode($Obj);
}
else
{
$Obj->error = "two";
$myJSON = json_encode($Obj);
}
}
}
else {
$Obj->error = "one";
$myJSON = json_encode($Obj);
}
//error one=user not found
//error two=wrong password
//error three=all detials are correct
Now, the trouble I am having is back at the main page where the user is. I want the JS to look at the $myJSON variable and decide what to do based on that. I have written some pseudo code below, but I don't know if or how I can do this in JS or AJAX.
decode JSON package
if error=one, do something
if error=two, do something else
if error=three, run a php script that sets some session variables. (Is it possible to run php inside of JS?)
Any help accomplishing these results would be greatly appreciated.
This is a vanilla javascript solution:
const xmlhttp = new XMLHttpRequest;
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
//passes results to a function
start(JSON.parse(this.responseText));
}
}
xmlhttp.open("POST", "PHP WEBSITE URL", true);
//sends the request with a FormData object based on the form
xmlhttp.send(new FormData(document.getElementById("myForm")));
function start(object) {
alert(object);
}
For this to work, your PHP script will have to echo your result object. Example:
if ($_POST["username"] === "correctUsername" && $_POST["password"] === "correctPassword") {
//echo javascript object
echo json_encode(['success'=>true]);
} else {
//echo javascript object
echo json_encode(['success'=>false]);
}
Obviously it needs to be more complex but this is the idea.
I have made login pages before and instead of returning a success I used the current PHP page as the main one and echoed the info to fill the page as well as credentials that can be used with AJAX requests. Hopefully this helps.

Username and Password validation to list

I am very new to web development and am attempting to write code to validate username and password combinations. http://universe.tc.uvu.edu/cs2550/assignments/PasswordCheck/check.php is the link to run the check, and http://universe.tc.uvu.edu/cs2550/assignments/PasswordCheck/list.php is the list of acceptable entries. I am able to hard code in a username and password and that seems to be working fine, my question is simply "How can I hook up this input, to check inside the server for an acceptable login." Thank you for your help in advance!
Here is my form:
<form id = "formLogin" 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">
<input type = "button" value = "Login" id = "submit" onclick = "validate()">
<input type = "reset" value = "Reset">
</form>
Here is my javascript thus far:
function validate(){
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if(username == ""){
alert("Please enter a User Name")
formLogin.username.focus()
return false
}
if(password == ""){
alert("Please enter a Password")
formLogin.password.focus()
return false
}
if( username == "Test" && password == "test#123"){
alert("Login successfully");
window.location = "gameboard.html";
return false;
}
else{
alert("Login failed - Please enter correct Username and Password")
}
}
Try looking into jQuery's AJAX function. Upon submission of the login form, send the username and password combo to http://universe.tc.uvu.edu/cs2550/assignments/PasswordCheck/check.php as follows.
<form id="formLogin" 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">
<input type="submit" value="Login" id="submit">
<input type="reset" value="Reset">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$('#formLogin').submit(function(e) {
e.preventDefault();
var username = $('input#username').val();
var password = $('input#password').val();
if(password == ""){
alert("Please enter a Password");
$('#password').focus();
return false;
}
if(username == ""){
alert("Please enter a Username");
$('#username').focus();
return false;
}
if(username != '' && password != '') {
$.ajax({
url: 'http://universe.tc.uvu.edu/cs2550/assignments/PasswordCheck/check.php',
type: 'POST',
data: {
username: username,
password: password
},
success: function(data) {
console.log(data);
// It looks like the page that handles the form returns JSON
// Parse the JSON
var obj = JSON.parse(data);
if(obj.result != 'invalid') {
alert("Login succeeded");
// You should redirect the user too
window.location = 'http://redirecturl.com';
}
}
});
}
});
</script>
This effectively validates your form submission. I prefer using the jQuery library as opposed to raw JS. You should look into it too.
It's also worth noting that forms must ALWAYS be validated on the server side as well. Because a client could always just disable JavaScript in their browser to bypass your front end validation. As mentioned by someone who commented on your question, your method of backend validation is pretty insecure. Raw values of passwords should never be stored. Rather, it's good to use an sha1 hash of the password so that if an unwanted user somehow hacks into your DB he/she doesn't have all of the passwords stored in there.
Also, username/password combination validation works a lot smoother on the backend if you just do something like
// Connect to the DB
$con = mysqli_connect('localhost', 'user', 'pass', 'db');
// Escape the form values or user prepared statements
$username = mysqli_real_escape_string($con, $username);
$password = mysqli_real_escape_string($con, $password);
$sql = "SELECT * FROM users WHERE username = '".$username." AND password = '".$password."'";
$result = mysqli_query($con, $sql);
$count = mysqli_num_rows($result);
if($count == 1) {
echo "Success";
} else {
echo "Fail";
}
instead of using a static list.
You have two options here -
You can use a server side language like ASP.Net / PHP and you can add an action attribute to your form,
This will then submit to the validate.php passing in any controls with a name tag to the validate.php page.
<form name='something' method='POST' action='validate.php'>
<label>User Name: </label>
<input type = "text" name = "username" id = "username" />
<label>Password: </label>
<input type = "password" name = "password" id = "password">
<input type = "submit" value = "Login" id = "submit"">
<input type = "reset" value = "Reset">
</form>
I would suggest you learn a server side language for this, I'm not going to post the code, I will leave that to you to learn.
OR
You can use JQuery (Don't have too, but it's easier in my opinion) to call an AJAX request to the server to validate.
http://api.jquery.com/jquery.ajax/
Good examples on how to use JQuery and AJAX to call some server side code.
Checking pass in js doesnt make sense, because user can see js code. Use PHP and AJAX.

Login form with ajax does not work

I have 3 files:
1. Simple form with email and password
2. login_validate.php to validate form input against database
3. login.js to perform ajax task
I tried to validate form with just login_validate.php and everything worked for me. But when i tried to use ajax(login.js), it always tells me wrong email and password even I tried to type in correct email and password in form. Below is my code, please advice what is wrong with it?
Here is my form:
<div id="login_result"></div>
<form action="login_validate.php" method="post">
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
<input type="password" class="form-control" id="pass" name="pass" placeholder="Password">
<button type="submit" class="btn btn-default" name="submit" id="submit">Submit</button>
</form>
Here is my login_validate.php:
<?php
require("configs/dbconnect.php");
if(isset($_POST["dangnhap"])){
$email=mysql_real_escape_string($_POST["email"]);
$pass=mysql_real_escape_string($_POST["pass"]);
$sql = 'SELECT name, email, pass, visible FROM user WHERE email = "'.$email.'" AND pass = "'.$pass.'"';
$result = mysql_query($sql) or die ("Could not access DB: " . mysql_error());
$num_rows= mysql_num_rows($result); // Get the number of rows
if($num_rows > 0){
$row = mysql_fetch_array($result);
echo 1;
$_SESSION["email"]=$row["email"];
$_SESSION["pass"]=$row["pass"];
$_SESSION["name"]=$row["name"];
}
else{
echo 0;
}
}
?>
Here is my login.js:
$(document).ready(function(){
$('#email').focus(); // Focus to the username field on body loads
$('#submit').click(function(){ // Create `click` event function for login
var email = $('#email'); // Get the username field
var pass = $('#pass'); // Get the password field
var login_result = $('#login_result'); // Get the login result div
login_result.html('loading..'); // Set the pre-loader can be an animation
if(email.val() == ''){ // Check the username values is empty or not
email.focus(); // focus to the filed
login_result.html('<span class="error">Enter the username</span>');
return false;
}
if(pass.val() == ''){ // Check the password values is empty or not
pass.focus();
login_result.html('<span class="error">Enter the password</span>');
return false;
}
if(email.val() != '' && pass.val() != ''){ // Check the username and password values is not empty and make the ajax request
var UrlToPass = 'email='+email.val()+'&pass='+pass.val();
$.ajax({ // Send the credential values to another checker.php using Ajax in POST menthod
type : 'POST',
cache: false,
data : UrlToPass,
url : 'login_validate.php',
success: function(responseText){ // Get the result and asign to each cases
if(responseText == 0){
login_result.html('<span class="error">Username or Password Incorrect!</span>');
}
else if(responseText == 1){
window.location = 'member/';
}
else{
alert('Problem with sql query');
}
}
});
}
return false;
});
});
No need to test the dangnhap.
in PHP remove the check:
isset($_POST["dangnhap"]) //remove it, no checking for submit required. done in JS file.
Change in JS:
var UrlToPass = {email:email.val(),pass:pass.val()} ;
in HTML:
remove the type( type="submit" ) attribute as you are using <button>
in login_validate.php
if(isset($_POST["dangnhap"])){
but in login.js dangnhap is not set.
in $.ajax({ data can be an object, you dont have to make it a string

Categories

Resources