Skip to content

Commit

Permalink
Updated to 2.0.0
Browse files Browse the repository at this point in the history
There was some major changes and tweaks made to the plugin. Too many
updates to mention. Read the read me file detailed information.
  • Loading branch information
Justin Greer committed May 14, 2014
1 parent 2a6db11 commit 0520579
Show file tree
Hide file tree
Showing 11 changed files with 1,090 additions and 329 deletions.
21 changes: 18 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,18 @@

Your site will be able to provide Single Sign On and also deliver authorized user data using the OAuth 2.0 API.

Contributors: Justin Greer, Joel Wickard
Contributors: Justin Greer, Joel Wickard, Neil Pullman
Requires at least: 3.4.2
Tested up to: 3.7
Stable tag: 1.0.4
Stable tag: 2.0.0
License: GPLv2 or later

License URI: http://www.gnu.org/licenses/gpl-2.0.html

## Description

ENSURE THAT WP_DEBUG IS SET TO FALSE IN THE WP-CONFIG.PHP FILE..... NO JOKE!!!!

OAuth2 Complete is a ONE OF A KIND plugin that instantly turns your WordPress webste into a valid OAuth v2 provider. The plugin is built using OAuth2 Draft 20 standards. The backend is designed to be extremely easy to use for any level of experience. OAuth is a great tool but leaves most developers behind since it a bit technical.
The plugin has aleady done the hard part for you.

Expand Down Expand Up @@ -57,7 +59,7 @@ Request Token Requires only 4 parameters
* grant_type - Supported value's = `authorization_code`
* client_id
* client_secret
* Example call `http://example.com/oauth/request_token?code=the_auth_key_sent_back_from_the_authorize_call&grant_typ=authorization_code&client_id=the_client_id&client_secret=the_client_secret`
* Example call `http://example.com/oauth/request_token?code=the_auth_key_sent_back_from_the_authorize_call&grant_type=authorization_code&client_id=the_client_id&client_secret=the_client_secret`

Request Access Requires only 1 parmeter

Expand Down Expand Up @@ -100,3 +102,16 @@ When upgrading OAuth2 Provider, I seriously recommend creating a backup of your
### 1.0.4
* Fixed short tag in login layout
* Filtered out hashed password / user activation key from returned oauth data.

## 2.0.0
* Rebuild init plugin code struture for more flexibilty and scalability.
* Added prefix to all DB connections
* Changed install query to use the InnoDB engine for better support and performance.
* Fixed improper loading of plugin stylesheet.
* Removed garbage data when plugin is activated. It was not being used and cluttering the codebase as well as the database.
* Move action template_redirect to rewrites file
* Added login form support for installs that are installed in sub directory
* Added missing in documentation for when calling requesting_token
* Suppressed some errors that was preventing a proper JSON return when `WP_DEBUG` was enabled.
* Added a client sample script to help learn the baiscs of connecting to the provider plugin.
* Add legacy installer that will hopfully keep old data in tacked while updating to the new structure with no data loss.
99 changes: 99 additions & 0 deletions client-example/callback_login.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
<?php
/**
* Login Callback
*
* Thsi file location is set in the providers dashboard. WP OAuth2 erelies on data input by the provider.
* This keeps security tight and does nto allow a user to use a 3rd party location for an attack or to steal information
*
* 1. The user will redirected here by the provider and the url will have some information as well.
* 2. state - This is a paramter only used by the client as a way to track user progress during the authentication. IS reffer link to redirect back to after a succesfful login in made
* 3. code - This is a token given by the provider that is used for the next step in the process of authenticating.
*
* COLLECT ALL DATA SENT BACK FROM THE PROVIDER
*/

// You can populate these values how ever you want but they must be correct (DB, hardcoded)
$clientID = "b953042c39dc30f07004a54e916acc9aa0bc7751";
$clientSecret = "3982b878f6f0704e1045";

// I KNOW, I KNOW but this is just an example - I am cheap and tired
if( count($_GET) <= 0 ){
die("unauthorized access.");
}

print "1. Passed simple GET check <br>";
print "2. Preparing to Request Token with token ".$_GET['code']."<br>";

/**
* This is not ideal for production at all
*
* Here you can take the code provided by provide after the authorize call and passit back
* to request access.
* ( If the user is not logged in, they should be presented with a login screen )
*/

