Skip to content

Commit

Permalink
Merge pull request #27 from NickolausDS/master
Browse files Browse the repository at this point in the history
Added Web Service Demo
  • Loading branch information
NickolausDS committed Oct 25, 2012
2 parents 42f2623 + 4837a70 commit 9c3aeeb
Show file tree
Hide file tree
Showing 6 changed files with 330 additions and 0 deletions.
42 changes: 42 additions & 0 deletions src/shared/wsdemo/service/Credentials.class.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php
/******************************************************************
* Credentials.class.php
* By: Jeff Miller ([email protected]), 2012-10-24
* Description: Validate a user
******************************************************************/

//this class is not the same as the Credentials class used by the client
//tbe client only needs the public properties for serialization purposes
class Credentials {
//these should probably be private because you want your setter/constructor to validate
public $username, $password;

public function __construct($un, $pwd) {
$this->username = $un;
$this->password = $pwd;
}

//notice the & before the $, this makes it a reference variable
public function validate(&$token) {
$isValid = false;
//simulate calling stored procedure...
//the token would be generated by the stored procedure or it would be passed in and saved
if ($this->username == "test" && $this->password == "qwert") {
$isValid = true;
//generate a hash of random characters that will be given to the client
$token = md5($this->rand_string(100));
}
return $isValid;
}

private function rand_string($length) {
$str = "";
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$size = strlen($chars);
for($i = 0; $i < $length; $i++) {
$str .= $chars[rand(0, $size - 1)];
}
return $str;
}
};
?>
68 changes: 68 additions & 0 deletions src/shared/wsdemo/service/ua.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?php
/******************************************************************
* ua.php
* By: Jeff Miller ([email protected]), 2012-10-24
* Description: User Accounts web service example
******************************************************************/

include("Credentials.class.php");

//this is the object format that the client expects from getTokenFromCredentials
//what else might the client want to know?
class UATokenMessage {
public $token, $expires, $statuscode, $statusdesc;
};

if (!isset($_POST["jsondata"])) {
header('HTTP/1.1 404 Not Found');
exit;
} else {
try {
$req = json_decode($_POST["jsondata"]);
if (!isset($req->behavior)) {
//these aren't the droids you're looking for...
header('HTTP/1.1 404 Not Found');
exit;
} else {
switch ($req->behavior) {
case "getTokenFromCredentials":
$msg = new UATokenMessage();
// the constructor for Credentials can do some basic validation (or throw an exception)
$credentials = new Credentials(
$req->credentials->username,
$req->credentials->password
);
// the validate() method returns true if valid or false if invalid
if ($credentials->validate($token)) {
// the $token parameter was passed by reference and set inside validate()
$msg->token = $token;
//get the current time
$dt = new DateTime(null, new DateTimeZone("America/Los_Angeles"));
//expire the token in 10 seconds, this should probably reside inside validate
$dt->modify("+10 seconds");
$msg->expires = $dt->format(DateTime::RFC822);
//just some helpful status information for the caller
$msg->statuscode = 0;
$msg->statusdesc = "Login successful";
} else {
//bad credentials
$msg->statuscode = 1;
$msg->statusdesc = "Invalid user name or password";
}
header("Content-type: application/json");
echo json_encode($msg); //serialize the UATokenMessage
break;
default:
//we don't implement that unknown behavior
header('HTTP/1.1 400 Bad Request');
exit;
}
}
} catch (Exception $e) {
header('HTTP/1.1 500 Internal Server Error');
echo "Error: " . $e->getMessage();
exit;
}
}

?>
45 changes: 45 additions & 0 deletions src/shared/wsdemo/web/WSRequestManager.class.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php
/******************************************************************
* WSRequestManager.class.php
* By: Jeff Miller ([email protected]), 2012-10-24
* Description: Simple Web Service caller
******************************************************************/

class WSRequestManager {
private $url;

public function setServiceAddress($serviceId) {
$serviceroot = (isset($_SERVER["HTTPS"]) ? "https" : "http") . "://" .
$_SERVER["SERVER_NAME"] .
"/wsdemo/service/";
switch ($serviceId) {
case "UA":
$this->url = "${serviceroot}ua.php";
break;
default:
//$this->url = "";
return false;
}
return true;
}

public function getData($post_args) {
$results = "";
if (isset($this->url)) {
$ch = curl_init();
// Set the URL to the web service required by the data manager.
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_args);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//header("Content-Type: application/json");
$results = curl_exec($ch);
curl_close($ch);
// Do whatever processing is needed to the data that was returned.
}
return $results;
}
}
?>

52 changes: 52 additions & 0 deletions src/shared/wsdemo/web/login.include.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php
/******************************************************************
* login.include.php
* By: Jeff Miller ([email protected]), 2012-10-24
* Description: Utility functions for pages that require login.
* This code wants to live in a Singleton...
******************************************************************/

