Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change namespace via query parameter #9

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 45 additions & 41 deletions swaggerauth.php
Original file line number Diff line number Diff line change
@@ -1,45 +1,47 @@
<?php

class SwaggerAuth {
class SwaggerAuth
{

private $error = null;

public function handler( $user_id ) {
public function handler($user_id)
{
// Don't authenticate twice
if ( ! empty( $user_id ) ) {
if (!empty($user_id)) {
return $user_id;
}

$server = new SwaggerBag( $_SERVER );
$server = new SwaggerBag($_SERVER);

// Check that we're trying to authenticate
if ( ! $server->has( 'PHP_AUTH_USER' ) ) {
$user_pass = $server->get( 'REDIRECT_HTTP_AUTHORIZATION' );
if ( $server->has( 'REDIRECT_HTTP_AUTHORIZATION' ) && ! empty( $user_pass ) ) {
list($username, $password) = explode( ':', base64_decode( substr( $user_pass, 6 ) ) );
$server->set( 'PHP_AUTH_USER', $username );
$server->set( 'PHP_AUTH_PW', $password );
if (!$server->has('PHP_AUTH_USER')) {

$user_pass = $server->get('REDIRECT_HTTP_AUTHORIZATION');
if ($server->has('REDIRECT_HTTP_AUTHORIZATION') && !empty($user_pass)) {
list($username, $password) = explode(':', base64_decode(substr($user_pass, 6)));
$server->set('PHP_AUTH_USER', $username);
$server->set('PHP_AUTH_PW', $password);
} else {
return $user_id;
}
}

$username = $server->get( 'PHP_AUTH_USER' );
$password = $server->get( 'PHP_AUTH_PW' );
$username = $server->get('PHP_AUTH_USER');
$password = $server->get('PHP_AUTH_PW');
/**
* In multi-site, wp_authenticate_spam_check filter is run on authentication. This filter calls
* get_currentuserinfo which in turn calls the determine_current_user filter. This leads to infinite
* recursion and a stack overflow unless the current function is removed from the determine_current_user
* filter during authentication.
*/
remove_filter( 'determine_current_user', [ $this, 'handler' ], 14 );
remove_filter('determine_current_user', [$this, 'handler'], 14);

$user = wp_authenticate( $username, $password );
$user = wp_authenticate($username, $password);

add_filter( 'determine_current_user', [ $this, 'handler' ], 14 );
add_filter('determine_current_user', [$this, 'handler'], 14);

if ( is_wp_error( $user ) ) {
if (is_wp_error($user)) {
$this->error = $user;
return null;
}
Expand All @@ -49,17 +51,19 @@ public function handler( $user_id ) {
return $user->ID;
}

public function error( $error ) {
public function error($error)
{

if ( ! empty( $error ) ) {
if (!empty($error)) {
return $error;
}

return $this->error;
}

public function appendSwaggerAuth( $auth ) {
if ( ! is_array( $auth ) ) {
public function appendSwaggerAuth($auth)
{
if (!is_array($auth)) {
$auth = [];
}

Expand All @@ -70,31 +74,31 @@ public function appendSwaggerAuth( $auth ) {
return $auth;
}

private function getUserDataByConsumerKey( $consumer_key ) {
global $wpdb;

$consumer_key = wc_api_hash( sanitize_text_field( $consumer_key ) );
return $wpdb->get_row( $wpdb->prepare( "SELECT key_id, user_id, permissions, consumer_key, consumer_secret, nonces FROM {$wpdb->prefix}woocommerce_api_keys WHERE consumer_key = %s LIMIT 1", $consumer_key ) );
}
private function getUserDataByConsumerKey($consumer_key)
{
global $wpdb;

public function authenticate( $user, $username, $password ) {
$consumer_key = wc_api_hash(sanitize_text_field($consumer_key));
return $wpdb->get_row($wpdb->prepare("SELECT key_id, user_id, permissions, consumer_key, consumer_secret, nonces FROM {$wpdb->prefix}woocommerce_api_keys WHERE consumer_key = %s LIMIT 1", $consumer_key));
}

if ( ! ( $user instanceof WP_User ) && class_exists( 'woocommerce' ) ) {
$u = $this->getUserDataByConsumerKey( $username );
if ( ! empty( $u ) && hash_equals( $u->consumer_secret, $password ) ) {
$user = get_user_by( 'ID', $u->user_id );
}
}
public function authenticate($user, $username, $password)
{

return $user;
}
if (!($user instanceof WP_User) && class_exists('woocommerce')) {
$u = $this->getUserDataByConsumerKey($username);
if (!empty($u) && hash_equals($u->consumer_secret, $password)) {
$user = get_user_by('ID', $u->user_id);
}
}

return $user;
}
}

$basic = new SwaggerAuth();

add_filter( 'determine_current_user', [ $basic, 'handler' ], 14 );
add_filter( 'authenticate', [ $basic, 'authenticate' ], 21, 3 );
add_filter( 'rest_authentication_errors', [ $basic, 'error' ] );
add_filter( 'swagger_api_security_definitions', [ $basic, 'appendSwaggerAuth' ] );

add_filter('determine_current_user', [$basic, 'handler'], 14);
add_filter('authenticate', [$basic, 'authenticate'], 21, 3);
add_filter('rest_authentication_errors', [$basic, 'error']);
add_filter('swagger_api_security_definitions', [$basic, 'appendSwaggerAuth']);
42 changes: 25 additions & 17 deletions swaggerbag.php
Original file line number Diff line number Diff line change
@@ -1,50 +1,58 @@
<?php

class SwaggerBag {
class SwaggerBag
{

public $items = [];

public function __construct( $items = [] ) {
$this->replace( $items );
public function __construct($items = [])
{
$this->replace($items);
}

public function replace( $items = [] ) {
public function replace($items = [])
{
$this->items = $items;
}

public function set( $name, $value ) {
public function set($name, $value)
{
$this->items[$name] = $value;
}

public function get( $name ) {
return isset( $this->items[$name] ) ? $this->items[$name] : null;
public function get($name)
{
return isset($this->items[$name]) ? $this->items[$name] : null;
}

public function has( $name ) {
return array_key_exists( $name, $this->items );
public function has($name)
{
return array_key_exists($name, $this->items);
}

public function all() {
public function all()
{
return $this->items;
}

public function keys() {
return array_keys( $this->items );
public function keys()
{
return array_keys($this->items);
}

public function only( $name ) {
$look = is_array( $name ) ? $name : func_get_args();
public function only($name)
{
$look = is_array($name) ? $name : func_get_args();

$all = $this->all();
$filtered = [];

foreach ( $look as $key ) {
if ( isset( $all[$key] ) ) {
foreach ($look as $key) {
if (isset($all[$key])) {
$filtered[$key] = $all[$key];
}
}

return $filtered;
}

}
47 changes: 27 additions & 20 deletions swaggersetting.php
Original file line number Diff line number Diff line change
@@ -1,53 +1,60 @@
<?php

class SwaggerSetting {
class SwaggerSetting
{

public function menu() {
add_submenu_page( 'options-general.php', 'Swagger Setting', 'Swagger', 'manage_options', 'swagger-ui', [ $this, 'display' ] );
public function menu()
{
add_submenu_page('options-general.php', 'Swagger Setting', 'Swagger', 'manage_options', 'swagger-ui', [$this, 'display']);
}

public function saveSetting() {
public function saveSetting()
{

if ( isset( $_POST['_wpnonce'] ) && current_user_can( 'manage_options' ) && wp_verify_nonce( $_POST['_wpnonce'], 'swagger_api_setting' ) ) {
if (isset($_POST['_wpnonce']) && current_user_can('manage_options') && wp_verify_nonce($_POST['_wpnonce'], 'swagger_api_setting')) {

if ( isset( $_POST['swagger_api_basepath'] ) ) {
update_option( 'swagger_api_basepath', sanitize_text_field( $_POST['swagger_api_basepath'] ) );
if (isset($_POST['swagger_api_basepath'])) {
update_option('swagger_api_basepath', sanitize_text_field($_POST['swagger_api_basepath']));
}

add_action( 'admin_notices', [ $this, 'notices' ] );
add_action('admin_notices', [$this, 'notices']);
}
}

public function notices() {
echo self::template( 'notice' );
public function notices()
{
echo self::template('notice');
}

public function display() {
public function display()
{

$data = [];
$data['page_title'] = get_admin_page_title();
$data['swagger_api_basepath'] = WP_API_SwaggerUI::getCLeanNameSpace();
$data['swagger_api_basepath'] = WP_API_SwaggerUI::getCleanNameSpace();
$data['namespaces'] = rest_get_server()->get_namespaces();
$data['docs_url'] = home_url( untrailingslashit( WP_API_SwaggerUI::rewriteBaseApi() ) . '/docs' );
$data['docs_url'] = home_url(untrailingslashit(WP_API_SwaggerUI::rewriteBaseApi()) . '/docs');
$data['schema_url'] = home_url(untrailingslashit(WP_API_SwaggerUI::rewriteBaseApi()) . '/schema');
$data['ns_url'] = home_url(untrailingslashit(WP_API_SwaggerUI::rewriteBaseApi()) . '/ns');

echo self::template( 'setting', $data );
echo self::template('setting', $data);
}

public static function template( $file, $data = [] ) {
public static function template($file, $data = [])
{
ob_start();

$__file = __DIR__ . DIRECTORY_SEPARATOR . 'template/' . $file . '.php';
if ( is_readable( $__file ) ) {
extract( $data, EXTR_SKIP );
if (is_readable($__file)) {
extract($data, EXTR_SKIP);
include $__file;
}

return ob_get_clean();
}

}

$swaggerSetting = new SwaggerSetting();

add_action( 'admin_menu', [ $swaggerSetting, 'menu' ] );
add_action( 'init', [ $swaggerSetting, 'saveSetting' ] );
add_action('admin_menu', [$swaggerSetting, 'menu']);
add_action('init', [$swaggerSetting, 'saveSetting']);
7 changes: 5 additions & 2 deletions swaggertemplate.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ public function view($template)
if (get_query_var('swagger_api') === 'docs') {
$template = WP_API_SwaggerUI::pluginPath('template/single.php');
}
if (get_query_var('swagger_api') === 'ns') {
die(WP_API_SwaggerUI::getNameSpaces());
}
return $template;
}

Expand Down Expand Up @@ -51,8 +54,9 @@ public function enqueueScritps()
$info_js = $this->getAssetInfo('assets/js/app');
wp_enqueue_script('swagger-ui', WP_API_SwaggerUI::pluginUrl('assets/js/app.js'), $info_js['dependencies'], $info_js['version'], true);

$qpNameSpace = WP_API_SwaggerUI::getQPNameSpace();
$l10n = array(
'schema_url' => home_url(WP_API_SwaggerUI::rewriteBaseApi() . '/schema')
'schema_url' => home_url(WP_API_SwaggerUI::rewriteBaseApi() . '/schema' . ($qpNameSpace ? "?namespace=$qpNameSpace" : ""))
);
wp_localize_script('swagger-ui', 'swagger_ui_app', $l10n);
}
Expand All @@ -70,7 +74,6 @@ public function getAssetInfo($name = '')

return $info;
}

}

$swaggerTemplate = new SwaggerTemplate();
Expand Down
2 changes: 1 addition & 1 deletion template/notice.php
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
<div class="notice notice-success is-dismissible">
<p><?php echo esc_attr( 'Settings saved.' ); ?></p>
<p><?php echo esc_attr('Settings saved.'); ?></p>
</div>
41 changes: 33 additions & 8 deletions template/setting.php
Original file line number Diff line number Diff line change
@@ -1,27 +1,52 @@
<div class="wrap">
<h2><?php echo $page_title; ?></h2>
<form action="" method="post">
<?php wp_nonce_field( 'swagger_api_setting' ) ?>
<?php wp_nonce_field('swagger_api_setting') ?>
<table class="form-table">
<tbody>
<tbody>
<tr>
<th>API Basepath</th>
<th>API Default namespace</th>
<td>
<select name="swagger_api_basepath">
<?php
foreach ( $namespaces as $namespace ) {
foreach ($namespaces as $namespace) {
?>
<option value="<?php echo esc_attr( $namespace ); ?>" <?php selected( $namespace, $swagger_api_basepath ) ?>><?php echo esc_html( $namespace ); ?></option>
<?php
<option value="<?php echo esc_attr($namespace); ?>" <?php selected($namespace, $swagger_api_basepath) ?>><?php echo esc_html($namespace); ?></option>
<?php
}
?>
</select>
</td>
</tr>
</tr>
<tr>
<th>API Docs</th>
<td>
<a href="<?php echo esc_url( $docs_url ); ?>" target="__blank">Docs URL</a>
<a href="<?php echo esc_url($docs_url); ?>" target="__blank">Docs URL</a>
</td>
</tr>
<tr>
<th>API Schema</th>
<td>
<a href="<?php echo esc_url($schema_url); ?>" target="__blank">Schema URL</a>
</td>
</tr>
<tr>
<th>API namespaces list</th>
<td>
<a href="<?php echo esc_url($ns_url); ?>" target="__blank">NS List URL</a>
</td>
</tr>
<tr>
<th>Notes</th>
<td>
<ul>
<li>
<small>
Add <code>namespace</code> query parameter to change the default
(eg <code><?php echo esc_url($docs_url); ?>?namespace=wp/v2</code>)
</small>
</li>
</ul>
</td>
</tr>
</tbody>
Expand Down
Loading