/////////////////////////////
//
// STEP 1 - REQUEST TOKEN
//
/////////////////////////////
$url = "http://development.dev/oauth/request_token?code=".$_GET['code']."&grant_type=authorization_code&client_id=".$clientID."&client_secret=".$clientSecret;
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__).'/cookie.txt');
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode( $result );

// Handle the response as you see fit
print '3. Response from provider: <pre>';
print_r( $result );
print '</pre>';

if( isset( $result->error) )
die("ERROR: There was an error present. This is where you would use [error_description] to your liking.");

// YOU COULD STOP HERE IS ALL YOU NEEDED WAS TO AUTHORIZE THE USER (SINGLE SIGN ON). IF YOU WANT TO GATHER THERE ACCOUNT INFORMATION YOU
// CAN GO TO STEP 4.

////////////////////////////////////////////////////////
//
// STEP 2 - REQUEST ACCESS TO USER INFORMATION
//
////////////////////////////////////////////////////////

// Use the return from above to and do as you please but you will need the acces_token at a minimum
print '4. Preparing the acces_token call <br>';
$url = "http://development.dev/oauth/request_access?access_token=". $result->access_token;

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__).'/cookie.txt');
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode( $result );

print '5. Response from provider: <pre>';
print_r( $result );
print '</pre>';

if( isset( $result->error) )
die("ERROR: There was an error present. This is where you would use [error_description] to your liking.");

/////////////////////////////////////
//
// STEP 3 - LOG USER IN ON YOUR SIDE
//
/////////////////////////////////////

// As long as everything went ok here, you
if( !isset( $result->error) )
print 'Here is where you can use the users information provided by the provider to set a user session and then redirect the user elsewhere';
35 changes: 35 additions & 0 deletions client-example/index.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php
/**
* Example WP OAuth2 Client
*
* @author Justin Greer
* @copyright 2014 Justin Greer <[email protected]>
* @license GPL2
*/

/**
* session_start
* In this example we will use simple sessions
* You can use cookies or any means to track user login status. It is up to you!
*/
session_start();

// Check if the user is logged in. This is simple for demonstration purposes
if( ! isset( $_SESSION['loggedIn'] ) )
$_SESSION['loggedIn'] = false;
?>

<html>
<head>
<title> WP Oauth2 Client - Example</title>
</head>
<body>
<?php if( $_SESSION['loggedIn'] === false ): ?>
<a href="http://development.dev/oauth/authorize/?client_id=b953042c39dc30f07004a54e916acc9aa0bc7751&state=someuidparameter&response_type=code" title="This will link to the WordPress site runing Oauth2 plugin"> Login </a>
<?php else: ?>
Welcome Back - <a href="/logout.php" title="The user will directed to a logout script that will simply unset the user sesion"> Logout </a>
<?php endif; ?>