function getSecret() {
//this is the private key that is used to encrypt/decrypt the cookie data
//it should be stored in a secure location on the server (for demonstration purposes only)
//how can this be made more secure?
return "qwertpoiuy";
}

//store encrypted cookies in user-agent
function setLoginCookie($data, $exptimestamp) {
//magic
$cookieData = serialize($data);
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
srand();
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$encryptedData = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, getSecret(), $cookieData, MCRYPT_MODE_CBC, $iv);
setcookie("usr", base64_encode($encryptedData) . ":" . $iv, $exptimestamp);
}

//get and decrypt encrypted cookies from user-agent
function getLoginCookie() {
//voodoo
list($encryptedData, $iv) = explode(":", $_COOKIE["usr"]);
$rawData = mcrypt_decrypt(
MCRYPT_RIJNDAEL_256,
getSecret(),
base64_decode($encryptedData),
MCRYPT_MODE_CBC,
$iv
);
return unserialize($rawData);
}

//If logged in, continue. Otherwise, go back to login page.

//here is the location of the login page, it should be stored in a config file somewhere instead of hard-coding it
$loginpage = "/wsdemo/web/login.php";
//this script is included by all pages that require login
//if we're sitting on the login page itself, don't infinite redirect
//otherwise, redirect to login if the cookie is not valid
//do we need a function that checks the database to see if the token is valid?
if ($_SERVER['PHP_SELF'] != $loginpage && strlen(getLoginCookie()) != 32) {
header("Location: ${loginpage}?jumpto=${_SERVER['PHP_SELF']}");
}
?>
100 changes: 100 additions & 0 deletions src/shared/wsdemo/web/login.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
<?php
/******************************************************************
* login.php
* By: Jeff Miller ([email protected]), 2012-10-24
* Description: Log in to the site.
******************************************************************/

include("WSRequestManager.class.php");
include("login.include.php");

class Credentials {
public $username, $password;
};

/*
This is the class returned by ua.php (before json_encode):
class UATokenMessage {
public $token, $expires, $statuscode, $statusdesc;
};
This is the same class in JSON (after json_encode):
Success:
{"token": "e984375893478", "expires": "", "statuscode": 0, "statusdesc": ""}
Bad credentials:
{"token": null, "expires": null, "statuscode": 1, "statusdesc": ""}
*/

function parseCredentials($un, $pwd, &$token, &$expires) {
try {
$postData = array(
"behavior" => "getTokenFromCredentials",
"credentials" => new Credentials()
);
$postData["credentials"]->username = $un;
$postData["credentials"]->password = $pwd;
$ws = new WSRequestManager();
$ws->setServiceAddress("UA");
$respTxt = $ws->getData("jsondata=" . json_encode($postData));
//return $respTxt;
$respObj = json_decode($respTxt);
$token = $respObj->token;
$expires = new DateTime($respObj->expires);
return $respObj->statusdesc;
} catch (Exception $e) {
header('HTTP/1.1 500 Internal Server Error');
echo "Error: " . $e->getMessage();
exit;
}
}

// $jumpto needs validation...
if (isset($_POST["jumpto"])) {
$jumpto = $_POST["jumpto"];
} else if(isset($_GET["jumpto"])) {
$jumpto = $_GET["jumpto"];
} else {
$jumpto = "trade.php";
}

$msg = "";
if (isset($_POST["un"]) && isset($_POST["pwd"])) {
$msg = parseCredentials($_POST["un"], $_POST["pwd"], $token, $expires);
//echo $token;
//exit;
if (isset($token) && strlen($token) == 32 && isset($expires)) {
setLoginCookie($token, $expires->getTimestamp());
header("Location: $jumpto");
}
}

?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login</title>
</head>
<body>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post" autocomplete="off">
<?php
if (strlen($msg) > 0) {
$msg = htmlentities($msg);
echo "<div style=\"text-align: center;\"><strong style=\"color: #F00;\">$msg</strong></div>";
}
?>
<fieldset style="width: 16em; margin: 0 auto;">
<legend>Log In</legend>
<dl>
<dt>User Name:</dt>
<dd><input type="text" name="un" value="" /></dd>
<dt>Password:</dt>
<dd><input type="password" name="pwd" value="" /></dd>
</dl>
<input type="submit" value="Log In" />
</fieldset>
<input type="hidden" name="jumpto" value="<?php echo htmlentities($jumpto); ?>" />
</form>
</body>
</html>


23 changes: 23 additions & 0 deletions src/shared/wsdemo/web/trade.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php
/******************************************************************
* trade.php
* By: Jeff Miller ([email protected]), 2012-10-24
* Description: Example of a page that requires login to access.
******************************************************************/

include("login.include.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Welcome</title>
</head>
<body>
<div><strong>You must be logged in to access this page.</strong></div>
<div><em>Your token was: <?php echo getLoginCookie() ?></em></div>
<a href="javascript:alert(document.cookie)">Show Cookie</a>
</body>
</html>


0 comments on commit 9c3aeeb

Please sign in to comment.