</body>
</html>
19 changes: 14 additions & 5 deletions lib/classes/OAuth2.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
* OAuth2 hook for WordPress
*
* @category PHP
* @author Modified Justin Greer <support@wpkeeper.com>
* @author Modified Justin Greer <justin@blackbirdi.com>
* @license http://www.gnu.org/licenses/gpl.html
* @link http://justin-greer.com
* @link http://blackbirdi.com
*/
class OAuth2 {

Expand Down Expand Up @@ -437,6 +437,10 @@ public function grantAccessToken(array $inputData = NULL, array $authHeaders = N

// Filter input data
$input = $inputData;

// Added due to server strict policys and was causing kaos in my head
if( !isset($input['redirect_uri']) )
$input['redirect_uri'] = NULL;

// Grant Type must be specified.
if (!$input["grant_type"]) {
Expand Down Expand Up @@ -567,6 +571,11 @@ public function grantAccessToken(array $inputData = NULL, array $authHeaders = N
$stored["scope"] = NULL;
}

// Added to make things easier for now.
if (!isset($input["scope"])) {
$input["scope"] = NULL;
}

// Check scope, if provided
if ($input["scope"] && (!is_array($stored) || !isset($stored["scope"]) || !$this->checkScope($input["scope"], $stored["scope"]))) {
throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_SCOPE, 'An unsupported scope was requested.');
Expand All @@ -577,7 +586,7 @@ public function grantAccessToken(array $inputData = NULL, array $authHeaders = N

// Send response
$this->sendJsonHeaders();
echo json_encode($token);
echo json_encode( $token );
}

/**
Expand Down Expand Up @@ -677,7 +686,7 @@ public function getAuthorizeParams($inputData) {
if ($this->getVariable(self::CONFIG_ENFORCE_INPUT_REDIRECT) && !$input["redirect_uri"]) {
header("Content-Type: application/json");
header("Cache-Control: no-store");
$error = json_encode(array('Error' => 'redirect_uri is require by the OAuth API'));
$error = json_encode(array('Error' => 'redirect_uri is require by Mydwellworks OAuth API'));
echo $error;
exit;
}
Expand Down Expand Up @@ -723,7 +732,7 @@ public function getAuthorizeParams($inputData) {
if ($this->getVariable(self::CONFIG_ENFORCE_STATE) && !$input["state"]) {
header("Content-Type: application/json");
header("Cache-Control: no-store");
$error = json_encode(array('Error' => 'state is required'));
$error = json_encode(array('Error' => 'state is required by Mydwellworks'));
echo $error;
exit;
}
Expand Down
49 changes: 18 additions & 31 deletions lib/classes/OAuth2_API.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@
* @author Justin Greer
*/
global $wp_query;

/**
* Require OAuth Storage
*/
require_once( dirname(__FILE__) .'/admin/IOAuth2Storage.php' );
require_once( dirname(__FILE__) . '/admin/IOAuth2Storage.php' );

/**
* @var Set the object
Expand All @@ -19,7 +20,6 @@
* @var Clean the method from the query up a bit if needed
*/
$method = $wp_query->get('oauth');

$allowed = array(
'authorize', // Authorize a user
'request_token', // Request a Token
Expand All @@ -35,7 +35,7 @@
$file = dirname(__FILE__).'/log.txt';
$log = "Incomming Connection:".date("D F j")." at ".date("g:i:s a")."\n";
$log .= "Method Being Called: ". $method ."\n";
$log .= $_SERVER['HTTP_REFERER']."\n";
$log .= @$_SERVER['HTTP_REFERER']."\n";
foreach ($_GET as $name => $value) {
$log .= "$name: $value\n";
}
Expand All @@ -59,26 +59,17 @@
switch($method){

case 'authorize':

/**
* Prevention check
*/

header('X-Frame-Options: DENY');

/**
*Check for client_id
*/
if (!isset($_GET['client_id']) || empty($_GET['client_id'])){
header("Content-Type: application/json");
header("Cache-Control: no-store");
$error = json_encode(array('error' => 'Parameter client_id', 'error_description' => 'The client_id parameter is required and seems to be missing'));
echo $error;
exit;
}

/**
* Check for state
*/

if(!isset($_GET['state']) || empty($_GET['state'])){
header("Content-Type: application/json");
header("Cache-Control: no-store");
Expand All @@ -87,11 +78,8 @@
exit;
}

/**
* If the user is not logged in then redirect them to the OAuth Login
*/
if (!is_user_logged_in()) {
wp_redirect('/oauth/login?sso_redirect='.$_GET['client_id'].'&state='.$_GET['state']);
if ( !is_user_logged_in() ) {
wp_redirect( site_url() . '/oauth/login?sso_redirect='.$_GET['client_id'].'&state='.$_GET['state']);
exit();
}

Expand All @@ -105,7 +93,7 @@
*/
$userId = $current_user->ID;

// JUST IN CASE ONLY RUN IF $user_id HAS BEEN SET
// @todo Not too sure what this is doing but we need to look at it.
if($userId != ''){
$oauth->finishClientAuthorization(TRUE, $userId, $_GET); // AUTO AUTHORIZE
}
Expand All @@ -116,19 +104,18 @@
$oauthError->sendHttpResponse();
}

break;
break;

case 'request_token':

header('X-Frame-Options: DENY');

try {
$oauth->grantAccessToken();
} catch (OAuth2ServerException $oauthError) {
$oauthError->sendHttpResponse();
}

break;
header('X-Frame-Options: DENY');
try {
$oauth->grantAccessToken();
} catch (OAuth2ServerException $oauthError) {
$oauthError->sendHttpResponse();
}

break;

case 'request_access':

Expand All @@ -142,7 +129,7 @@
global $wpdb;
$info = $wpdb->get_row("SELECT * FROM wp_users WHERE ID = ".$user_id."");

//don't send sensitive info accross the wire.
// don't send sensitive info accross the wire.
unset($info->user_pass);
unset($info->user_activation_key);

Expand Down
Loading

0 comments on commit 0520579

Please sign in to comment.