Plugin Directory

Changeset 2334413


Ignore:
Timestamp:
07/02/2020 05:59:07 PM (6 years ago)
Author:
codexshaper
Message:

Updated WordPress Coding standard

Location:
oauth2-server/trunk
Files:
31 edited

Legend:

Unmodified
Added
Removed
  • oauth2-server/trunk/app/Exceptions/Handler.php

    r2333274 r2334413  
    66use Throwable;
    77
    8 class Handler extends ExceptionHandler
    9 {
    10     /**
    11      * A list of the exception types that are not reported.
    12      *
    13      * @var array
    14      */
    15     protected $dontReport = [
    16         //
    17     ];
     8/**
     9 * Exception handler.
     10 *
     11 * @since      1.0.0
     12 * @package    Codexshaper_Oauth_Server
     13 * @subpackage Codexshaper_Oauth_Server/app/Exceptions
     14 * @author     Md Abu Ahsan basir <maab.career@gmail.com>
     15 */
     16class Handler extends ExceptionHandler {
    1817
    19     /**
    20      * A list of the inputs that are never flashed for validation exceptions.
    21      *
    22      * @var array
    23      */
    24     protected $dontFlash = [
    25         'password',
    26         'password_confirmation',
    27     ];
     18    /**
     19     * A list of the exception types that are not reported.
     20     *
     21     * @var array
     22     */
     23    protected $dont_report = array();
    2824
    29     /**
    30      * Report or log an exception.
    31      *
    32      * @param  \Throwable  $exception
    33      * @return void
    34      *
    35      * @throws \Exception
    36      */
    37     public function report(Throwable $exception)
    38     {
    39         // throw new \Exception($exception->getMessage());
    40         parent::report($exception);
    41     }
     25    /**
     26     * A list of the inputs that are never flashed for validation exceptions.
     27     *
     28     * @var array
     29     */
     30    protected $dont_flash = array(
     31        'password',
     32        'password_confirmation',
     33    );
    4234
    43     /**
    44      * Render an exception into an HTTP response.
    45      *
    46      * @param  \Illuminate\Http\Request  $request
    47      * @param  \Throwable  $exception
    48      * @return \Symfony\Component\HttpFoundation\Response
    49      *
    50      * @throws \Throwable
    51      */
    52     public function render($request, Throwable $exception)
    53     {
    54         // throw new \Exception($exception->getMessage());
    55         return parent::render($request, $exception);
    56     }
     35    /**
     36     * Report or log an exception.
     37     *
     38     * @param  \Throwable $exception Throwable object.
     39     * @return void
     40     *
     41     * @throws \Exception Throw the exception.
     42     */
     43    public function report( Throwable $exception ) {
     44        parent::report( $exception );
     45    }
     46
     47    /**
     48     * Render an exception into an HTTP response.
     49     *
     50     * @param  \Illuminate\Http\Request $request The app request.
     51     * @param  \Throwable               $exception The throwable execption.
     52     * @return \Symfony\Component\HttpFoundation\Response The app response.
     53     *
     54     * @throws \Throwable Throw the exception.
     55     */
     56    public function render( $request, Throwable $exception ) {
     57        return parent::render( $request, $exception );
     58    }
    5759}
  • oauth2-server/trunk/app/Http/Controllers/PostController.php

    r2333274 r2334413  
    88use Illuminate\Routing\Controller;
    99
    10 class PostController extends Controller
    11 {}
     10/**
     11 * Post controller.
     12 *
     13 * @since      1.0.0
     14 * @package    Codexshaper_Oauth_Server
     15 * @subpackage Codexshaper_Oauth_Server/src/Support/Facades
     16 * @author     Md Abu Ahsan basir <maab.career@gmail.com>
     17 */
     18class PostController extends Controller {
     19}
  • oauth2-server/trunk/app/Http/Kernel.php

    r2333274 r2334413  
    55use Codexshaper_Oauth_Server\Http\Kernel as HttpKernel;
    66
    7 class Kernel extends HttpKernel
    8 {
    9     /**
    10      * The application's global HTTP middleware stack.
    11      *
    12      * These middleware are run during every request to your application.
    13      *
    14      * @var array
    15      */
    16     protected $middleware = [
    17         // \App\Http\Middleware\TrustProxies::class,
    18         // \Fruitcake\Cors\HandleCors::class,
    19         // \App\Http\Middleware\CheckForMaintenanceMode::class,
    20         // \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    21         // \App\Http\Middleware\TrimStrings::class,
    22         // \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    23     ];
     7/**
     8 * Http request handler.
     9 *
     10 * @since      1.0.0
     11 * @package    Codexshaper_Oauth_Server
     12 * @subpackage Codexshaper_Oauth_Server/app/Http
     13 * @author     Md Abu Ahsan basir <maab.career@gmail.com>
     14 */
     15class Kernel extends HttpKernel {
    2416
    25     /**
    26      * The application's route middleware groups.
    27      *
    28      * @var array
    29      */
    30     protected $middlewareGroups = [
    31         'web' => [
    32             // \App\Http\Middleware\EncryptCookies::class,
    33             // \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    34             // \Illuminate\Session\Middleware\StartSession::class,
    35             // \Illuminate\Session\Middleware\AuthenticateSession::class,
    36             // \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    37             \Codexshaper_Oauth_Server\App\Http\Middleware\VerifyCsrfToken::class,
    38             // \Illuminate\Routing\Middleware\SubstituteBindings::class,
    39         ],
     17    /**
     18     * The application's global HTTP middleware stack.
     19     *
     20     * These middleware are run during every request to your application.
     21     *
     22     * @var array
     23     */
     24    protected $middleware = array();
    4025
    41         'api' => [
    42             'throttle:60,1',
    43             \Illuminate\Routing\Middleware\SubstituteBindings::class,
    44         ],
    45     ];
     26    /**
     27     * The application's route middleware groups.
     28     *
     29     * @var array
     30     */
     31    protected $middleware_groups = array(
     32        'web' => array(
     33            \Codexshaper_Oauth_Server\App\Http\Middleware\VerifyCsrfToken::class,
     34        ),
    4635
    47     /**
    48      * The application's route middleware.
    49      *
    50      * These middleware may be assigned to groups or used individually.
    51      *
    52      * @var array
    53      */
    54     protected $routeMiddleware = [
    55         // 'auth' => \App\Http\Middleware\Authenticate::class,
    56         // 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    57         'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    58         'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    59         // 'can' => \Illuminate\Auth\Middleware\Authorize::class,
    60         // 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    61         // 'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
    62         'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    63         'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    64         // 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    65         'auth' => \Codexshaper_Oauth_Server\App\Http\Middleware\AuthMiddleware::class,
    66     ];
     36        'api' => array(
     37            'throttle:60,1',
     38        ),
     39    );
     40
     41    /**
     42     * The application's route middleware.
     43     *
     44     * These middleware may be assigned to groups or used individually.
     45     *
     46     * @var array
     47     */
     48    protected $route_middleware = array(
     49        'auth' => \Codexshaper_Oauth_Server\App\Http\Middleware\AuthMiddleware::class,
     50    );
    6751}
  • oauth2-server/trunk/app/Http/Middleware/AuthMiddleware.php

    r2333274 r2334413  
    1111use Codexshaper_Oauth_Server\App\User;
    1212
    13 class AuthMiddleware
    14 {
    15     /**
    16      * Handle an incoming request.
    17      *
    18      * @param  \Illuminate\Http\Request  $request
    19      * @param  \Closure  $next
    20      * @param  array  $guards
    21      * @return mixed
    22      */
    23     public function handle(Request $request, Closure $next, ...$guards)
    24     {   
    25         foreach($guards as $guard) {
    26             if($guard == 'api') {
    27                 if(
    28                     !Schema::hasTable('oauth_access_tokens') ||
    29                     !Schema::hasTable('oauth_refresh_tokens') ||
    30                     !Schema::hasTable('oauth_personal_access_clients') ||
    31                     !Schema::hasTable('oauth_clients') ||
    32                     !Schema::hasTable('oauth_auth_codes')
    33                 ) {
    34                  throw new \Exception("Please install OAuth2 Server Plugin (plugin link) or Implement OAuth2 Server from this link (https://github.com/Codexshaper/oauth2)", 1);
    35                 }
     13/**
     14 * Auth middleware.
     15 *
     16 * @since      1.0.0
     17 * @package    Codexshaper_Oauth_Server
     18 * @subpackage Codexshaper_Oauth_Server/app/Http/Middleware
     19 * @author     Md Abu Ahsan basir <maab.career@gmail.com>
     20 */
     21class AuthMiddleware {
    3622
    37                 $manager        = new Manager;
    38                 $resourceServer = $manager->getResourceServer();
    39                 $psrRequest        = ServerRequest::getPsrServerRequest();
     23    /**
     24     * Handle an incoming request.
     25     *
     26     * @param  \Illuminate\Http\Request $request The app request.
     27     * @param  \Closure                 $next The next closure.
     28     * @param  array                    $guards The request guards.
     29     *
     30     * @return mixed
     31     */
     32    public function handle( Request $request, Closure $next, ...$guards ) {
     33        foreach ( $guards as $guard ) {
     34            if ( $guard == 'api' ) {
     35                if ( ! Schema::hasTable( 'oauth_access_tokens' ) ||
     36                    ! Schema::hasTable( 'oauth_refresh_tokens' ) ||
     37                    ! Schema::hasTable( 'oauth_personal_access_clients' ) ||
     38                    ! Schema::hasTable( 'oauth_clients' ) ||
     39                    ! Schema::hasTable( 'oauth_auth_codes' )
     40                ) {
     41                    throw new \Exception( 'Please install OAuth2 Server Plugin (plugin link) or Implement OAuth2 Server from this link (https://github.com/Codexshaper/oauth2)', 1 );
     42                }
    4043
    41                 try {
    42                     $psr        = $resourceServer->validateAuthenticatedRequest($psrRequest);
    43                     $user_id    = $manager->validateUserForRequest($psr);
    44                    
    45                     if ($user_id) {
    46                         $user = User::find($user_id);
    47                        
    48                         $request->merge(['user' => $user ]);
    49                         $request->merge(['scopes' => $psr->getAttribute('oauth_scopes') ]);
     44                $manager         = new Manager();
     45                $resource_server = $manager->getResourceServer();
     46                $psr_request     = ServerRequest::getPsrServerRequest();
    5047
    51                         $request->setUserResolver(function () use ($user) {
    52                             return $user;
    53                         });
     48                try {
     49                    $psr     = $resource_server->validateAuthenticatedRequest( $psr_request );
     50                    $user_id = $manager->validateUserForRequest( $psr );
    5451
    55                         return $next($request);
    56                     }
     52                    if ( $user_id ) {
     53                        $user = User::find( $user_id );
    5754
    58                 } catch (OAuthServerException $e) {
    59                     throw new \Exception($e->getMessage());
    60                    
    61                 }
     55                        $request->merge( array( 'user' => $user ) );
     56                        $request->merge( array( 'scopes' => $psr->getAttribute( 'oauth_scopes' ) ) );
    6257
    63                 return $next($request);
    64             }
    65         }
     58                        $request->setUserResolver(
     59                            function () use ( $user ) {
     60                                return $user;
     61                            }
     62                        );
    6663
    67         if(\is_user_logged_in()) {
    68             return $next($request);
    69         }
    70        
    71         header('Location: '.\get_site_url().'/wp-admin');
    72         die();
    73     }
     64                        return $next( $request );
     65                    }
     66                } catch ( OAuthServerException $e ) {
     67                    throw new \Exception( $e->getMessage() );
     68
     69                }
     70
     71                return $next( $request );
     72            }
     73        }
     74
     75        if ( \is_user_logged_in() ) {
     76            return $next( $request );
     77        }
     78
     79        header( 'Location: ' . \get_site_url() . '/wp-admin' );
     80        die();
     81    }
    7482}
  • oauth2-server/trunk/app/Http/Middleware/Scope.php

    r2333274 r2334413  
    1111use WPB\App\User;
    1212
    13 class Scope
    14 {
    15     /**
    16      * Handle an incoming request.
    17      *
    18      * @param  \Illuminate\Http\Request  $request
    19      * @param  \Closure  $next
    20      * @param  array  $scopes
    21      * @return mixed
    22      */
    23     public function handle(Request $request, Closure $next, ...$scopes)
    24     {
    25         foreach ($scopes as $scope) {
    26             if (! in_array($scope, $request->scopes)) {
    27                 wp_send_json( ["msg" => "You don't have enough permission"], 400 );
    28             }
    29         } 
     13/**
     14 * Scope middleware.
     15 *
     16 * @since      1.0.0
     17 * @package    Codexshaper_Oauth_Server
     18 * @subpackage Codexshaper_Oauth_Server/app/Http/Middleware
     19 * @author     Md Abu Ahsan basir <maab.career@gmail.com>
     20 */
     21class Scope {
    3022
    31         return $next($request);
    32     }
     23    /**
     24     * Handle an incoming request.
     25     *
     26     * @param  \Illuminate\Http\Request $request The app request.
     27     * @param  \Closure                 $next The next closure.
     28     * @param  array                    $scopes Requested scopes.
     29     * @return mixed
     30     */
     31    public function handle( Request $request, Closure $next, ...$scopes ) {
     32        foreach ( $scopes as $scope ) {
     33            if ( ! in_array( $scope, $request->scopes ) ) {
     34                wp_send_json( array( 'msg' => "You don't have enough permission" ), 400 );
     35            }
     36        }
     37
     38        return $next( $request );
     39    }
    3340}
  • oauth2-server/trunk/app/Http/Middleware/VerifyCsrfToken.php

    r2333274 r2334413  
    66use Illuminate\Http\Request;
    77
    8 class VerifyCsrfToken
    9 {
    10     /**
    11      * Handle an incoming request.
    12      *
    13      * @param  \Illuminate\Http\Request  $request
    14      * @param  \Closure  $next
    15      * @return mixed
    16      */
    17     public function handle(Request $request, Closure $next)
    18     {
    19         $token = $request->input('_token') ?: $request->header('X-CSRF-TOKEN');
    20         $action = $request->codexshaper_oauth_server_nonce ?: 'codexshaper_oauth_server_nonce';
     8/**
     9 * Scope middleware.
     10 *
     11 * @since      1.0.0
     12 * @package    Codexshaper_Oauth_Server
     13 * @subpackage Codexshaper_Oauth_Server/app/Http/Middleware
     14 * @author     Md Abu Ahsan basir <maab.career@gmail.com>
     15 */
     16class VerifyCsrfToken {
    2117
    22         if ( !wp_verify_nonce( $token, $action ) ) {
    23             if ($request->ajax()) {
    24                 return wp_send_json(["message" => "CSRF Token mitchmatch"], 403 );
    25             }
     18    /**
     19     * Handle an incoming request.
     20     *
     21     * @param  \Illuminate\Http\Request $request The app request.
     22     * @param  \Closure                 $next The next closure.
     23     *
     24     * @throws \Exception Throw an error when mismatch nonce.
     25     *
     26     * @return mixed
     27     */
     28    public function handle( Request $request, Closure $next ) {
     29        $token  = $request->input( '_token' ) ?? $request->header( 'X-CSRF-TOKEN' );
     30        $action = $request->codexshaper_oauth_server_nonce ?? 'codexshaper_oauth_server_nonce';
    2631
    27             throw new \Exception("CSRF Token mismatch");
    28            
    29            
    30         }
     32        if ( ! wp_verify_nonce( $token, $action ) ) {
     33            if ( $request->ajax() ) {
     34                return wp_send_json( array( 'message' => 'CSRF Token mitchmatch' ), 403 );
     35            }
    3136
    32         return $next($request);
    33     }
     37            throw new \Exception( 'CSRF Token mismatch' );
     38
     39        }
     40
     41        return $next( $request );
     42    }
    3443}
  • oauth2-server/trunk/app/Post.php

    r2333274 r2334413  
    66use Illuminate\Database\Eloquent\Builder;
    77
    8 class Post extends Model
    9 {
    10     protected $primaryKey = 'ID';
     8/**
     9 * Post model.
     10 *
     11 * @since      1.0.0
     12 * @package    Codexshaper_Oauth_Server
     13 * @subpackage Codexshaper_Oauth_Server/app
     14 * @author     Md Abu Ahsan basir <maab.career@gmail.com>
     15 */
     16class Post extends Model {
    1117
    12     protected static $type_scope = 'post';
    13     protected static $status_scope = 'publish';
    14     protected static $author_scope = null;
     18    /**
     19     * The primary key of the model.
     20     *
     21     * @var string
     22     */
     23    protected $primaryKey = 'ID';
    1524
    16     /**
    17      * The name of the "created at" column.
    18     *
    19     * @var string
    20     */
    21     const CREATED_AT = 'post_date';
     25    /**
     26     * The type of the model.
     27    *
     28    * @var string
     29    */
     30    protected static $type_scope = 'post';
    2231
    23     /**
    24      * The name of the "updated at" column.
    25     *
    26     * @var string
    27     */
    28     const UPDATED_AT = 'post_modified';
     32    /**
     33     * The publish status of the model.
     34    *
     35    * @var string
     36    */
     37    protected static $status_scope = 'publish';
    2938
    30     /**
    31      * The "booting" method of the model.
    32      *
    33      * @return void
    34      */
    35     protected static function boot()
    36     {
    37         parent::boot();
     39    /**
     40     * The author of the model.
     41     *
     42     * @var string
     43     */
     44    protected static $author_scope = null;
    3845
    39         // foreach (['PostTypeScope', 'PostStatusScope'] as $scope) {
    40         //  $namespace = '\\CodexShaper\\WP\Database\\Eloquent\\Scopes';
    41         //  $defaultPostScopeClass = $namespace.'\\'.$scope;
    42         //  static::addGlobalScope(new $defaultPostScopeClass);
    43         // }
     46    /**
     47     * The name of the "created at" column.
     48     *
     49     * @var string
     50     */
     51    const CREATED_AT = 'post_date';
    4452
    45         // static::addGlobalScope(new PostTypeScope);
    46         // static::addGlobalScope(new PostStatusScope);
    47         // static::addGlobalScope(new PostAuthorScope);
    48         static::addGlobalScope('type', function (Builder $builder) {
    49             $builder->where('post_type', '=', static::$type_scope);
    50         });
    51         // static::addGlobalScope('scope', function (Builder $builder) {
    52         //     $builder->where('post_status', '=', static::$status_scope);
    53         // });
    54         // static::addGlobalScope('author', function (Builder $builder) {
    55         //     $builder->where('post_author', '=', static::$author_scope);
    56         // });
    57     }
     53    /**
     54     * The name of the "updated at" column.
     55     *
     56     * @var string
     57     */
     58    const UPDATED_AT = 'post_modified';
    5859
    59     // public static function all($columns = ['*'])
    60     // {
    61     //  return static::query()->where('post_type', '=', 'post')->get();
    62     // }
     60    /**
     61     * The "booting" method of the model.
     62     *
     63     * @return void
     64     */
     65    protected static function boot() {
     66        parent::boot();
     67        static::addGlobalScope(
     68            'type',
     69            function ( Builder $builder ) {
     70                $builder->where( 'post_type', '=', static::$type_scope );
     71            }
     72        );
     73    }
    6374
    64     /**
    65      * Filter by post type
    66      *
    67      * @param \Illuminate\Database\Eloquent\Builder $builder
    68      * @param string $status
    69      *
    70      * @return mixed
    71      */
    72     public function scopeType(Builder $builder, $type)
    73     {
    74         self::$type_scope = $type;
    75         return $builder->where('post_type', '=', $type);
    76     }
     75    /**
     76     * Filter by post type
     77     *
     78     * @param \Illuminate\Database\Eloquent\Builder $builder The eloquent builder.
     79     * @param string                                $type The type of model.
     80     *
     81     * @return mixed
     82     */
     83    public function scopeType( Builder $builder, $type ) {
     84        self::$type_scope = $type;
     85        return $builder->where( 'post_type', '=', $type );
     86    }
    7787
    78     /**
    79      * Filter by post status
    80      *
    81      * @param \Illuminate\Database\Eloquent\Builder $builder
    82      * @param string $status
    83      *
    84      * @return mixed
    85      */
    86     public function scopeStatus(Builder $builder, $status)
    87     {
    88         return $builder->where('post_status', '=', $status);
    89     }
     88    /**
     89     * Filter by post status
     90     *
     91     * @param \Illuminate\Database\Eloquent\Builder $builder $builder The eloquent builder.
     92     * @param string                                $status $builder The model status.
     93     *
     94     * @return mixed
     95     */
     96    public function scopeStatus( Builder $builder, $status ) {
     97        return $builder->where( 'post_status', '=', $status );
     98    }
    9099
    91     /**
    92      * Filter by post author
    93      *
    94      * @param \Illuminate\Database\Eloquent\Builder $builder
    95      * @param string|null $author
    96      *
    97      * @return mixed
    98      */
    99     public function scopeAuthor(Builder $builder, $author)
    100     {
    101         if ($author) {
    102             return $builder->where('post_author', '=', $author);
    103         }
    104     }
     100    /**
     101     * Filter by post author
     102     *
     103     * @param \Illuminate\Database\Eloquent\Builder $builder $builder The eloquent builder.
     104     * @param string|null                           $author $builder The author.
     105     *
     106     * @return mixed
     107     */
     108    public function scopeAuthor( Builder $builder, $author ) {
     109        if ( $author ) {
     110            return $builder->where( 'post_author', '=', $author );
     111        }
     112    }
    105113}
  • oauth2-server/trunk/app/User.php

    r2333274 r2334413  
    55use Illuminate\Database\Eloquent\Model;
    66
    7 class User extends Model
    8 {
     7/**
     8 * User model.
     9 *
     10 * @since      1.0.0
     11 * @package    Codexshaper_Oauth_Server
     12 * @subpackage Codexshaper_Oauth_Server/app
     13 * @author     Md Abu Ahsan basir <maab.career@gmail.com>
     14 */
     15class User extends Model {
     16
    917    protected $primaryKey = 'ID';
    10    
     18
    1119    /**
    1220     * The attributes that are mass assignable.
     
    1422     * @var array
    1523     */
    16     protected $fillable = [
    17         'name', 'email', 'password',
    18     ];
     24    protected $fillable = array(
     25        'name',
     26        'email',
     27        'password',
     28    );
    1929
    2030    /**
     
    2333     * @var array
    2434     */
    25     protected $hidden = [
    26         'password', 'remember_token',
    27     ];
     35    protected $hidden = array(
     36        'password',
     37        'remember_token',
     38    );
    2839
    2940    /**
     
    3243     * @var array
    3344     */
    34     protected $casts = [
    35         'email_verified_at' => 'datetime',
    36     ];
     45    protected $casts = array(
     46        'email_verified_at' => 'datetime',
     47    );
    3748}
  • oauth2-server/trunk/bootstrap/app.php

    r2333274 r2334413  
    11<?php
    2 require_once(ABSPATH.'wp-includes/pluggable.php');
    3 require_once __DIR__.'/../vendor/autoload.php';
    4 require_once __DIR__. '/../src/helpers.php';
     2
     3require_once ABSPATH . 'wp-includes/pluggable.php';
     4require_once __DIR__ . '/../vendor/autoload.php';
     5require_once __DIR__ . '/../src/helpers.php';
    56
    67use Codexshaper_Oauth_Server\Application;
    78
    8 // global $app;
    9 $app = (new Application([
    10     'paths' => [
    11         'root' => CODEXSHAPER_OAUTH_SERVER_APP_ROOT
    12     ]
    13 ]));
     9$app = ( new Application(
     10    array(
     11        'paths' => array(
     12            'root' => CODEXSHAPER_OAUTH_SERVER_APP_ROOT,
     13        ),
     14    )
     15) );
    1416
    15 $container = $app->getInstance();
     17$container = $app->instance();
    1618
    1719$container->singleton(
    18     Illuminate\Contracts\Http\Kernel::class,
    19     \Codexshaper_Oauth_Server\App\Http\Kernel::class
     20    Illuminate\Contracts\Http\Kernel::class,
     21    \Codexshaper_Oauth_Server\App\Http\Kernel::class
    2022);
    2123$container->singleton(
    22     \Illuminate\Contracts\Debug\ExceptionHandler::class,
    23     \Codexshaper_Oauth_Server\App\Exceptions\Handler::class
     24    \Illuminate\Contracts\Debug\ExceptionHandler::class,
     25    \Codexshaper_Oauth_Server\App\Exceptions\Handler::class
    2426);
    2527
    2628try {
    2729
    28     $kernel = $container->make(\Illuminate\Contracts\Http\Kernel::class);
     30    $kernel = $container->make( \Illuminate\Contracts\Http\Kernel::class );
    2931
    30     $response = $kernel->handle(\Illuminate\Http\Request::capture());
     32    $response = $kernel->handle( \Illuminate\Http\Request::capture() );
    3133
    3234    $response->send();
    3335
    34 } catch(\Exception $ex) {
    35     if(! \Codexshaper_Oauth_Server\Support\Facades\Route::current()) {
     36} catch ( \Exception $ex ) {
     37    if ( ! \Codexshaper_Oauth_Server\Support\Facades\Route::current() ) {
    3638        return true;
    3739    }
    38     throw new \Exception($ex, 1);
     40    throw new \Exception( $ex, 1 );
    3941}
  • oauth2-server/trunk/config/app.php

    r2333274 r2334413  
    11<?php
    22
    3 return [
    4     'debug' => true,
    5     'env'   => 'production',
    6     'providers' => [
     3return array(
     4    'debug'     => true,
     5    'env'       => 'production',
     6    'providers' => array(
    77        '\Illuminate\Filesystem\FilesystemServiceProvider',
    88        '\Illuminate\Events\EventServiceProvider',
    99        '\CodexShaper\Routing\RoutingServiceProvider',
    1010        'Illuminate\View\ViewServiceProvider',
    11     ]
    12 ];
     11    ),
     12);
  • oauth2-server/trunk/config/database.php

    r2333274 r2334413  
    11<?php
    22
    3 return [
    4     'paths' => [
     3return array(
     4    'paths' => array(
    55        'migrations' => __DIR__ . '/../database/migrations',
    6         'seeds' => __DIR__ . '/../database/seeds',
    7     ],
    8 ];
     6        'seeds'      => __DIR__ . '/../database/seeds',
     7    ),
     8);
  • oauth2-server/trunk/config/view.php

    r2333274 r2334413  
    11<?php
    22
    3 return [
    4     'paths' => [
    5         __DIR__ . '/../resources/views'
    6     ],
     3return array(
     4    'paths'    => array(
     5        __DIR__ . '/../resources/views',
     6    ),
    77    'compiled' => __DIR__ . '/../storage/cache',
    8 ];
     8);
  • oauth2-server/trunk/includes/class-codexshaper-oauth-server-activator.php

    r2333274 r2334413  
    3939    }
    4040
    41     public static function codexshaper_oauth_server_add_rewrite_authorization(){
     41    /**
     42     * Add Authorization rule to .htaccess.
     43     *
     44     * @since    1.0.0
     45     */
     46    public static function codexshaper_oauth_server_add_rewrite_authorization() {
    4247
    43       global $wp_rewrite;
     48        global $wp_rewrite;
    4449
    45       $wp_rewrite->add_rule("(.*) - [E=HTTP_AUTHORIZATION:%1]",null);
     50        $wp_rewrite->add_rule( '(.*) - [E=HTTP_AUTHORIZATION:%1]', null );
    4651
    47       $wp_rewrite->wp_rewrite_rules();
    48       $wp_rewrite->flush_rules();
     52        $wp_rewrite->wp_rewrite_rules();
     53        $wp_rewrite->flush_rules();
    4954
    50       flush_rewrite_rules();
     55        flush_rewrite_rules();
    5156
    52       static::codexshaper_oauth_server_rewrite_auth_conditions();
     57        static::codexshaper_oauth_server_rewrite_auth_conditions();
    5358    }
    5459
    55     public static function codexshaper_oauth_server_rewrite_auth_conditions(){
     60    /**
     61     * Add Authorization condition to .htaccess.
     62     *
     63     * @since    1.0.0
     64     */
     65    public static function codexshaper_oauth_server_rewrite_auth_conditions() {
    5666
    57         $filesystem = new Filesystem;
    58         $path = __DIR__.'/../../../../';
    59         $htaccess = $filesystem->get($path . '.htaccess');
     67        $filesystem = new Filesystem();
     68        $path       = __DIR__ . '/../../../../';
     69        $htaccess   = $filesystem->get( $path . '.htaccess' );
    6070
    61         //Check if our RewriteRule is present
    62        $needle = 'RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]';
    63        $replace = 'RewriteCond %{HTTP:Authorization} ^(.*)';
     71        // Check if our RewriteRule is present
     72        $needle = 'RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]';
     73        $replace = 'RewriteCond %{HTTP:Authorization} ^(.*)';
    6474
    65        if( false !== strpos( $htaccess, $needle) ) {
    66           $htaccess = str_replace($needle, $replace . "\n". $needle, $htaccess);     
    67        }
     75        if ( false !== strpos( $htaccess, $needle ) ) {
     76            $htaccess = str_replace( $needle, $replace . "\n" . $needle, $htaccess );
     77        }
    6878
    69         $filesystem->put(
    70             $path . '.htaccess',
    71             $htaccess
    72         );
     79        $filesystem->put(
     80            $path . '.htaccess',
     81            $htaccess
     82        );
    7383    }
    7484}
  • oauth2-server/trunk/includes/class-codexshaper-oauth-server-deactivator.php

    r2333274 r2334413  
    2626
    2727    /**
    28      * Short Description. (use period)
    29      *
    30      * Long Description.
     28     * Decativate plugin.
    3129     *
    3230     * @since    1.0.0
     
    3634    }
    3735
    38     protected static function update_authorization_rewrite_condition(){
     36    /**
     37     * Reset authorization in .htaccess.
     38     *
     39     * @since    1.0.0
     40     */
     41    protected static function update_authorization_rewrite_condition() {
    3942
    40         $filesystem = new Filesystem;
    41         $path = __DIR__.'/../../../../';
    42         $htaccess = $filesystem->get($path . '.htaccess');
     43        $filesystem = new Filesystem();
     44        $path       = __DIR__ . '/../../../../';
     45        $htaccess   = $filesystem->get( $path . '.htaccess' );
    4346
    44         $rules = explode("\n", $htaccess);
     47        $rules = explode( "\n", $htaccess );
    4548
    46         foreach($rules as $key => $search) {
    47             if( (false !== strpos( $search, 'RewriteCond %{HTTP:Authorization} ^(.*)')) || (false !== strpos( $search, 'RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]'))) {
    48                 unset($rules[$key]); 
    49             }
     49        foreach ( $rules as $key => $search ) {
     50            if ( ( false !== strpos( $search, 'RewriteCond %{HTTP:Authorization} ^(.*)' ) ) || ( false !== strpos( $search, 'RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]' ) ) ) {
     51                unset( $rules[ $key ] );
     52            }
    5053        }
    5154
    52         $filesystem->put(
    53             $path . '.htaccess',
    54             implode("\n", $rules)
    55         );
     55        $filesystem->put(
     56            $path . '.htaccess',
     57            implode( "\n", $rules )
     58        );
    5659    }
    5760
  • oauth2-server/trunk/includes/class-codexshaper-oauth-server-handler.php

    r2333274 r2334413  
    4949     *
    5050     * @since    1.0.0
    51      * @param      string    $plugin_name       The name of this plugin.
    52      * @param      string    $version    The version of this plugin.
     51     * @param      string $plugin_name       The name of this plugin.
     52     * @param      string $version    The version of this plugin.
    5353     */
    5454    public function __construct( $plugin_name, $version ) {
    5555
    5656        $this->plugin_name = $plugin_name;
    57         $this->version = $version;
     57        $this->version     = $version;
    5858
    5959    }
     
    6464     * @since    1.0.0
    6565     */
    66     public function codexshaper_bypass_user_for_oauth_authentication($user_id) {
     66    public function codexshaper_bypass_user_for_oauth_authentication( $user_id ) {
    6767
    6868        if ( $user_id && $user_id > 0 ) {
     
    7070        }
    7171
    72         $manager        = new Manager;
    73         $resourceServer = $manager->getResourceServer();
    74         $request        = ServerRequest::getPsrServerRequest();
     72        $manager         = new Manager();
     73        $resource_server = $manager->getResourceServer();
     74        $request         = ServerRequest::getPsrServerRequest();
    7575
    7676        try {
    77             $psr        = $resourceServer->validateAuthenticatedRequest($request);
    78             $user_id    = $manager->validateUserForRequest($psr);
    79            
    80             if ($user_id) {
    81                 return (int) $user_id;
    82             }
     77            $psr     = $resource_server->validateAuthenticatedRequest( $request );
     78            $user_id = $manager->validateUserForRequest( $psr );
    8379
    84         } catch (OAuthServerException $e) {
     80            if ( $user_id ) {
     81                return (int) $user_id;
     82            }
     83        } catch ( OAuthServerException $e ) {
    8584            return null;
    8685        }
     
    9493     * @since    1.0.0
    9594     */
    96     public function codexshaper_handle_authentication_errors($result) {
     95    public function codexshaper_handle_authentication_errors( $result ) {
    9796
    9897        return $result;
  • oauth2-server/trunk/includes/class-codexshaper-oauth-server-i18n.php

    r2333274 r2334413  
    2525 * @author     Md Abu Ahsan basir <maab.career@gmail.com>
    2626 */
    27 class Codexshaper_Oauth_Server_i18n {
     27class Codexshaper_Oauth_Server_I18n {
    2828
    2929
  • oauth2-server/trunk/includes/class-codexshaper-oauth-server-loader.php

    r2333274 r2334413  
    5858     *
    5959     * @since    1.0.0
    60      * @param    string               $hook             The name of the WordPress action that is being registered.
    61      * @param    object               $component        A reference to the instance of the object on which the action is defined.
    62      * @param    string               $callback         The name of the function definition on the $component.
    63      * @param    int                  $priority         Optional. The priority at which the function should be fired. Default is 10.
    64      * @param    int                  $accepted_args    Optional. The number of arguments that should be passed to the $callback. Default is 1.
     60     * @param    string $hook             The name of the WordPress action that is being registered.
     61     * @param    object $component        A reference to the instance of the object on which the action is defined.
     62     * @param    string $callback         The name of the function definition on the $component.
     63     * @param    int    $priority         Optional. The priority at which the function should be fired. Default is 10.
     64     * @param    int    $accepted_args    Optional. The number of arguments that should be passed to the $callback. Default is 1.
    6565     */
    6666    public function add_action( $hook, $component, $callback, $priority = 10, $accepted_args = 1 ) {
     
    7272     *
    7373     * @since    1.0.0
    74      * @param    string               $hook             The name of the WordPress filter that is being registered.
    75      * @param    object               $component        A reference to the instance of the object on which the filter is defined.
    76      * @param    string               $callback         The name of the function definition on the $component.
    77      * @param    int                  $priority         Optional. The priority at which the function should be fired. Default is 10.
    78      * @param    int                  $accepted_args    Optional. The number of arguments that should be passed to the $callback. Default is 1
     74     * @param    string $hook             The name of the WordPress filter that is being registered.
     75     * @param    object $component        A reference to the instance of the object on which the filter is defined.
     76     * @param    string $callback         The name of the function definition on the $component.
     77     * @param    int    $priority         Optional. The priority at which the function should be fired. Default is 10.
     78     * @param    int    $accepted_args    Optional. The number of arguments that should be passed to the $callback. Default is 1
    7979     */
    8080    public function add_filter( $hook, $component, $callback, $priority = 10, $accepted_args = 1 ) {
     
    8888     * @since    1.0.0
    8989     * @access   private
    90      * @param    array                $hooks            The collection of hooks that is being registered (that is, actions or filters).
    91      * @param    string               $hook             The name of the WordPress filter that is being registered.
    92      * @param    object               $component        A reference to the instance of the object on which the filter is defined.
    93      * @param    string               $callback         The name of the function definition on the $component.
    94      * @param    int                  $priority         The priority at which the function should be fired.
    95      * @param    int                  $accepted_args    The number of arguments that should be passed to the $callback.
     90     * @param    array  $hooks            The collection of hooks that is being registered (that is, actions or filters).
     91     * @param    string $hook             The name of the WordPress filter that is being registered.
     92     * @param    object $component        A reference to the instance of the object on which the filter is defined.
     93     * @param    string $callback         The name of the function definition on the $component.
     94     * @param    int    $priority         The priority at which the function should be fired.
     95     * @param    int    $accepted_args    The number of arguments that should be passed to the $callback.
    9696     * @return   array                                  The collection of actions and filters registered with WordPress.
    9797     */
     
    103103            'callback'      => $callback,
    104104            'priority'      => $priority,
    105             'accepted_args' => $accepted_args
     105            'accepted_args' => $accepted_args,
    106106        );
    107107
  • oauth2-server/trunk/includes/class-codexshaper-oauth-server.php

    r2333274 r2334413  
    8484        $this->define_oauth2_hooks();
    8585
    86         $menu = new Codexshaper_Oauth_Server_Admin_Menu;
    87         $menu->plugin_name = "codexshaper-oauth-server";
    88         $menu->page_title = "OAuth2 Server";
    89         $menu->menu_title = "OAuth2 Server";
    90         $menu->capability = "manage_options";
    91         $menu->slug = "codexshaper-oauth-server";
    92         $menu->callback = function() {
    93                 echo '<div class="wrap"><div id="codexshaper-oauth-server-admin" base-url="'.get_site_url().'" csrf-token="'.codexshaper_oauth_server_csrf_token().'"></div></div>';
    94         };
    95         $menu->icon = "dashicons-unlock";
    96         $menu->save();
    97 
    98         $submenu = new Codexshaper_Oauth_Server_Admin_SubMenu;
    99         $submenu->plugin_name = "codexshaper-oauth-server";
    100         $submenu->parent_slug = $menu->slug;
    101         $submenu->page_title = 'Clients';
    102         $submenu->menu_title = 'Clients';
    103         $submenu->capability = 'manage_options';
    104         $submenu->slug = 'admin.php?page=' . $menu->slug . '#/clients';
    105         $submenu->save();
     86        $menu              = new Codexshaper_Oauth_Server_Admin_Menu();
     87        $menu->plugin_name = 'codexshaper-oauth-server';
     88        $menu->page_title  = 'OAuth2 Server';
     89        $menu->menu_title  = 'OAuth2 Server';
     90        $menu->capability  = 'manage_options';
     91        $menu->slug        = 'codexshaper-oauth-server';
     92        $menu->callback    = function() {
     93                echo '<div class="wrap"><div id="codexshaper-oauth-server-admin" base-url="' . get_site_url() . '" csrf-token="' . codexshaper_oauth_server_csrf_token() . '"></div></div>';
     94        };
     95        $menu->icon        = 'dashicons-unlock';
     96        $menu->save();
     97
     98        $submenu              = new Codexshaper_Oauth_Server_Admin_SubMenu();
     99        $submenu->plugin_name = 'codexshaper-oauth-server';
     100        $submenu->parent_slug = $menu->slug;
     101        $submenu->page_title = 'Clients';
     102        $submenu->menu_title = 'Clients';
     103        $submenu->capability = 'manage_options';
     104        $submenu->slug        = 'admin.php?page=' . $menu->slug . '#/clients';
     105        $submenu->save();
    106106    }
    107107
     
    115115     * - Codexshaper_Oauth_Server_Admin. Defines all hooks for the admin area.
    116116     * - Codexshaper_Oauth_Server_Public. Defines all hooks for the public side of the site.
     117     * - Codexshaper_Oauth_Server_Admin_Menu. Include admin menu.
     118     * - Codexshaper_Oauth_Server_Admin_SubMenu. Include admin sub menu.
     119     * - Codexshaper_Oauth_Server_Handler. Defines all hooks for the oauth server of the site.
    117120     *
    118121     * Create an instance of the loader which will be used to register the hooks
     
    169172     * Define the locale for this plugin for internationalization.
    170173     *
    171      * Uses the Codexshaper_Oauth_Server_i18n class in order to set the domain and to register the hook
     174     * Uses the Codexshaper_Oauth_Server_I18n class in order to set the domain and to register the hook
    172175     * with WordPress.
    173176     *
     
    177180    private function set_locale() {
    178181
    179         $plugin_i18n = new Codexshaper_Oauth_Server_i18n();
     182        $plugin_i18n = new Codexshaper_Oauth_Server_I18n();
    180183
    181184        $this->loader->add_action( 'plugins_loaded', $plugin_i18n, 'load_plugin_textdomain' );
     
    272275
    273276    /**
    274     * Define the constants.
    275     *
    276     * @return void
    277     */
    278     public function define_constants() {
    279         define( 'CODEXSHAPER_OAUTH_SERVER_VERSION', $this->version );
    280     }
    281 
    282     /**
    283     * Register our app scripts and styles.
    284     *
    285     * @return void
    286     */
    287     public function register_assets() {
    288         $this->register_scripts( $this->get_scripts() );
    289         $this->register_styles( $this->get_styles() );
    290     }
    291 
    292     /**
    293     * Register scripts.
    294     *
    295     * @param  array $scripts
    296     *
    297     * @return void
    298     */
    299     private function register_scripts( $scripts ) {
    300         foreach ( $scripts as $handle => $script ) {
    301             $deps      = isset( $script['deps'] ) ? $script['deps'] : false;
    302             $in_footer = isset( $script['in_footer'] ) ? $script['in_footer'] : false;
    303             $version   = isset( $script['version'] ) ? $script['version'] : CODEXSHAPER_OAUTH_SERVER_VERSION;
    304 
    305             wp_register_script( $handle, $script['src'], $deps, $version, $in_footer );
    306         }
    307     }
    308 
    309     /**
    310     * Register styles.
    311     *
    312     * @param  array $styles
    313     *
    314     * @return void
    315     */
    316     public function register_styles( $styles ) {
    317         foreach ( $styles as $handle => $style ) {
    318             $deps = isset( $style['deps'] ) ? $style['deps'] : false;
    319 
    320             wp_register_style( $handle, $style['src'], $deps, CODEXSHAPER_OAUTH_SERVER_VERSION );
    321         }
    322     }
    323 
    324     /**
    325     * Get all registered scripts.
    326     *
    327     * @return array
    328     */
    329     public function get_scripts() {
    330 
    331         $prefix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '.min' : '';
    332 
    333         $scripts = [
    334             'codexshaper-oauth-server-runtime' => [
    335                 'src'       => CODEXSHAPER_OAUTH_SERVER_ASSETS . '/js/runtime.js',
    336                 'version'   => filemtime( CODEXSHAPER_OAUTH_SERVER_PATH . '/public/js/runtime.js' ),
    337                 'in_footer' => true
    338             ],
    339             'codexshaper-oauth-server-vendor' => [
    340                 'src'       => CODEXSHAPER_OAUTH_SERVER_ASSETS . '/js/vendors.js',
    341                 'version'   => filemtime( CODEXSHAPER_OAUTH_SERVER_PATH . '/public/js/vendors.js' ),
    342                 'in_footer' => true
    343             ],
    344             'codexshaper-oauth-server-frontend' => [
    345                 'src'       => CODEXSHAPER_OAUTH_SERVER_ASSETS . '/js/frontend.js',
    346                 'deps'      => [ 'jquery', 'codexshaper-oauth-server-vendor', 'codexshaper-oauth-server-runtime' ],
    347                 'version'   => filemtime( CODEXSHAPER_OAUTH_SERVER_PATH . '/public/js/frontend.js' ),
    348                 'in_footer' => true
    349             ],
    350             'codexshaper-oauth-server-admin' => [
    351                 'src'       => CODEXSHAPER_OAUTH_SERVER_ASSETS . '/js/admin.js',
    352                 'deps'      => [ 'jquery', 'codexshaper-oauth-server-vendor', 'codexshaper-oauth-server-runtime' ],
    353                 'version'   => filemtime( CODEXSHAPER_OAUTH_SERVER_PATH . '/public/js/admin.js' ),
    354                 'in_footer' => true
    355             ],
    356             'codexshaper-oauth-server-spa' => [
    357                 'src'       => CODEXSHAPER_OAUTH_SERVER_ASSETS . '/js/spa.js',
    358                 'deps'      => [ 'jquery', 'codexshaper-oauth-server-vendor', 'codexshaper-oauth-server-runtime' ],
    359                 'version'   => filemtime( CODEXSHAPER_OAUTH_SERVER_PATH . '/public/js/spa.js' ),
    360                 'in_footer' => true
    361             ]
    362         ];
    363 
    364         return $scripts;
    365     }
    366 
    367     /**
    368     * Get registered styles.
    369     *
    370     * @return array
    371     */
    372     public function get_styles() {
    373 
    374         $styles = [
    375             'codexshaper-oauth-server-style' => [
    376                 'src' =>  CODEXSHAPER_OAUTH_SERVER_ASSETS . '/css/style.css'
    377             ],
    378             'codexshaper-oauth-server-frontend' => [
    379                 'src' =>  CODEXSHAPER_OAUTH_SERVER_ASSETS . '/css/frontend.css'
    380             ],
    381             'codexshaper-oauth-server-admin' => [
    382                 'src' =>  CODEXSHAPER_OAUTH_SERVER_ASSETS . '/css/admin.css'
    383             ],
    384             'codexshaper-oauth-server-spa' => [
    385                 'src' =>  CODEXSHAPER_OAUTH_SERVER_ASSETS . '/css/spa.css'
    386             ],
    387             'codexshaper-oauth-server-vendors' => [
    388                 'src' =>  CODEXSHAPER_OAUTH_SERVER_ASSETS . '/css/vendors.css'
    389             ],
    390         ];
    391 
    392         return $styles;
    393     }
     277    * Define the constants.
     278    *
     279    * @return void
     280    */
     281    public function define_constants() {
     282        define( 'CODEXSHAPER_OAUTH_SERVER_VERSION', $this->version );
     283    }
     284
     285    /**
     286    * Register our app scripts and styles.
     287    *
     288    * @return void
     289    */
     290    public function register_assets() {
     291        $this->register_scripts( $this->get_scripts() );
     292        $this->register_styles( $this->get_styles() );
     293    }
     294
     295    /**
     296    * Register scripts.
     297    *
     298    * @param  array $scripts
     299    *
     300    * @return void
     301    */
     302    private function register_scripts( $scripts ) {
     303        foreach ( $scripts as $handle => $script ) {
     304            $deps      = isset( $script['deps'] ) ? $script['deps'] : false;
     305            $in_footer = isset( $script['in_footer'] ) ? $script['in_footer'] : false;
     306            $version   = isset( $script['version'] ) ? $script['version'] : CODEXSHAPER_OAUTH_SERVER_VERSION;
     307
     308            wp_register_script( $handle, $script['src'], $deps, $version, $in_footer );
     309        }
     310    }
     311
     312    /**
     313    * Register styles.
     314    *
     315    * @param  array $styles
     316    *
     317    * @return void
     318    */
     319    public function register_styles( $styles ) {
     320        foreach ( $styles as $handle => $style ) {
     321            $deps = isset( $style['deps'] ) ? $style['deps'] : false;
     322
     323            wp_register_style( $handle, $style['src'], $deps, CODEXSHAPER_OAUTH_SERVER_VERSION );
     324        }
     325    }
     326
     327    /**
     328    * Get all registered scripts.
     329    *
     330    * @return array
     331    */
     332    public function get_scripts() {
     333
     334        $prefix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '.min' : '';
     335
     336        $scripts = array(
     337            'codexshaper-oauth-server-runtime'  => array(
     338                'src'       => CODEXSHAPER_OAUTH_SERVER_ASSETS . '/js/runtime.js',
     339                'version'   => filemtime( CODEXSHAPER_OAUTH_SERVER_PATH . '/public/js/runtime.js' ),
     340                'in_footer' => true,
     341            ),
     342            'codexshaper-oauth-server-vendor'   => array(
     343                'src'       => CODEXSHAPER_OAUTH_SERVER_ASSETS . '/js/vendors.js',
     344                'version'   => filemtime( CODEXSHAPER_OAUTH_SERVER_PATH . '/public/js/vendors.js' ),
     345                'in_footer' => true,
     346            ),
     347            'codexshaper-oauth-server-frontend' => array(
     348                'src'       => CODEXSHAPER_OAUTH_SERVER_ASSETS . '/js/frontend.js',
     349                'deps'      => array( 'jquery', 'codexshaper-oauth-server-vendor', 'codexshaper-oauth-server-runtime' ),
     350                'version'   => filemtime( CODEXSHAPER_OAUTH_SERVER_PATH . '/public/js/frontend.js' ),
     351                'in_footer' => true,
     352            ),
     353            'codexshaper-oauth-server-admin'    => array(
     354                'src'       => CODEXSHAPER_OAUTH_SERVER_ASSETS . '/js/admin.js',
     355                'deps'      => array( 'jquery', 'codexshaper-oauth-server-vendor', 'codexshaper-oauth-server-runtime' ),
     356                'version'   => filemtime( CODEXSHAPER_OAUTH_SERVER_PATH . '/public/js/admin.js' ),
     357                'in_footer' => true,
     358            ),
     359            'codexshaper-oauth-server-spa'      => array(
     360                'src'       => CODEXSHAPER_OAUTH_SERVER_ASSETS . '/js/spa.js',
     361                'deps'      => array( 'jquery', 'codexshaper-oauth-server-vendor', 'codexshaper-oauth-server-runtime' ),
     362                'version'   => filemtime( CODEXSHAPER_OAUTH_SERVER_PATH . '/public/js/spa.js' ),
     363                'in_footer' => true,
     364            ),
     365        );
     366
     367        return $scripts;
     368    }
     369
     370    /**
     371    * Get registered styles.
     372    *
     373    * @return array
     374    */
     375    public function get_styles() {
     376
     377        $styles = array(
     378            'codexshaper-oauth-server-style'    => array(
     379                'src' => CODEXSHAPER_OAUTH_SERVER_ASSETS . '/css/style.css',
     380            ),
     381            'codexshaper-oauth-server-frontend' => array(
     382                'src' => CODEXSHAPER_OAUTH_SERVER_ASSETS . '/css/frontend.css',
     383            ),
     384            'codexshaper-oauth-server-admin'    => array(
     385                'src' => CODEXSHAPER_OAUTH_SERVER_ASSETS . '/css/admin.css',
     386            ),
     387            'codexshaper-oauth-server-spa'      => array(
     388                'src' => CODEXSHAPER_OAUTH_SERVER_ASSETS . '/css/spa.css',
     389            ),
     390            'codexshaper-oauth-server-vendors'  => array(
     391                'src' => CODEXSHAPER_OAUTH_SERVER_ASSETS . '/css/vendors.css',
     392            ),
     393        );
     394
     395        return $styles;
     396    }
    394397}
  • oauth2-server/trunk/oauth2-server.php

    r2333274 r2334413  
    1414 *
    1515 * @wordpress-plugin
    16  * Plugin Name:       WP Oauth2 Server
     16 * Plugin Name:       WP Oauth2 Server Original
    1717 * Plugin URI:        https://github.com/Codexshaper/wp-oauth2
    1818 * Description:       Enbble full oauth2 authentication for your site.
  • oauth2-server/trunk/public/class-codexshaper-oauth-server-public.php

    r2333274 r2334413  
    11<?php
    2 
    32/**
    43 * The public-facing functionality of the plugin.
     
    4544     *
    4645     * @since    1.0.0
    47      * @param      string    $plugin_name       The name of the plugin.
    48      * @param      string    $version    The version of this plugin.
     46     * @param      string $plugin_name       The name of the plugin.
     47     * @param      string $version    The version of this plugin.
    4948     */
    5049    public function __construct( $plugin_name, $version ) {
    5150
    5251        $this->plugin_name = $plugin_name;
    53         $this->version = $version;
     52        $this->version     = $version;
    5453
    5554    }
  • oauth2-server/trunk/public/partials/wpb-display.php

    r2333274 r2334413  
    11<?php
    2 
    32/**
    43 * Provide a public-facing view for the plugin
  • oauth2-server/trunk/readme.txt

    r2333274 r2334413  
    11=== WP OAuth2 Server ===
    22Contributors: codexshaper
    3 Tags: oauth2, server, oauth2-server, oauth2-provider, oauth2-implementation, authentication
     3Tags: oauth2, authentication
    44Requires at least: 4.7
    55Tested up to: 5.4
     
    1717There is few steps to create your credentials:
    1818
    19 *   First go to `OAuth2 Server` menu.
     19*   First go to `WP OAuth2 Server` menu.
    2020*   Then click `Clients` sub menu.
    2121*   Then click on `Create new client`. It'll popup a modal. Fill up the form and click `save`.
     
    3232= 1.0 =
    3333* This is the initial release.
    34 
    35 == Contribution ==
    36 
    37 This is free open source project, so anyone can use and contribute. If you are interested you can contribute in our github repository https://github.com/Codexshaper/wp-oauth2.
    38 
    39 If anyone found or face any security issue please mail us at codexshaper@gmail.com or create an issue in https://github.com/Codexshaper/wp-oauth2/issues.
    40 
    41 = Contributors =
    42 
    43 * [Md Abu Ahsan Basir](https://github.com/maab16)
  • oauth2-server/trunk/routes/api.php

    r2333274 r2334413  
    11<?php
     2/**
     3 * This is the api routes file.
     4 *
     5 * You can declare your all api routes here.
     6 * Either $router object or Route facade
     7 *
     8 * @link       https://github.com/maab16
     9 * @since      1.0.0
     10 *
     11 * @package    Codexshaper_Oauth_Server
     12 * @subpackage Codexshaper_Oauth_Server/routes
     13 */
    214
    315use Codexshaper_Oauth_Server\Support\Facades\Route;
     
    820 */
    921
    10 $router->get('test', function(Request $request){
    11     echo "API Test";
    12     die();
    13 });
     22$router->get(
     23    'test',
     24    function( Request $request ) {
     25        echo 'API Test';
     26        die();
     27    }
     28);
  • oauth2-server/trunk/routes/web.php

    r2333274 r2334413  
    11<?php
    2 
     2/**
     3 * This is the web routes file.
     4 *
     5 * You can declare your all web routes here.
     6 * Either $router object or Route facade
     7 *
     8 * @link       https://github.com/maab16
     9 * @since      1.0.0
     10 *
     11 * @package    Codexshaper_Oauth_Server
     12 * @subpackage Codexshaper_Oauth_Server/routes
     13 */
    314use Codexshaper_Oauth_Server\Support\Facades\Route;
    415use Illuminate\Http\Request;
    516use CodexShaper\OAuth2\Server\Manager;
    617
    7 /**
    8  * You can use either $router object or Route facate to create new route
    9  */
     18Route::group(
     19    array(
     20        'prefix'    => 'cos/oauth',
     21        'namespace' => '\CodexShaper\OAuth2\Server\Http\Controllers',
     22    ),
     23    function () {
     24        Route::post( 'token', 'ClientController@issueAccessToken' );
     25        Route::get( 'authorize', 'AuthorizationController@authorize' );
    1026
    11 Route::prefix('cos')->group(function(){
    12     Route::group(['prefix' => 'oauth', 'namespace' => '\CodexShaper\OAuth2\Server\Http\Controllers'], function () {
    13         Route::post('token', 'ClientController@issueAccessToken');
    14         Route::get('authorize', 'AuthorizationController@authorize');
     27        Route::group(
     28            array( 'middleware' => array( 'web', 'auth' ) ),
     29            function () {
     30                Route::get( 'clients', 'ClientController@all' );
     31                Route::post( 'clients', 'ClientController@store' );
     32                Route::put( 'clients', 'ClientController@update' );
     33                Route::delete( 'clients', 'ClientController@destroy' );
    1534
    16         Route::group(['middleware' => ['web', 'auth']], function () {
    17             Route::get('clients', 'ClientController@all');
    18             Route::post('clients', 'ClientController@store');
    19             Route::put('clients', 'ClientController@update');
    20             Route::delete('clients', 'ClientController@destroy');
    21 
    22             // Refresh token
    23             Route::post('token/refresh', 'ClientController@issueAccessToken');
    24         });
    25     });
    26 });
     35                // Refresh token.
     36                Route::post( 'token/refresh', 'ClientController@issueAccessToken' );
     37            }
     38        );
     39    }
     40);
  • oauth2-server/trunk/src/Application.php

    r2333274 r2334413  
    1212use Illuminate\Support\Facades\Facade;
    1313
    14 class Application
    15 {
    16     /**
    17      * @var app
    18      */
    19     protected $app = null;
    20 
    21     /**
    22      * @var config
    23      */
    24     protected $config;
    25 
    26     /**
    27      * @var db
    28      */
    29     protected $db;
    30 
    31     /**
    32      * @var options
    33      */
    34     protected $options;
    35 
    36     /**
    37      * @var root
    38      */
    39     protected $root;
    40 
    41     public function __construct($options = [], ContainerInterface $container = null)
    42     {
    43         $this->options = $options;
    44        
    45         $this->app = $container;
    46 
    47         if (is_null($this->app)) {
    48             $this->app = new Container();
    49             Facade::setFacadeApplication($this->app);
    50             $this->app->instance(ContainerInterface::class, $this->app);
    51         }
    52 
    53         $this->app['app'] = $this->app;
    54 
    55         $this->root = __DIR__ . '/../../../../';
    56 
    57         if (! empty($this->options) && isset($this->options['paths']['root'])) {
    58             $this->root = rtrim($this->options['paths']['root'], "/") . '/';
    59         }
    60 
    61         if (!isset($this->app['root'])) {
    62             $this->app['root'] = $this->root;
    63         }
    64 
    65         $this->config = new Config($this->options);
    66 
    67         $this->setupEnv();
    68         $this->registerConfig();
    69         $this->setupDatabase();
    70         $this->registerProviders();
    71         $this->registerRequest();
    72         $this->registerRouter();
    73         $this->loadRoutes($this->app['router']);
    74     }
    75 
    76     public function getInstance()
    77     {
    78         if (!$this->app) {
    79             return new self();
    80         }
    81 
    82         return $this->app;
    83     }
    84 
    85     protected function setupEnv()
    86     {
    87         $this->app['env'] = $this->config->get('app.env');
    88     }
    89 
    90     protected function registerConfig()
    91     {
    92         $this->app->bind('config', function () {
    93             return [
    94                 'app'           => $this->config->get('app'),
    95                 'view.paths'    => $this->config->get('view.paths'),
    96                 'view.compiled' => $this->config->get('view.compiled'),
    97             ];
    98         }, true);
    99     }
    100 
    101     protected function setupDatabase()
    102     {
    103         global $wpdb;
    104 
    105         $this->db = new Database([
    106             'driver'            => 'mysql',
    107             'host'               => $wpdb->dbhost,
    108             'database'        => $wpdb->dbname,
    109             'username'        => $wpdb->dbuser,
    110             'password'        => $wpdb->dbpassword,
    111             'prefix'          => $wpdb->prefix,
    112             'charset'            => $wpdb->charset,
    113             'collation'     => $wpdb->collate,
    114         ]);
    115 
    116         $this->db->run();
    117 
    118         $this->app->singleton('db', function () {
    119             return $this->db;
    120         });
    121     }
    122 
    123     protected function registerProviders()
    124     {
    125         $providers = $this->config->get('app.providers');
    126 
    127         if( $providers && count($providers) > 0) {
    128             foreach ($providers as $provider) {
    129                 with(new $provider($this->app))->register();
    130             }
    131         }
    132     }
    133 
    134     protected function registerRequest()
    135     {
    136         $this->app->bind(Request::class, function ($app) {
    137             $request = Request::capture();
    138 
    139             if ($wp_user = wp_get_current_user()) {
    140                 $user = User::find($wp_user->ID);
    141                 $request->merge(['user' => $user]);
    142                 $request->setUserResolver(function () use ($user) {
    143                     return $user;
    144                 });
    145             }
    146 
    147             return $request;
    148         });
    149     }
    150 
    151     protected function registerRouter()
    152     {
    153         $this->app->instance(\Illuminate\Routing\Router::class, $this->app['router']);
    154          $this->app->instance(\Codexshaper_Oauth_Server\Router::class, $this->app['router']); 
    155         $this->app->alias('Route', \Codexshaper_Oauth_Server\Support\Facades\Route::class);
    156     }
    157 
    158     public function loadRoutes($router, $dir = null)
    159     {
    160         if (!$dir) {
    161             $dir =  __DIR__ . '/../routes/';
    162         }
    163 
    164         require $dir.'web.php';
    165 
    166         $router->group(['prefix' => 'api'], function () use ($dir, $router) {
    167             require $dir.'api.php';
    168         });
    169     }
     14/**
     15 * Base Application.
     16 *
     17 * @link       https://github.com/maab16
     18 * @since      1.0.0
     19 *
     20 * @package    Codexshaper_Oauth_Server
     21 * @subpackage Codexshaper_Oauth_Server/src
     22 */
     23
     24/**
     25 * Base Application.
     26 *
     27 * @since      1.0.0
     28 * @package    Codexshaper_Oauth_Server
     29 * @subpackage Codexshaper_Oauth_Server/src
     30 * @author     Md Abu Ahsan basir <maab.career@gmail.com>
     31 */
     32class Application {
     33
     34    /**
     35     * The application container.
     36     *
     37     * @since    1.0.0
     38     * @access   protected
     39     * @var      \Illuminate\Contracts\Container\Container    $app
     40     */
     41    protected $app = null;
     42
     43    /**
     44     * The configuration object.
     45     *
     46     * @since    1.0.0
     47     * @access   protected
     48     * @var      \Codexshaper_Oauth_Server\Support\Facades\Config    $config
     49     */
     50    protected $config;
     51
     52    /**
     53     * The database manager.
     54     *
     55     * @since    1.0.0
     56     * @access   protected
     57     * @var      \CodexShaper\Database\Database    $db
     58     */
     59    protected $db;
     60
     61    /**
     62     * The options.
     63     *
     64     * @since    1.0.0
     65     * @access   protected
     66     * @var      array    $options
     67     */
     68    protected $options;
     69
     70    /**
     71     * The unique root path.
     72     *
     73     * @since    1.0.0
     74     * @access   protected
     75     * @var      string    $root
     76     */
     77    protected $root;
     78
     79    /**
     80     * Define the core functionality of the plugin.
     81     *
     82     * @since    1.0.0
     83     * @param   array                                          $options The default options.
     84     * @param   null|\Illuminate\Contracts\Container\Container $container Bind the container.
     85     *
     86     * @return  void
     87     */
     88    public function __construct( $options = array(), ContainerInterface $container = null ) {
     89        $this->options = $options;
     90
     91        $this->app = $container;
     92
     93        if ( is_null( $this->app ) ) {
     94            $this->app = new Container();
     95            Facade::setFacadeApplication( $this->app );
     96            $this->app->instance( ContainerInterface::class, $this->app );
     97        }
     98
     99        $this->app['app'] = $this->app;
     100
     101        $this->root = __DIR__ . '/../../../../';
     102
     103        if ( ! empty( $this->options ) && isset( $this->options['paths']['root'] ) ) {
     104            $this->root = rtrim( $this->options['paths']['root'], '/' ) . '/';
     105        }
     106
     107        if ( ! isset( $this->app['root'] ) ) {
     108            $this->app['root'] = $this->root;
     109        }
     110
     111        $this->config = new Config( $this->options );
     112
     113        $this->setup_env();
     114        $this->register_config();
     115        $this->setup_database();
     116        $this->register_providers();
     117        $this->register_request();
     118        $this->register_router();
     119        $this->load_routes( $this->app['router'] );
     120    }
     121
     122    /**
     123     * Get the instance of \Illuminate\Contracts\Container\Container.
     124     *
     125     * @since     1.0.0
     126     * @return    \Illuminate\Contracts\Container\Container
     127     */
     128    public function instance() {
     129        if ( ! $this->app ) {
     130            return new self();
     131        }
     132
     133        return $this->app;
     134    }
     135
     136    /**
     137     * Setup the app environment.
     138     *
     139     * @since     1.0.0
     140     * @return    void
     141     */
     142    protected function setup_env() {
     143        $this->app['env'] = $this->config->get( 'app.env' );
     144    }
     145
     146    /**
     147     * Register the app config.
     148     *
     149     * @since     1.0.0
     150     * @return    void
     151     */
     152    protected function register_config() {
     153        $this->app->bind(
     154            'config',
     155            function () {
     156                return array(
     157                    'app'           => $this->config->get( 'app' ),
     158                    'view.paths'    => $this->config->get( 'view.paths' ),
     159                    'view.compiled' => $this->config->get( 'view.compiled' ),
     160                );
     161            },
     162            true
     163        );
     164    }
     165
     166    /**
     167     * Setup the database.
     168     *
     169     * @since     1.0.0
     170     * @return    void
     171     */
     172    protected function setup_database() {
     173        global $wpdb;
     174
     175        $this->db = new Database(
     176            array(
     177                'driver'    => 'mysql',
     178                'host'      => $wpdb->dbhost,
     179                'database'  => $wpdb->dbname,
     180                'username'  => $wpdb->dbuser,
     181                'password'  => $wpdb->dbpassword,
     182                'prefix'    => $wpdb->prefix,
     183                'charset'   => $wpdb->charset,
     184                'collation' => $wpdb->collate,
     185            )
     186        );
     187
     188        $this->db->run();
     189
     190        $this->app->singleton(
     191            'db',
     192            function () {
     193                return $this->db;
     194            }
     195        );
     196    }
     197
     198    /**
     199     * Register providers.
     200     *
     201     * @since     1.0.0
     202     * @return    void
     203     */
     204    protected function register_providers() {
     205        $providers = $this->config->get( 'app.providers' );
     206
     207        if ( $providers && count( $providers ) > 0 ) {
     208            foreach ( $providers as $provider ) {
     209                with( new $provider( $this->app ) )->register();
     210            }
     211        }
     212    }
     213
     214    /**
     215     * Register request.
     216     *
     217     * @since     1.0.0
     218     * @return    void
     219     */
     220    protected function register_request() {
     221        $this->app->bind(
     222            Request::class,
     223            function ( $app ) {
     224                $request = Request::capture();
     225                $wp_user = wp_get_current_user();
     226
     227                if ( $wp_user ) {
     228                    $user = User::find( $wp_user->ID );
     229                    $request->merge( array( 'user' => $user ) );
     230                    $request->setUserResolver(
     231                        function () use ( $user ) {
     232                            return $user;
     233                        }
     234                    );
     235                }
     236
     237                return $request;
     238            }
     239        );
     240    }
     241
     242    /**
     243     * Register router.
     244     *
     245     * @since     1.0.0
     246     * @return    void
     247     */
     248    protected function register_router() {
     249        $this->app->instance( \Illuminate\Routing\Router::class, $this->app['router'] );
     250        $this->app->instance( \Codexshaper_Oauth_Server\Router::class, $this->app['router'] );
     251        $this->app->alias( 'Route', \Codexshaper_Oauth_Server\Support\Facades\Route::class );
     252    }
     253
     254    /**
     255     * Load all routes.
     256     *
     257     * @since     1.0.0
     258     * @param   \Illuminate\Routing\Router $router The Router to load routes.
     259     * @param   null|string                $dir This is the routes dir.
     260     * @return    void
     261     */
     262    public function load_routes( $router, $dir = null ) {
     263        if ( ! $dir ) {
     264            $dir = __DIR__ . '/../routes/';
     265        }
     266
     267        require $dir . 'web.php';
     268
     269        $router->group(
     270            array( 'prefix' => 'api' ),
     271            function () use ( $dir, $router ) {
     272                require $dir . 'api.php';
     273            }
     274        );
     275    }
    170276}
  • oauth2-server/trunk/src/Composer/ComposerScripts.php

    r2333274 r2334413  
    66use Symfony\Component\Process\Process;
    77
    8 class ComposerScripts
    9 {
    10     /**
    11      * Handle the post-install Composer event.
    12      *
    13      * @param  \Composer\Script\Event  $event
    14      * @return void
    15      */
    16     public static function postInstall(Event $event)
    17     {
    18         require_once $event->getComposer()->getConfig()->get('vendor-dir').'/autoload.php';
    19     }
     8/**
     9 * Run composer script after autoload dump.
     10 *
     11 * @link       https://github.com/maab16
     12 * @since      1.0.0
     13 *
     14 * @package    Codexshaper_Oauth_Server
     15 * @subpackage Codexshaper_Oauth_Server/src/Composer
     16 */
    2017
    21     /**
    22      * Handle the post-update Composer event.
    23      *
    24      * @param  \Composer\Script\Event  $event
    25      * @return void
    26      */
    27     public static function postUpdate(Event $event)
    28     {
    29         require_once $event->getComposer()->getConfig()->get('vendor-dir').'/autoload.php';
    30     }
     18/**
     19 * Run composer script after autoload dump.
     20 *
     21 * @since      1.0.0
     22 * @package    Codexshaper_Oauth_Server
     23 * @subpackage Codexshaper_Oauth_Server/src/Composer
     24 * @author     Md Abu Ahsan basir <maab.career@gmail.com>
     25 */
     26class ComposerScripts {
    3127
    32     /**
    33      * Handle the post-autoload-dump Composer event.
    34     *
    35      * @param  \Composer\Script\Event  $event
    36     * @return void
    37     */
    38     public static function postAutoloadDump(Event $event)
    39     {
    40         require_once $event->getComposer()->getConfig()->get('vendor-dir').'/autoload.php';
     28    /**
     29     * Handle the post-install Composer event.
     30    *
     31     * @param  \Composer\Script\Event $event The composer event.
     32    * @return void
     33    */
     34    public static function post_install( Event $event ) {
     35        require_once $event->getComposer()->getConfig()->get( 'vendor-dir' ) . '/autoload.php';
     36    }
    4137
    42         $dir = $event->getComposer()->getConfig()->get('vendor-dir').'/../';
    43         $root = dirname($event->getComposer()->getConfig()->get('vendor-dir'));
     38    /**
     39     * Handle the post-update Composer event.
     40     *
     41     * @param  \Composer\Script\Event $event The composer event.
     42     * @return void
     43     */
     44    public static function post_update( Event $event ) {
     45        require_once $event->getComposer()->getConfig()->get( 'vendor-dir' ) . '/autoload.php';
     46    }
    4447
    45         $vendor_name = strtolower(basename($root));
    46         $partials = explode('-', $vendor_name);
    47         $camel_case_partials = [];
    48         foreach ($partials as $partial) {
    49            $camel_case_partials[] = ucfirst(strtolower($partial));
    50         }
    51         $camel_case = implode('_', $camel_case_partials);
    52         $snake_case = implode('_', $partials);
     48    /**
     49     * Handle the post-autoload-dump Composer event.
     50     *
     51     * @param  \Composer\Script\Event $event The composer event.
     52     * @return void
     53     */
     54    public static function post_autoload_dump( Event $event ) {
     55        require_once $event->getComposer()->getConfig()->get( 'vendor-dir' ) . '/autoload.php';
    5356
    54         $files = [
    55             '/wpb.php',
    56             '/bootstrap/app.php',
    57             '/includes/class-wpb-activator.php',
    58             '/includes/class-wpb-deactivator.php',
    59             '/includes/class-wpb-i18n.php',
    60             '/includes/class-wpb-loader.php',
    61             '/includes/class-wpb.php',
    62             '/admin/class-wpb-admin.php',
    63             '/admin/class-wpb-admin-menu.php',
    64             '/admin/class-wpb-admin-submenu.php',
    65             '/admin/partials/wpb-admin-display.php',
    66             '/admin/css/wpb-admin.css',
    67             '/admin/js/wpb-admin.js',
    68             '/public/class-wpb-public.php',
    69             '/public/partials/wpb-public-display.php',
    70             '/public/css/wpb-public.css',
    71             '/public/js/wpb-public.js',
    72             '/routes/web.php',
    73             '/routes/api.php',
    74             '/resources/js/admin/main.js',
    75             '/resources/js/frontend/main.js',
    76             '/resources/js/spa/main.js',
    77             '/src/Application.php',
    78             '/src/helpers.php',
    79             '/src/Support/Facades/Config.php',
    80             '/src/Support/Facades/Route.php',
    81             '/src/Http/Kernel.php',
    82             '/src/Http/Events/RequestHandler.php',
    83             '/src/Exceptions/Handler.php',
    84             '/app/User.php',
    85             '/app/Post.php',
    86             '/app/Http/Controllers/ProductController.php',
    87             '/app/Http/Middleware/AuthMiddleware.php',
    88             '/app/Http/Middleware/VerifyCsrfToken.php',
    89             '/app/Http/Kernel.php',
    90             '/app/Exceptions/Handler.php',
    91         ];
     57        $dir  = $event->getComposer()->getConfig()->get( 'vendor-dir' ) . '/../';
     58        $root = dirname( $event->getComposer()->getConfig()->get( 'vendor-dir' ) );
    9259
    93         foreach ($files as $file) {
    94             $file = $root.$file;
    95             if(file_exists($file)) {
    96                 $contents = file_get_contents($file);
    97                 $contents = str_replace('wpb_', $snake_case.'_', $contents);
    98                 $contents = str_replace('wpb', $vendor_name, $contents);
    99                 $contents = str_replace('WPB_APP_ROOT', strtoupper($camel_case).'_APP_ROOT', $contents);
    100                 $contents = str_replace('WPB_FILE', strtoupper($camel_case).'_FILE', $contents);
    101                 $contents = str_replace('WPB_PATH', strtoupper($camel_case).'_PATH', $contents);
    102                 $contents = str_replace('WPB_INCLUDES', strtoupper($camel_case).'_INCLUDES', $contents);
    103                 $contents = str_replace('WPB_URL', strtoupper($camel_case).'_URL', $contents);
    104                 $contents = str_replace('WPB_ASSETS', strtoupper($camel_case).'_ASSETS', $contents);
    105                 $contents = str_replace('WPB_VERSION', strtoupper($camel_case).'_VERSION', $contents);
    106                 $contents = str_replace('WPB', $camel_case, $contents);
    107                 file_put_contents(
    108                     $file,
    109                     $contents
    110                 );
     60        $vendor_name         = strtolower( basename( $root ) );
     61        $partials            = explode( '-', $vendor_name );
     62        $camel_case_partials = array();
     63        foreach ( $partials as $partial ) {
     64            $camel_case_partials[] = ucfirst( strtolower( $partial ) );
     65        }
     66        $camel_case = implode( '_', $camel_case_partials );
     67        $snake_case = implode( '_', $partials );
    11168
    112                 $dir = dirname($file);
    113                 $fileName = basename($file);
    114                 $newFileName = str_replace('wpb', $vendor_name, $fileName);
    115                
    116                 if($fileName != $newFileName) {
    117                     rename($file, $dir.'/'.$newFileName);
    118                 }
    119                
    120             }
    121         }
     69        $files = array(
     70            '/wpb.php',
     71            '/bootstrap/app.php',
     72            '/includes/class-wpb-activator.php',
     73            '/includes/class-wpb-deactivator.php',
     74            '/includes/class-wpb-i18n.php',
     75            '/includes/class-wpb-loader.php',
     76            '/includes/class-wpb.php',
     77            '/admin/class-wpb-admin.php',
     78            '/admin/class-wpb-admin-menu.php',
     79            '/admin/class-wpb-admin-submenu.php',
     80            '/admin/partials/wpb-admin-display.php',
     81            '/admin/css/wpb-admin.css',
     82            '/admin/js/wpb-admin.js',
     83            '/public/class-wpb-public.php',
     84            '/public/partials/wpb-public-display.php',
     85            '/public/css/wpb-public.css',
     86            '/public/js/wpb-public.js',
     87            '/routes/web.php',
     88            '/routes/api.php',
     89            '/resources/js/admin/main.js',
     90            '/resources/js/frontend/main.js',
     91            '/resources/js/spa/main.js',
     92            '/src/Application.php',
     93            '/src/helpers.php',
     94            '/src/Support/Facades/Config.php',
     95            '/src/Support/Facades/Route.php',
     96            '/src/Http/Kernel.php',
     97            '/src/Http/Events/RequestHandler.php',
     98            '/src/Exceptions/Handler.php',
     99            '/app/User.php',
     100            '/app/Post.php',
     101            '/app/Http/Controllers/ProductController.php',
     102            '/app/Http/Middleware/AuthMiddleware.php',
     103            '/app/Http/Middleware/VerifyCsrfToken.php',
     104            '/app/Http/Kernel.php',
     105            '/app/Exceptions/Handler.php',
     106        );
    122107
    123         // static::configApp($root, $camel_case);
    124         static::updateComposer($root, $camel_case);
    125     }
     108        foreach ( $files as $file ) {
     109            $file = $root . $file;
     110            if ( file_exists( $file ) ) {
     111                $contents = file_get_contents( $file );
     112                $contents = str_replace( 'wpb_', $snake_case . '_', $contents );
     113                $contents = str_replace( 'wpb', $vendor_name, $contents );
     114                $contents = str_replace( 'WPB_APP_ROOT', strtoupper( $camel_case ) . '_APP_ROOT', $contents );
     115                $contents = str_replace( 'WPB_FILE', strtoupper( $camel_case ) . '_FILE', $contents );
     116                $contents = str_replace( 'WPB_PATH', strtoupper( $camel_case ) . '_PATH', $contents );
     117                $contents = str_replace( 'WPB_INCLUDES', strtoupper( $camel_case ) . '_INCLUDES', $contents );
     118                $contents = str_replace( 'WPB_URL', strtoupper( $camel_case ) . '_URL', $contents );
     119                $contents = str_replace( 'WPB_ASSETS', strtoupper( $camel_case ) . '_ASSETS', $contents );
     120                $contents = str_replace( 'WPB_VERSION', strtoupper( $camel_case ) . '_VERSION', $contents );
     121                $contents = str_replace( 'WPB', $camel_case, $contents );
     122                file_put_contents(
     123                    $file,
     124                    $contents
     125                );
    126126
    127     protected static function configApp($root, $camel_case)
    128     {
    129         $file = $root.'/bootstrap/app.php';
    130         if(file_exists($file)) {
    131             $contents = file_get_contents($file);
    132             $contents = str_replace('WPB_APP_ROOT', strtoupper($camel_case).'_APP_ROOT', $contents);
    133             file_put_contents(
    134                 $file,
    135                 $contents
    136             );
    137            
    138         }
    139     }
     127                $dir           = dirname( $file );
     128                $file_name     = basename( $file );
     129                $new_file_name = str_replace( 'wpb', $vendor_name, $file_name );
    140130
    141     protected static function updateComposer($root, $camel_case)
    142     {
    143         $file = $root.'/composer.json';
    144         if(file_exists($file)) {
    145             $contents = file_get_contents($file);
    146             $contents = str_replace('WPB', $camel_case, $contents);
    147             file_put_contents(
    148                 $file,
    149                 $contents
    150             );
    151         }
    152     }
     131                if ( $file_name !== $new_file_name ) {
     132                    rename( $file, $dir . '/' . $new_file_name );
     133                }
     134            }
     135        }
     136
     137        static::config_app( $root, $camel_case );
     138        // static::update_composer( $root, $camel_case );
     139    }
     140
     141    /**
     142     * Prepare configuration for app.
     143     *
     144     * @param  string $root The app root.
     145     * @param  string $camel_case The composer event.
     146     *
     147     * @return void
     148     */
     149    protected static function config_app( $root, $camel_case ) {
     150        $file = $root . '/bootstrap/app.php';
     151        if ( file_exists( $file ) ) {
     152            $contents = file_get_contents( $file );
     153            $contents = str_replace( 'WPB_APP_ROOT', strtoupper( $camel_case ) . '_APP_ROOT', $contents );
     154            file_put_contents(
     155                $file,
     156                $contents
     157            );
     158
     159        }
     160    }
     161
     162    /**
     163     * Update composer.
     164     *
     165     * @param  string $root The app root.
     166     * @param  string $camel_case The composer event.
     167     *
     168     * @return void
     169     */
     170    protected static function update_composer( $root, $camel_case ) {
     171        $file = $root . '/composer.json';
     172        if ( file_exists( $file ) ) {
     173            $contents = file_get_contents( $file );
     174            $contents = str_replace( 'WPB', $camel_case, $contents );
     175            file_put_contents(
     176                $file,
     177                $contents
     178            );
     179        }
     180    }
    153181}
  • oauth2-server/trunk/src/Exceptions/Handler.php

    r2333274 r2334413  
    3636use Whoops\Run as Whoops;
    3737
    38 class Handler implements ExceptionHandlerContract
    39 {
    40     /**
    41      * The container implementation.
    42      *
    43      * @var \Illuminate\Contracts\Container\Container
    44      */
    45     protected $container;
    46 
    47     /**
    48      * A list of the exception types that are not reported.
    49      *
    50      * @var array
    51      */
    52     protected $dontReport = [];
    53 
    54     /**
    55      * A list of the internal exception types that should not be reported.
    56      *
    57      * @var array
    58      */
    59     protected $internalDontReport = [
    60         AuthenticationException::class,
    61         AuthorizationException::class,
    62         HttpException::class,
    63         HttpResponseException::class,
    64         ModelNotFoundException::class,
    65         SuspiciousOperationException::class,
    66         TokenMismatchException::class,
    67         ValidationException::class,
    68     ];
    69 
    70     /**
    71      * A list of the inputs that are never flashed for validation exceptions.
    72      *
    73      * @var array
    74      */
    75     protected $dontFlash = [
    76         'password',
    77         'password_confirmation',
    78     ];
    79 
    80     /**
    81      * Create a new exception handler instance.
    82      *
    83      * @param \Illuminate\Contracts\Container\Container $container
    84      *
    85      * @return void
    86      */
    87     public function __construct(Container $container)
    88     {
    89         $this->container = $container;
    90     }
    91 
    92     /**
    93      * Report or log an exception.
    94      *
    95      * @param \Throwable $e
    96      *
    97      * @throws \Exception
    98      *
    99      * @return void
    100      */
    101     public function report(Throwable $e)
    102     {
    103         if ($this->shouldntReport($e)) {
    104             return;
    105         }
    106 
    107         if (is_callable($reportCallable = [$e, 'report'])) {
    108             $this->container->call($reportCallable);
    109 
    110             return;
    111         }
    112 
    113         try {
    114             $logger = $this->container->make(LoggerInterface::class);
    115         } catch (Exception $ex) {
    116             throw $e;
    117         }
    118 
    119         $logger->error(
    120             $e->getMessage(),
    121             array_merge(
    122                 $this->exceptionContext($e),
    123                 $this->context(),
    124                 ['exception' => $e]
    125             )
    126         );
    127     }
    128 
    129     /**
    130      * Determine if the exception should be reported.
    131      *
    132      * @param \Throwable $e
    133      *
    134      * @return bool
    135      */
    136     public function shouldReport(Throwable $e)
    137     {
    138         return !$this->shouldntReport($e);
    139     }
    140 
    141     /**
    142      * Determine if the exception is in the "do not report" list.
    143      *
    144      * @param \Throwable $e
    145      *
    146      * @return bool
    147      */
    148     protected function shouldntReport(Throwable $e)
    149     {
    150         $dontReport = array_merge($this->dontReport, $this->internalDontReport);
    151 
    152         return !is_null(Arr::first($dontReport, function ($type) use ($e) {
    153             return $e instanceof $type;
    154         }));
    155     }
    156 
    157     /**
    158      * Get the default exception context variables for logging.
    159      *
    160      * @param \Throwable $e
    161      *
    162      * @return array
    163      */
    164     protected function exceptionContext(Throwable $e)
    165     {
    166         return [];
    167     }
    168 
    169     /**
    170      * Get the default context variables for logging.
    171      *
    172      * @return array
    173      */
    174     protected function context()
    175     {
    176         try {
    177             return array_filter([
    178                 'userId' => Auth::id(),
    179                 // 'email' => optional(Auth::user())->email,
    180             ]);
    181         } catch (Throwable $e) {
    182             return [];
    183         }
    184     }
    185 
    186     /**
    187      * Render an exception into an HTTP response.
    188      *
    189      * @param \Illuminate\Http\Request $request
    190      * @param \Throwable               $e
    191      *
    192      * @throws \Throwable
    193      *
    194      * @return \Symfony\Component\HttpFoundation\Response
    195      */
    196     public function render($request, Throwable $e)
    197     {
    198         if (method_exists($e, 'render') && $response = $e->render($request)) {
    199             return Router::toResponse($request, $response);
    200         } elseif ($e instanceof Responsable) {
    201             return $e->toResponse($request);
    202         }
    203 
    204         $e = $this->prepareException($e);
    205 
    206         if ($e instanceof HttpResponseException) {
    207             return $e->getResponse();
    208         } elseif ($e instanceof AuthenticationException) {
    209             return $this->unauthenticated($request, $e);
    210         } elseif ($e instanceof ValidationException) {
    211             return $this->convertValidationExceptionToResponse($e, $request);
    212         }
    213 
    214         return $request->expectsJson()
    215                     ? $this->prepareJsonResponse($request, $e)
    216                     : $this->prepareResponse($request, $e);
    217     }
    218 
    219     /**
    220      * Prepare exception for rendering.
    221      *
    222      * @param \Throwable $e
    223      *
    224      * @return \Throwable
    225      */
    226     protected function prepareException(Throwable $e)
    227     {
    228         if ($e instanceof ModelNotFoundException) {
    229             $e = new NotFoundHttpException($e->getMessage(), $e);
    230         } elseif ($e instanceof AuthorizationException) {
    231             $e = new AccessDeniedHttpException($e->getMessage(), $e);
    232         } elseif ($e instanceof TokenMismatchException) {
    233             $e = new HttpException(419, $e->getMessage(), $e);
    234         } elseif ($e instanceof SuspiciousOperationException) {
    235             $e = new NotFoundHttpException('Bad hostname provided.', $e);
    236         }
    237 
    238         return $e;
    239     }
    240 
    241     /**
    242      * Convert an authentication exception into a response.
    243      *
    244      * @param \Illuminate\Http\Request                 $request
    245      * @param \Illuminate\Auth\AuthenticationException $exception
    246      *
    247      * @return \Symfony\Component\HttpFoundation\Response
    248      */
    249     protected function unauthenticated($request, AuthenticationException $exception)
    250     {
    251         return $request->expectsJson()
    252                     ? response()->json(['message' => $exception->getMessage()], 401)
    253                     : redirect()->guest($exception->redirectTo() ?? route('login'));
    254     }
    255 
    256     /**
    257      * Create a response object from the given validation exception.
    258      *
    259      * @param \Illuminate\Validation\ValidationException $e
    260      * @param \Illuminate\Http\Request                   $request
    261      *
    262      * @return \Symfony\Component\HttpFoundation\Response
    263      */
    264     protected function convertValidationExceptionToResponse(ValidationException $e, $request)
    265     {
    266         if ($e->response) {
    267             return $e->response;
    268         }
    269 
    270         return $request->expectsJson()
    271                     ? $this->invalidJson($request, $e)
    272                     : $this->invalid($request, $e);
    273     }
    274 
    275     /**
    276      * Convert a validation exception into a response.
    277      *
    278      * @param \Illuminate\Http\Request                   $request
    279      * @param \Illuminate\Validation\ValidationException $exception
    280      *
    281      * @return \Illuminate\Http\Response
    282      */
    283     protected function invalid($request, ValidationException $exception)
    284     {
    285         return redirect($exception->redirectTo ?? url()->previous())
    286                     ->withInput(Arr::except($request->input(), $this->dontFlash))
    287                     ->withErrors($exception->errors(), $exception->errorBag);
    288     }
    289 
    290     /**
    291      * Convert a validation exception into a JSON response.
    292      *
    293      * @param \Illuminate\Http\Request                   $request
    294      * @param \Illuminate\Validation\ValidationException $exception
    295      *
    296      * @return \Illuminate\Http\JsonResponse
    297      */
    298     protected function invalidJson($request, ValidationException $exception)
    299     {
    300         return response()->json([
    301             'message' => $exception->getMessage(),
    302             'errors'  => $exception->errors(),
    303         ], $exception->status);
    304     }
    305 
    306     /**
    307      * Prepare a response for the given exception.
    308      *
    309      * @param \Illuminate\Http\Request $request
    310      * @param \Throwable               $e
    311      *
    312      * @return \Symfony\Component\HttpFoundation\Response
    313      */
    314     protected function prepareResponse($request, Throwable $e)
    315     {
    316         if (!$this->isHttpException($e) && $this->container['config']['app.debug']) {
    317             return $this->toIlluminateResponse($this->convertExceptionToResponse($e), $e);
    318         }
    319 
    320         if (!$this->isHttpException($e)) {
    321             $e = new HttpException(500, $e->getMessage());
    322         }
    323 
    324         return $this->toIlluminateResponse(
    325             $this->renderHttpException($e),
    326             $e
    327         );
    328     }
    329 
    330     /**
    331      * Create a Symfony response for the given exception.
    332      *
    333      * @param \Throwable $e
    334      *
    335      * @return \Symfony\Component\HttpFoundation\Response
    336      */
    337     protected function convertExceptionToResponse(Throwable $e)
    338     {
    339         return SymfonyResponse::create(
    340             $this->renderExceptionContent($e),
    341             $this->isHttpException($e) ? $e->getStatusCode() : 500,
    342             $this->isHttpException($e) ? $e->getHeaders() : []
    343         );
    344     }
    345 
    346     /**
    347      * Get the response content for the given exception.
    348      *
    349      * @param \Throwable $e
    350      *
    351      * @return string
    352      */
    353     protected function renderExceptionContent(Throwable $e)
    354     {
    355         try {
    356             return $this->container['config']['app.debug'] && class_exists(Whoops::class)
    357                         ? $this->renderExceptionWithWhoops($e)
    358                         : $this->renderExceptionWithSymfony($e, $this->container['config']['app.debug']);
    359         } catch (Exception $e) {
    360             return $this->renderExceptionWithSymfony($e, $this->container['config']['app.debug']);
    361         }
    362     }
    363 
    364     /**
    365      * Render an exception to a string using "Whoops".
    366      *
    367      * @param \Throwable $e
    368      *
    369      * @return string
    370      */
    371     protected function renderExceptionWithWhoops(Throwable $e)
    372     {
    373         return tap(new Whoops(), function ($whoops) {
    374             $whoops->appendHandler($this->whoopsHandler());
    375 
    376             $whoops->writeToOutput(false);
    377 
    378             $whoops->allowQuit(false);
    379         })->handleException($e);
    380     }
    381 
    382     /**
    383      * Get the Whoops handler for the application.
    384      *
    385      * @return \Whoops\Handler\Handler
    386      */
    387     protected function whoopsHandler()
    388     {
    389         try {
    390             return $this->container(HandlerInterface::class);
    391         } catch (BindingResolutionException $e) {
    392             return (new WhoopsHandler())->forDebug();
    393         }
    394     }
    395 
    396     /**
    397      * Render an exception to a string using Symfony.
    398      *
    399      * @param \Throwable $e
    400      * @param bool       $debug
    401      *
    402      * @return string
    403      */
    404     protected function renderExceptionWithSymfony(Throwable $e, $debug)
    405     {
    406         $renderer = new HtmlErrorRenderer($debug);
    407 
    408         return $renderer->getBody($renderer->render($e));
    409     }
    410 
    411     /**
    412      * Render the given HttpException.
    413      *
    414      * @param \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $e
    415      *
    416      * @return \Symfony\Component\HttpFoundation\Response
    417      */
    418     protected function renderHttpException(HttpExceptionInterface $e)
    419     {
    420         $this->registerErrorViewPaths();
    421 
    422         if (view()->exists($view = $this->getHttpExceptionView($e))) {
    423             return response()->view($view, [
    424                 'errors'    => new ViewErrorBag(),
    425                 'exception' => $e,
    426             ], $e->getStatusCode(), $e->getHeaders());
    427         }
    428 
    429         return $this->convertExceptionToResponse($e);
    430     }
    431 
    432     /**
    433      * Register the error template hint paths.
    434      *
    435      * @return void
    436      */
    437     protected function registerErrorViewPaths()
    438     {
    439         $paths = collect($this->container['config']['view.paths']);
    440 
    441         View::replaceNamespace('errors', $paths->map(function ($path) {
    442             return "{$path}/errors";
    443         })->push(__DIR__.'/views')->all());
    444     }
    445 
    446     /**
    447      * Get the view used to render HTTP exceptions.
    448      *
    449      * @param \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $e
    450      *
    451      * @return string
    452      */
    453     protected function getHttpExceptionView(HttpExceptionInterface $e)
    454     {
    455         return "errors::{$e->getStatusCode()}";
    456     }
    457 
    458     /**
    459      * Map the given exception into an Illuminate response.
    460      *
    461      * @param \Symfony\Component\HttpFoundation\Response $response
    462      * @param \Throwable                                 $e
    463      *
    464      * @return \Illuminate\Http\Response
    465      */
    466     protected function toIlluminateResponse($response, Throwable $e)
    467     {
    468         if ($response instanceof SymfonyRedirectResponse) {
    469             $response = new RedirectResponse(
    470                 $response->getTargetUrl(),
    471                 $response->getStatusCode(),
    472                 $response->headers->all()
    473             );
    474         } else {
    475             $response = new Response(
    476                 $response->getContent(),
    477                 $response->getStatusCode(),
    478                 $response->headers->all()
    479             );
    480         }
    481 
    482         return $response->withException($e);
    483     }
    484 
    485     /**
    486      * Prepare a JSON response for the given exception.
    487      *
    488      * @param \Illuminate\Http\Request $request
    489      * @param \Throwable               $e
    490      *
    491      * @return \Illuminate\Http\JsonResponse
    492      */
    493     protected function prepareJsonResponse($request, Throwable $e)
    494     {
    495         return new JsonResponse(
    496             $this->convertExceptionToArray($e),
    497             $this->isHttpException($e) ? $e->getStatusCode() : 500,
    498             $this->isHttpException($e) ? $e->getHeaders() : [],
    499             JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES
    500         );
    501     }
    502 
    503     /**
    504      * Convert the given exception to an array.
    505      *
    506      * @param \Throwable $e
    507      *
    508      * @return array
    509      */
    510     protected function convertExceptionToArray(Throwable $e)
    511     {
    512         return $this->container['config']['app.debug'] ? [
    513             'message'   => $e->getMessage(),
    514             'exception' => get_class($e),
    515             'file'      => $e->getFile(),
    516             'line'      => $e->getLine(),
    517             'trace'     => collect($e->getTrace())->map(function ($trace) {
    518                 return Arr::except($trace, ['args']);
    519             })->all(),
    520         ] : [
    521             'message' => $this->isHttpException($e) ? $e->getMessage() : 'Server Error',
    522         ];
    523     }
    524 
    525     /**
    526      * Render an exception to the console.
    527      *
    528      * @param \Symfony\Component\Console\Output\OutputInterface $output
    529      * @param \Throwable                                        $e
    530      *
    531      * @return void
    532      */
    533     public function renderForConsole($output, Throwable $e)
    534     {
    535         (new ConsoleApplication())->renderThrowable($e, $output);
    536     }
    537 
    538     /**
    539      * Determine if the given exception is an HTTP exception.
    540      *
    541      * @param \Throwable $e
    542      *
    543      * @return bool
    544      */
    545     protected function isHttpException(Throwable $e)
    546     {
    547         return $e instanceof HttpExceptionInterface;
    548     }
     38/**
     39 * Exception handler.
     40 *
     41 * @since      1.0.0
     42 * @package    Codexshaper_Oauth_Server
     43 * @subpackage Codexshaper_Oauth_Server/src/Exceptions
     44 * @author     Md Abu Ahsan basir <maab.career@gmail.com>
     45 */
     46class Handler {
     47
     48    /**
     49     * The container implementation.
     50     *
     51     * @var \Illuminate\Contracts\Container\Container
     52     */
     53    protected $container;
     54
     55    /**
     56     * A list of the exception types that are not reported.
     57     *
     58     * @var array
     59     */
     60    protected $dont_report = array();
     61
     62    /**
     63     * A list of the internal exception types that should not be reported.
     64     *
     65     * @var array
     66     */
     67    protected $internal_dont_report = array(
     68        AuthenticationException::class,
     69        AuthorizationException::class,
     70        HttpException::class,
     71        HttpResponseException::class,
     72        ModelNotFoundException::class,
     73        SuspiciousOperationException::class,
     74        TokenMismatchException::class,
     75        ValidationException::class,
     76    );
     77
     78    /**
     79     * A list of the inputs that are never flashed for validation exceptions.
     80     *
     81     * @var array
     82     */
     83    protected $dont_flash = array(
     84        'password',
     85        'password_confirmation',
     86    );
     87
     88    /**
     89     * Create a new exception handler instance.
     90     *
     91     * @param \Illuminate\Contracts\Container\Container $container The app container.
     92     *
     93     * @return void
     94     */
     95    public function __construct( Container $container ) {
     96        $this->container = $container;
     97    }
     98
     99    /**
     100     * Report or log an exception.
     101     *
     102     * @param \Throwable $e The throwable exception.
     103     *
     104     * @throws \Exception Throw the exception.
     105     *
     106     * @return void
     107     */
     108    public function report( Throwable $e ) {
     109        if ( $this->shouldnt_report( $e ) ) {
     110            return;
     111        }
     112
     113        if ( is_callable( $report_callable = array( $e, 'report' ) ) ) {
     114            $this->container->call( $report_callable );
     115
     116            return;
     117        }
     118
     119        try {
     120            $logger = $this->container->make( LoggerInterface::class );
     121        } catch ( Exception $ex ) {
     122            throw $e;
     123        }
     124
     125        $logger->error(
     126            $e->getMessage(),
     127            array_merge(
     128                $this->exception_context( $e ),
     129                $this->context(),
     130                array( 'exception' => $e )
     131            )
     132        );
     133    }
     134
     135    /**
     136     * Determine if the exception should be reported.
     137     *
     138     * @param \Throwable $e The throwable exception.
     139     *
     140     * @return bool
     141     */
     142    public function should_report( Throwable $e ) {
     143        return ! $this->shouldnt_report( $e );
     144    }
     145
     146    /**
     147     * Determine if the exception is in the "do not report" list.
     148     *
     149     * @param \Throwable $e The throwable exception.
     150     *
     151     * @return bool
     152     */
     153    protected function shouldnt_report( Throwable $e ) {
     154        $dont_report = array_merge( $this->dont_report, $this->internal_dont_report );
     155
     156        return ! is_null(
     157            Arr::first(
     158                $dont_report,
     159                function ( $type ) use ( $e ) {
     160                    return $e instanceof $type;
     161                }
     162            )
     163        );
     164    }
     165
     166    /**
     167     * Get the default exception context variables for logging.
     168     *
     169     * @param \Throwable $e The throwable exception.
     170     *
     171     * @return array
     172     */
     173    protected function exception_context( Throwable $e ) {
     174        return array();
     175    }
     176
     177    /**
     178     * Get the default context variables for logging.
     179     *
     180     * @return array
     181     */
     182    protected function context() {
     183        try {
     184            return array_filter(
     185                array(
     186                    'userId' => Auth::id(),
     187                // 'email' => optional(Auth::user())->email,
     188                )
     189            );
     190        } catch ( Throwable $e ) {
     191            return array();
     192        }
     193    }
     194
     195    /**
     196     * Render an exception into an HTTP response.
     197     *
     198     * @param \Illuminate\Http\Request $request The app request.
     199     * @param \Throwable               $e The throwable exception.
     200     *
     201     * @throws \Throwable Throw the exception.
     202     *
     203     * @return \Symfony\Component\HttpFoundation\Response
     204     */
     205    public function render( $request, Throwable $e ) {
     206        if ( method_exists( $e, 'render' ) && $response = $e->render( $request ) ) {
     207            return Router::toResponse( $request, $response );
     208        } elseif ( $e instanceof Responsable ) {
     209            return $e->toResponse( $request );
     210        }
     211
     212        $e = $this->prepare_exception( $e );
     213
     214        if ( $e instanceof HttpResponseException ) {
     215            return $e->getResponse();
     216        } elseif ( $e instanceof AuthenticationException ) {
     217            return $this->unauthenticated( $request, $e );
     218        } elseif ( $e instanceof ValidationException ) {
     219            return $this->convert_validation_exception_to_response( $e, $request );
     220        }
     221
     222        return $request->expectsJson()
     223                    ? $this->prepare_json_response( $request, $e )
     224                    : $this->prepare_response( $request, $e );
     225    }
     226
     227    /**
     228     * Prepare exception for rendering.
     229     *
     230     * @param \Throwable $e The throwable exception.
     231     *
     232     * @return \Throwable Throw the error.
     233     */
     234    protected function prepare_exception( Throwable $e ) {
     235        if ( $e instanceof ModelNotFoundException ) {
     236            $e = new NotFoundHttpException( $e->getMessage(), $e );
     237        } elseif ( $e instanceof AuthorizationException ) {
     238            $e = new AccessDeniedHttpException( $e->getMessage(), $e );
     239        } elseif ( $e instanceof TokenMismatchException ) {
     240            $e = new HttpException( 419, $e->getMessage(), $e );
     241        } elseif ( $e instanceof SuspiciousOperationException ) {
     242            $e = new NotFoundHttpException( 'Bad hostname provided.', $e );
     243        }
     244
     245        return $e;
     246    }
     247
     248    /**
     249     * Convert an authentication exception into a response.
     250     *
     251     * @param \Illuminate\Http\Request                 $request The app request.
     252     * @param \Illuminate\Auth\AuthenticationException $exception Authenticated exception.
     253     *
     254     * @return \Symfony\Component\HttpFoundation\Response
     255     */
     256    protected function unauthenticated( $request, AuthenticationException $exception ) {
     257        return $request->expectsJson()
     258                    ? response()->json( array( 'message' => $exception->getMessage() ), 401 )
     259                    : redirect()->guest( $exception->redirectTo() ?? route( 'login' ) );
     260    }
     261
     262    /**
     263     * Create a response object from the given validation exception.
     264     *
     265     * @param \Illuminate\Validation\ValidationException $e The validator exception.
     266     * @param \Illuminate\Http\Request                   $request The app request.
     267     *
     268     * @return \Symfony\Component\HttpFoundation\Response
     269     */
     270    protected function convert_validation_exception_to_response( ValidationException $e, $request ) {
     271        if ( $e->response ) {
     272            return $e->response;
     273        }
     274
     275        return $request->expectsJson()
     276                    ? $this->invalid_json( $request, $e )
     277                    : $this->invalid( $request, $e );
     278    }
     279
     280    /**
     281     * Convert a validation exception into a response.
     282     *
     283     * @param \Illuminate\Http\Request                   $request The app request.
     284     * @param \Illuminate\Validation\ValidationException $exception The validator exception.
     285     *
     286     * @return \Illuminate\Http\Response
     287     */
     288    protected function invalid( $request, ValidationException $exception ) {
     289        return redirect( $exception->redirectTo ?? url()->previous() )
     290                    ->withInput( Arr::except( $request->input(), $this->dont_flash ) )
     291                    ->withErrors( $exception->errors(), $exception->errorBag );
     292    }
     293
     294    /**
     295     * Convert a validation exception into a JSON response.
     296     *
     297     * @param \Illuminate\Http\Request                   $request The app request.
     298     * @param \Illuminate\Validation\ValidationException $exception The validator exception.
     299     *
     300     * @return \Illuminate\Http\JsonResponse
     301     */
     302    protected function invalid_json( $request, ValidationException $exception ) {
     303        return response()->json(
     304            array(
     305                'message' => $exception->getMessage(),
     306                'errors'  => $exception->errors(),
     307            ),
     308            $exception->status
     309        );
     310    }
     311
     312    /**
     313     * Prepare a response for the given exception.
     314     *
     315     * @param \Illuminate\Http\Request $request The app request.
     316     * @param \Throwable               $e Throw the exception.
     317     *
     318     * @return \Symfony\Component\HttpFoundation\Response
     319     */
     320    protected function prepare_response( $request, Throwable $e ) {
     321        if ( ! $this->is_http_exception( $e ) && $this->container['config']['app.debug'] ) {
     322            return $this->to_illuminate_response( $this->convert_exception_to_response( $e ), $e );
     323        }
     324
     325        if ( ! $this->is_http_exception( $e ) ) {
     326            $e = new HttpException( 500, $e->getMessage() );
     327        }
     328
     329        return $this->to_illuminate_response(
     330            $this->render_http_exception( $e ),
     331            $e
     332        );
     333    }
     334
     335    /**
     336     * Create a Symfony response for the given exception.
     337     *
     338     * @param \Throwable $e Throw the exception.
     339     *
     340     * @return \Symfony\Component\HttpFoundation\Response
     341     */
     342    protected function convert_exception_to_response( Throwable $e ) {
     343        return SymfonyResponse::create(
     344            $this->render_exception_content( $e ),
     345            $this->is_http_exception( $e ) ? $e->getStatusCode() : 500,
     346            $this->is_http_exception( $e ) ? $e->getHeaders() : array()
     347        );
     348    }
     349
     350    /**
     351     * Get the response content for the given exception.
     352     *
     353     * @param \Throwable $e Throw the exception.
     354     *
     355     * @return string
     356     */
     357    protected function render_exception_content( Throwable $e ) {
     358        try {
     359            return $this->container['config']['app.debug'] && class_exists( Whoops::class )
     360                        ? $this->render_exception_with_whoops( $e )
     361                        : $this->render_exception_with_symfony( $e, $this->container['config']['app.debug'] );
     362        } catch ( Exception $e ) {
     363            return $this->render_exception_with_symfony( $e, $this->container['config']['app.debug'] );
     364        }
     365    }
     366
     367    /**
     368     * Render an exception to a string using "Whoops".
     369     *
     370     * @param \Throwable $e Throw the exception.
     371     *
     372     * @return string
     373     */
     374    protected function render_exception_with_whoops( Throwable $e ) {
     375        return tap(
     376            new Whoops(),
     377            function ( $whoops ) {
     378                $whoops->appendHandler( $this->whoops_handler() );
     379
     380                $whoops->writeToOutput( false );
     381
     382                $whoops->allowQuit( false );
     383            }
     384        )->handleException( $e );
     385    }
     386
     387    /**
     388     * Get the Whoops handler for the application.
     389     *
     390     * @return \Whoops\Handler\Handler
     391     */
     392    protected function whoops_handler() {
     393        try {
     394            return $this->container( HandlerInterface::class );
     395        } catch ( BindingResolutionException $e ) {
     396            return ( new WhoopsHandler() )->forDebug();
     397        }
     398    }
     399
     400    /**
     401     * Render an exception to a string using Symfony.
     402     *
     403     * @param \Throwable $e Throw the exception.
     404     * @param bool       $debug Enable or disable debug.
     405     *
     406     * @return string
     407     */
     408    protected function render_exception_with_symfony( Throwable $e, $debug ) {
     409        $renderer = new HtmlErrorRenderer( $debug );
     410
     411        return $renderer->getBody( $renderer->render( $e ) );
     412    }
     413
     414    /**
     415     * Render the given HttpException.
     416     *
     417     * @param \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $e Http exception.
     418     *
     419     * @return \Symfony\Component\HttpFoundation\Response
     420     */
     421    protected function render_http_exception( HttpExceptionInterface $e ) {
     422        $this->registerErrorViewPaths();
     423
     424        $view = $this->get_http_exception_view( $e );
     425
     426        if ( view()->exists( $view ) ) {
     427            return response()->view(
     428                $view,
     429                array(
     430                    'errors'    => new ViewErrorBag(),
     431                    'exception' => $e,
     432                ),
     433                $e->getStatusCode(),
     434                $e->getHeaders()
     435            );
     436        }
     437
     438        return $this->convert_exception_to_response( $e );
     439    }
     440
     441    /**
     442     * Register the error template hint paths.
     443     *
     444     * @return void
     445     */
     446    protected function register_error_view_paths() {
     447        $paths = collect( $this->container['config']['view.paths'] );
     448
     449        View::replaceNamespace(
     450            'errors',
     451            $paths->map(
     452                function ( $path ) {
     453                    return "{$path}/errors";
     454                }
     455            )->push( __DIR__ . '/views' )->all()
     456        );
     457    }
     458
     459    /**
     460     * Get the view used to render HTTP exceptions.
     461     *
     462     * @param \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $e Http exception.
     463     *
     464     * @return string
     465     */
     466    protected function get_http_exception_view( HttpExceptionInterface $e ) {
     467        return "errors::{$e->getStatusCode()}";
     468    }
     469
     470    /**
     471     * Map the given exception into an Illuminate response.
     472     *
     473     * @param \Symfony\Component\HttpFoundation\Response $response The app response.
     474     * @param \Throwable                                 $e Throw the exception.
     475     *
     476     * @return \Illuminate\Http\Response
     477     */
     478    protected function to_illuminate_response( $response, Throwable $e ) {
     479        if ( $response instanceof SymfonyRedirectResponse ) {
     480            $response = new RedirectResponse(
     481                $response->getTargetUrl(),
     482                $response->getStatusCode(),
     483                $response->headers->all()
     484            );
     485        } else {
     486            $response = new Response(
     487                $response->getContent(),
     488                $response->getStatusCode(),
     489                $response->headers->all()
     490            );
     491        }
     492
     493        return $response->withException( $e );
     494    }
     495
     496    /**
     497     * Prepare a JSON response for the given exception.
     498     *
     499     * @param \Illuminate\Http\Request $request The app request.
     500     * @param \Throwable               $e Throw the exception.
     501     *
     502     * @return \Illuminate\Http\JsonResponse
     503     */
     504    protected function prepare_json_response( $request, Throwable $e ) {
     505        return new JsonResponse(
     506            $this->convert_exception_to_array( $e ),
     507            $this->is_http_exception( $e ) ? $e->getStatusCode() : 500,
     508            $this->is_http_exception( $e ) ? $e->getHeaders() : array(),
     509            JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES
     510        );
     511    }
     512
     513    /**
     514     * Convert the given exception to an array.
     515     *
     516     * @param \Throwable $e Throw the exception.
     517     *
     518     * @return array
     519     */
     520    protected function convert_exception_to_array( Throwable $e ) {
     521        return $this->container['config']['app.debug'] ? array(
     522            'message'   => $e->getMessage(),
     523            'exception' => get_class( $e ),
     524            'file'      => $e->getFile(),
     525            'line'      => $e->getLine(),
     526            'trace'     => collect( $e->getTrace() )->map(
     527                function ( $trace ) {
     528                    return Arr::except( $trace, array( 'args' ) );
     529                }
     530            )->all(),
     531        ) : array(
     532            'message' => $this->is_http_exception( $e ) ? $e->getMessage() : 'Server Error',
     533        );
     534    }
     535
     536    /**
     537     * Render an exception to the console.
     538     *
     539     * @param \Symfony\Component\Console\Output\OutputInterface $output The symphony Output.
     540     * @param \Throwable                                        $e      Throw the exception.
     541     *
     542     * @return void
     543     */
     544    public function render_for_console( $output, Throwable $e ) {
     545        ( new ConsoleApplication() )->renderThrowable( $e, $output );
     546    }
     547
     548    /**
     549     * Determine if the given exception is an HTTP exception.
     550     *
     551     * @param \Throwable $e Throw the exception.
     552     *
     553     * @return bool
     554     */
     555    protected function is_http_exception( Throwable $e ) {
     556        return $e instanceof HttpExceptionInterface;
     557    }
    549558}
  • oauth2-server/trunk/src/Http/Kernel.php

    r2333274 r2334413  
    1313use Throwable;
    1414
    15 class Kernel implements KernelContract
    16 {
    17     /**
    18      * The application implementation.
    19      *
    20      * @var \Illuminate\Contracts\Foundation\Application
    21      */
    22     protected $app;
    23 
    24     /**
    25      * The router instance.
    26      *
    27      * @var \Illuminate\Routing\Router
    28      */
    29     protected $router;
    30 
    31     /**
    32      * The bootstrap classes for the application.
    33      *
    34      * @var array
    35      */
    36     protected $bootstrappers = [];
    37 
    38     /**
    39      * The application's middleware stack.
    40      *
    41      * @var array
    42      */
    43     protected $middleware = [];
    44 
    45     /**
    46      * The application's route middleware groups.
    47      *
    48      * @var array
    49      */
    50     protected $middlewareGroups = [];
    51 
    52     /**
    53      * The application's route middleware.
    54      *
    55      * @var array
    56      */
    57     protected $routeMiddleware = [];
    58 
    59     /**
    60      * The priority-sorted list of middleware.
    61      *
    62      * Forces non-global middleware to always be in the given order.
    63      *
    64      * @var array
    65      */
    66     protected $middlewarePriority = [];
    67 
    68     /**
    69      * Create a new HTTP kernel instance.
    70      *
    71      * @param \Illuminate\Contracts\Foundation\Application $app
    72      * @param \Illuminate\Routing\Router                   $router
    73      *
    74      * @return void
    75      */
    76     public function __construct(Container $app, Router $router)
    77     {
    78         $this->app = $app;
    79         $this->router = $router;
    80 
    81         $this->syncMiddlewareToRouter();
    82     }
    83 
    84     /**
    85      * Handle an incoming HTTP request.
    86      *
    87      * @param \Illuminate\Http\Request $request
    88      *
    89      * @return \Illuminate\Http\Response
    90      */
    91     public function handle($request)
    92     {
    93         try {
    94             $request->enableHttpMethodParameterOverride();
    95             $response = $this->sendRequestThroughRouter($request);
    96         } catch (Throwable $e) {
    97             throw new \Exception($e, 1);
    98             $this->reportException($e);
    99 
    100             $response = $this->renderException($request, $e);
    101         }
    102 
    103         $this->app['events']->dispatch(
    104             new RequestHandled($request, $response)
    105         );
    106 
    107         return $response;
    108     }
    109 
    110     /**
    111      * Send the given request through the middleware / router.
    112      *
    113      * @param \Illuminate\Http\Request $request
    114      *
    115      * @return \Illuminate\Http\Response
    116      */
    117     protected function sendRequestThroughRouter($request)
    118     {
    119         $this->app->instance('request', $request);
    120 
    121         Facade::clearResolvedInstance('request');
    122 
    123         $this->bootstrap();
    124 
    125         return (new Pipeline($this->app))
    126                     ->send($request)
    127                     // ->through($this->app->shouldSkipMiddleware() ? [] : $this->middleware)
    128                     ->through($this->middleware)
    129                     ->then($this->dispatchToRouter());
    130     }
    131 
    132     /**
    133      * Bootstrap the application for HTTP requests.
    134      *
    135      * @return void
    136      */
    137     public function bootstrap()
    138     {
    139         // if (! $this->app->hasBeenBootstrapped()) {
    140         //     $this->app->bootstrapWith($this->bootstrappers());
    141         // }
    142     }
    143 
    144     /**
    145      * Get the route dispatcher callback.
    146      *
    147      * @return \Closure
    148      */
    149     protected function dispatchToRouter()
    150     {
    151         return function ($request) {
    152             $this->app->instance('request', $request);
    153 
    154             return $this->router->dispatch($request);
    155         };
    156     }
    157 
    158     /**
    159      * Call the terminate method on any terminable middleware.
    160      *
    161      * @param \Illuminate\Http\Request  $request
    162      * @param \Illuminate\Http\Response $response
    163      *
    164      * @return void
    165      */
    166     public function terminate($request, $response)
    167     {
    168         $this->terminateMiddleware($request, $response);
    169 
    170         $this->app->terminate();
    171     }
    172 
    173     /**
    174      * Call the terminate method on any terminable middleware.
    175      *
    176      * @param \Illuminate\Http\Request  $request
    177      * @param \Illuminate\Http\Response $response
    178      *
    179      * @return void
    180      */
    181     protected function terminateMiddleware($request, $response)
    182     {
    183         $middlewares = $this->app->shouldSkipMiddleware() ? [] : array_merge(
    184             $this->gatherRouteMiddleware($request),
    185             $this->middleware
    186         );
    187 
    188         foreach ($middlewares as $middleware) {
    189             if (!is_string($middleware)) {
    190                 continue;
    191             }
    192 
    193             [$name] = $this->parseMiddleware($middleware);
    194 
    195             $instance = $this->app->make($name);
    196 
    197             if (method_exists($instance, 'terminate')) {
    198                 $instance->terminate($request, $response);
    199             }
    200         }
    201     }
    202 
    203     /**
    204      * Gather the route middleware for the given request.
    205      *
    206      * @param \Illuminate\Http\Request $request
    207      *
    208      * @return array
    209      */
    210     protected function gatherRouteMiddleware($request)
    211     {
    212         if ($route = $request->route()) {
    213             return $this->router->gatherRouteMiddleware($route);
    214         }
    215 
    216         return [];
    217     }
    218 
    219     /**
    220      * Parse a middleware string to get the name and parameters.
    221      *
    222      * @param string $middleware
    223      *
    224      * @return array
    225      */
    226     protected function parseMiddleware($middleware)
    227     {
    228         [$name, $parameters] = array_pad(explode(':', $middleware, 2), 2, []);
    229 
    230         if (is_string($parameters)) {
    231             $parameters = explode(',', $parameters);
    232         }
    233 
    234         return [$name, $parameters];
    235     }
    236 
    237     /**
    238      * Determine if the kernel has a given middleware.
    239      *
    240      * @param string $middleware
    241      *
    242      * @return bool
    243      */
    244     public function hasMiddleware($middleware)
    245     {
    246         return in_array($middleware, $this->middleware);
    247     }
    248 
    249     /**
    250      * Add a new middleware to beginning of the stack if it does not already exist.
    251      *
    252      * @param string $middleware
    253      *
    254      * @return $this
    255      */
    256     public function prependMiddleware($middleware)
    257     {
    258         if (array_search($middleware, $this->middleware) === false) {
    259             array_unshift($this->middleware, $middleware);
    260         }
    261 
    262         return $this;
    263     }
    264 
    265     /**
    266      * Add a new middleware to end of the stack if it does not already exist.
    267      *
    268      * @param string $middleware
    269      *
    270      * @return $this
    271      */
    272     public function pushMiddleware($middleware)
    273     {
    274         if (array_search($middleware, $this->middleware) === false) {
    275             $this->middleware[] = $middleware;
    276         }
    277 
    278         return $this;
    279     }
    280 
    281     /**
    282      * Prepend the given middleware to the given middleware group.
    283      *
    284      * @param string $group
    285      * @param string $middleware
    286      *
    287      * @throws \InvalidArgumentException
    288      *
    289      * @return $this
    290      */
    291     public function prependMiddlewareToGroup($group, $middleware)
    292     {
    293         if (!isset($this->middlewareGroups[$group])) {
    294             throw new InvalidArgumentException("The [{$group}] middleware group has not been defined.");
    295         }
    296 
    297         if (array_search($middleware, $this->middlewareGroups[$group]) === false) {
    298             array_unshift($this->middlewareGroups[$group], $middleware);
    299         }
    300 
    301         $this->syncMiddlewareToRouter();
    302 
    303         return $this;
    304     }
    305 
    306     /**
    307      * Append the given middleware to the given middleware group.
    308      *
    309      * @param string $group
    310      * @param string $middleware
    311      *
    312      * @throws \InvalidArgumentException
    313      *
    314      * @return $this
    315      */
    316     public function appendMiddlewareToGroup($group, $middleware)
    317     {
    318         if (!isset($this->middlewareGroups[$group])) {
    319             throw new InvalidArgumentException("The [{$group}] middleware group has not been defined.");
    320         }
    321 
    322         if (array_search($middleware, $this->middlewareGroups[$group]) === false) {
    323             $this->middlewareGroups[$group][] = $middleware;
    324         }
    325 
    326         $this->syncMiddlewareToRouter();
    327 
    328         return $this;
    329     }
    330 
    331     /**
    332      * Prepend the given middleware to the middleware priority list.
    333      *
    334      * @param string $middleware
    335      *
    336      * @return $this
    337      */
    338     public function prependToMiddlewarePriority($middleware)
    339     {
    340         if (!in_array($middleware, $this->middlewarePriority)) {
    341             array_unshift($this->middlewarePriority, $middleware);
    342         }
    343 
    344         $this->syncMiddlewareToRouter();
    345 
    346         return $this;
    347     }
    348 
    349     /**
    350      * Append the given middleware to the middleware priority list.
    351      *
    352      * @param string $middleware
    353      *
    354      * @return $this
    355      */
    356     public function appendToMiddlewarePriority($middleware)
    357     {
    358         if (!in_array($middleware, $this->middlewarePriority)) {
    359             $this->middlewarePriority[] = $middleware;
    360         }
    361 
    362         $this->syncMiddlewareToRouter();
    363 
    364         return $this;
    365     }
    366 
    367     /**
    368      * Sync the current state of the middleware to the router.
    369      *
    370      * @return void
    371      */
    372     protected function syncMiddlewareToRouter()
    373     {
    374         $this->router->middlewarePriority = $this->middlewarePriority;
    375 
    376         foreach ($this->middlewareGroups as $key => $middleware) {
    377             $this->router->middlewareGroup($key, $middleware);
    378         }
    379 
    380         foreach ($this->routeMiddleware as $key => $middleware) {
    381             $this->router->aliasMiddleware($key, $middleware);
    382         }
    383     }
    384 
    385     /**
    386      * Get the bootstrap classes for the application.
    387      *
    388      * @return array
    389      */
    390     protected function bootstrappers()
    391     {
    392         return $this->bootstrappers;
    393     }
    394 
    395     /**
    396      * Report the exception to the exception handler.
    397      *
    398      * @param \Throwable $e
    399      *
    400      * @return void
    401      */
    402     protected function reportException(Throwable $e)
    403     {
    404         $this->app[ExceptionHandler::class]->report($e);
    405     }
    406 
    407     /**
    408      * Render the exception to a response.
    409      *
    410      * @param \Illuminate\Http\Request $request
    411      * @param \Throwable               $e
    412      *
    413      * @return \Symfony\Component\HttpFoundation\Response
    414      */
    415     protected function renderException($request, Throwable $e)
    416     {
    417         return $this->app[ExceptionHandler::class]->render($request, $e);
    418     }
    419 
    420     /**
    421      * Get the application's route middleware groups.
    422      *
    423      * @return array
    424      */
    425     public function getMiddlewareGroups()
    426     {
    427         return $this->middlewareGroups;
    428     }
    429 
    430     /**
    431      * Get the application's route middleware.
    432      *
    433      * @return array
    434      */
    435     public function getRouteMiddleware()
    436     {
    437         return $this->routeMiddleware;
    438     }
    439 
    440     /**
    441      * Get the Laravel application instance.
    442      *
    443      * @return \Illuminate\Contracts\Foundation\Application
    444      */
    445     public function getApplication()
    446     {
    447         return $this->app;
    448     }
     15/**
     16 * Http handler.
     17 *
     18 * @link       https://github.com/maab16
     19 * @since      1.0.0
     20 *
     21 * @package    Codexshaper_Oauth_Server
     22 * @subpackage Codexshaper_Oauth_Server/src/Http
     23 */
     24
     25/**
     26 * Http handler.
     27 *
     28 * @since      1.0.0
     29 * @package    Codexshaper_Oauth_Server
     30 * @subpackage Codexshaper_Oauth_Server/src/Http
     31 * @author     Md Abu Ahsan basir <maab.career@gmail.com>
     32 */
     33class Kernel {
     34
     35    /**
     36     * The application implementation.
     37     *
     38     * @var \Codexshaper_Oauth_Server\Application
     39     */
     40    protected $app;
     41
     42    /**
     43     * The router instance.
     44     *
     45     * @var \Illuminate\Routing\Router
     46     */
     47    protected $router;
     48
     49    /**
     50     * The bootstrap classes for the application.
     51     *
     52     * @var array
     53     */
     54    protected $bootstrappers = array();
     55
     56    /**
     57     * The application's middleware stack.
     58     *
     59     * @var array
     60     */
     61    protected $middleware = array();
     62
     63    /**
     64     * The application's route middleware groups.
     65     *
     66     * @var array
     67     */
     68    protected $middleware_groups = array();
     69
     70    /**
     71     * The application's route middleware.
     72     *
     73     * @var array
     74     */
     75    protected $route_middleware = array();
     76
     77    /**
     78     * The priority-sorted list of middleware.
     79     *
     80     * Forces non-global middleware to always be in the given order.
     81     *
     82     * @var array
     83     */
     84    protected $middleware_priority = array();
     85
     86    /**
     87     * Create a new HTTP kernel instance.
     88     *
     89     * @param \Illuminate\Contracts\Container\Container $app The app container.
     90     * @param \Illuminate\Routing\Router                $router The app router.
     91     *
     92     * @return void
     93     */
     94    public function __construct( Container $app, Router $router ) {
     95        $this->app    = $app;
     96        $this->router = $router;
     97
     98        $this->sync_middleware_to_router();
     99    }
     100
     101    /**
     102     * Handle an incoming HTTP request.
     103     *
     104     * @param \Illuminate\Http\Request $request The app request.
     105     *
     106     * @throws \Exception Throw error if response failed.
     107     * @return \Illuminate\Http\Response
     108     */
     109    public function handle( $request ) {
     110        try {
     111            $request->enableHttpMethodParameterOverride();
     112            $response = $this->send_request_through_router( $request );
     113        } catch ( Throwable $e ) {
     114            throw new \Exception( $e, 1 );
     115            $this->reportException( $e );
     116
     117            $response = $this->render_exception( $request, $e );
     118        }
     119
     120        $this->app['events']->dispatch(
     121            new RequestHandled( $request, $response )
     122        );
     123
     124        return $response;
     125    }
     126
     127    /**
     128     * Send the given request through the middleware / router.
     129     *
     130     * @param \Illuminate\Http\Request $request The app request.
     131     *
     132     * @return \Illuminate\Http\Response
     133     */
     134    protected function send_request_through_router( $request ) {
     135        $this->app->instance( 'request', $request );
     136
     137        Facade::clearResolvedInstance( 'request' );
     138
     139        $this->bootstrap();
     140
     141        return ( new Pipeline( $this->app ) )
     142                    ->send( $request )
     143                    ->through( $this->middleware )
     144                    ->then( $this->dispatch_to_router() );
     145    }
     146
     147    /**
     148     * Bootstrap the application for HTTP requests.
     149     *
     150     * @return void
     151     */
     152    public function bootstrap() {
     153        /*
     154        if (! $this->app->hasBeenBootstrapped()) {
     155        $this->app->bootstrapWith($this->bootstrappers());
     156        }
     157        */
     158    }
     159
     160    /**
     161     * Get the route dispatcher callback.
     162     *
     163     * @return \Closure
     164     */
     165    protected function dispatch_to_router() {
     166        return function ( $request ) {
     167            $this->app->instance( 'request', $request );
     168
     169            return $this->router->dispatch( $request );
     170        };
     171    }
     172
     173    /**
     174     * Call the terminate method on any terminable middleware.
     175     *
     176     * @param \Illuminate\Http\Request  $request The app request.
     177     * @param \Illuminate\Http\Response $response The app response.
     178     *
     179     * @return void
     180     */
     181    public function terminate( $request, $response ) {
     182        $this->terminate_middleware( $request, $response );
     183
     184        $this->app->terminate();
     185    }
     186
     187    /**
     188     * Call the terminate method on any terminable middleware.
     189     *
     190     * @param \Illuminate\Http\Request  $request The app request.
     191     * @param \Illuminate\Http\Response $response The app response.
     192     *
     193     * @return void
     194     */
     195    protected function terminate_middleware( $request, $response ) {
     196        $middlewares = $this->app->shouldSkipMiddleware() ? array() : array_merge(
     197            $this->gather_route_middleware( $request ),
     198            $this->middleware
     199        );
     200
     201        foreach ( $middlewares as $middleware ) {
     202            if ( ! is_string( $middleware ) ) {
     203                continue;
     204            }
     205
     206            $name = $this->parse_middleware( $middleware );
     207
     208            $instance = $this->app->make( $name );
     209
     210            if ( method_exists( $instance, 'terminate' ) ) {
     211                $instance->terminate( $request, $response );
     212            }
     213        }
     214    }
     215
     216    /**
     217     * Gather the route middleware for the given request.
     218     *
     219     * @param \Illuminate\Http\Request $request The app request.
     220     *
     221     * @return array
     222     */
     223    protected function gather_route_middleware( $request ) {
     224        $route = $request->route();
     225        if ( $route ) {
     226            return $this->router->gatherRouteMiddleware( $route );
     227        }
     228
     229        return array();
     230    }
     231
     232    /**
     233     * Parse a middleware string to get the name and parameters.
     234     *
     235     * @param string $middleware The app middleware.
     236     *
     237     * @return array
     238     */
     239    protected function parse_middleware( $middleware ) {
     240        list( $name, $parameters ) = array_pad( explode( ':', $middleware, 2 ), 2, array() );
     241
     242        if ( is_string( $parameters ) ) {
     243            $parameters = explode( ',', $parameters );
     244        }
     245
     246        return array( $name, $parameters );
     247    }
     248
     249    /**
     250     * Determine if the kernel has a given middleware.
     251     *
     252     * @param string $middleware The app middleware.
     253     *
     254     * @return bool
     255     */
     256    public function has_middleware( $middleware ) {
     257        return in_array( $middleware, $this->middleware );
     258    }
     259
     260    /**
     261     * Add a new middleware to beginning of the stack if it does not already exist.
     262     *
     263     * @param string $middleware The app middleware.
     264     *
     265     * @return $this
     266     */
     267    public function prepend_middleware( $middleware ) {
     268        if ( array_search( $middleware, $this->middleware ) === false ) {
     269            array_unshift( $this->middleware, $middleware );
     270        }
     271
     272        return $this;
     273    }
     274
     275    /**
     276     * Add a new middleware to end of the stack if it does not already exist.
     277     *
     278     * @param string $middleware The app middleware.
     279     *
     280     * @return $this
     281     */
     282    public function push_middleware( $middleware ) {
     283        if ( array_search( $middleware, $this->middleware ) === false ) {
     284            $this->middleware[] = $middleware;
     285        }
     286
     287        return $this;
     288    }
     289
     290    /**
     291     * Prepend the given middleware to the given middleware group.
     292     *
     293     * @param string $group The app group.
     294     * @param string $middleware The app middleware.
     295     *
     296     * @throws \InvalidArgumentException Throw when argument is invalid.
     297     *
     298     * @return $this
     299     */
     300    public function prepend_middleware_to_group( $group, $middleware ) {
     301        if ( ! isset( $this->middleware_groups[ $group ] ) ) {
     302            throw new InvalidArgumentException( "The [{$group}] middleware group has not been defined." );
     303        }
     304
     305        if ( array_search( $middleware, $this->middleware_groups[ $group ] ) === false ) {
     306            array_unshift( $this->middleware_groups[ $group ], $middleware );
     307        }
     308
     309        $this->sync_middleware_to_router();
     310
     311        return $this;
     312    }
     313
     314    /**
     315     * Append the given middleware to the given middleware group.
     316     *
     317     * @param string $group The app group.
     318     * @param string $middleware The app middleware.
     319     *
     320     * @throws \InvalidArgumentException Throw when argument is invalid.
     321     *
     322     * @return $this
     323     */
     324    public function append_middleware_to_group( $group, $middleware ) {
     325        if ( ! isset( $this->middleware_groups[ $group ] ) ) {
     326            throw new InvalidArgumentException( "The [{$group}] middleware group has not been defined." );
     327        }
     328
     329        if ( array_search( $middleware, $this->middleware_groups[ $group ] ) === false ) {
     330            $this->middleware_groups[ $group ][] = $middleware;
     331        }
     332
     333        $this->sync_middleware_to_router();
     334
     335        return $this;
     336    }
     337
     338    /**
     339     * Prepend the given middleware to the middleware priority list.
     340     *
     341     * @param string $middleware The app middleware.
     342     *
     343     * @return $this
     344     */
     345    public function prepend_to_middleware_priority( $middleware ) {
     346        if ( ! in_array( $middleware, $this->middleware_priority ) ) {
     347            array_unshift( $this->middleware_priority, $middleware );
     348        }
     349
     350        $this->sync_middleware_to_router();
     351
     352        return $this;
     353    }
     354
     355    /**
     356     * Append the given middleware to the middleware priority list.
     357     *
     358     * @param string $middleware The app middleware.
     359     *
     360     * @return $this
     361     */
     362    public function append_to_middleware_priority( $middleware ) {
     363        if ( ! in_array( $middleware, $this->middleware_priority ) ) {
     364            $this->middleware_priority[] = $middleware;
     365        }
     366
     367        $this->sync_middleware_to_router();
     368
     369        return $this;
     370    }
     371
     372    /**
     373     * Sync the current state of the middleware to the router.
     374     *
     375     * @return void
     376     */
     377    protected function sync_middleware_to_router() {
     378        $this->router->middlewarePriority = $this->middleware_priority;
     379
     380        foreach ( $this->middleware_groups as $key => $middleware ) {
     381            $this->router->middlewareGroup( $key, $middleware );
     382        }
     383
     384        foreach ( $this->route_middleware as $key => $middleware ) {
     385            $this->router->aliasMiddleware( $key, $middleware );
     386        }
     387    }
     388
     389    /**
     390     * Get the bootstrap classes for the application.
     391     *
     392     * @return array
     393     */
     394    protected function bootstrappers() {
     395        return $this->bootstrappers;
     396    }
     397
     398    /**
     399     * Report the exception to the exception handler.
     400     *
     401     * @param \Throwable $e Throwable error.
     402     *
     403     * @return void
     404     */
     405    protected function report_exception( Throwable $e ) {
     406        $this->app[ ExceptionHandler::class ]->report( $e );
     407    }
     408
     409    /**
     410     * Render the exception to a response.
     411     *
     412     * @param \Illuminate\Http\Request $request The app middlerequestware.
     413     * @param \Throwable               $e Throwable error.
     414     *
     415     * @return \Symfony\Component\HttpFoundation\Response
     416     */
     417    protected function render_exception( $request, Throwable $e ) {
     418        return $this->app[ ExceptionHandler::class ]->render( $request, $e );
     419    }
     420
     421    /**
     422     * Get the application's route middleware groups.
     423     *
     424     * @return array
     425     */
     426    public function get_middleware_groups() {
     427        return $this->middleware_groups;
     428    }
     429
     430    /**
     431     * Get the application's route middleware.
     432     *
     433     * @return array
     434     */
     435    public function get_route_middleware() {
     436        return $this->route_middleware;
     437    }
     438
     439    /**
     440     * Get the Laravel application instance.
     441     *
     442     * @return \Illuminate\Contracts\Foundation\Application
     443     */
     444    public function get_application() {
     445        return $this->app;
     446    }
    449447}
  • oauth2-server/trunk/src/Support/Facades/Config.php

    r2333274 r2334413  
    33namespace Codexshaper_Oauth_Server\Support\Facades;
    44
    5 class Config
    6 {
    7     protected $config = [];
     5/**
     6 * Configuration file.
     7 *
     8 * @link       https://github.com/maab16
     9 * @since      1.0.0
     10 *
     11 * @package    Codexshaper_Oauth_Server
     12 * @subpackage Codexshaper_Oauth_Server/src/Support/Facades
     13 */
    814
    9     public function __construct($options = [])
    10     {
    11         $dir = __DIR__ . '/../../../../../../';
     15/**
     16 * Configuration file.
     17 *
     18 * @since      1.0.0
     19 * @package    Codexshaper_Oauth_Server
     20 * @subpackage Codexshaper_Oauth_Server/src/Support/Facades
     21 * @author     Md Abu Ahsan basir <maab.career@gmail.com>
     22 */
     23class Config {
    1224
    13         if (! empty($options) && isset($options['paths']['root'])) {
    14             $dir = rtrim($options['paths']['root'], "/") . '/';
    15         }
    16        
    17         foreach (glob($dir . 'config/*.php') as $file) {
    18             $index = pathinfo($file)['filename'];
    19             $this->config[$index] = require_once $file;
    20         }
    21     }
     25    /**
     26     * The config array.
     27     *
     28     * @since    1.0.0
     29     * @access   protected
     30     * @var      array    $config
     31     */
     32    protected $config = array();
    2233
    23     public function get($config, $default = null)
    24     {
    25         $keys = explode('.', $config);
    26         $filename = array_shift($keys);
    27         $data = $this->config[$filename];
     34    /**
     35     * Define the core functionality of the plugin.
     36     *
     37     * @since    1.0.0
     38     * @param   array $options The default options.
     39     *
     40     * @return  void
     41     */
     42    public function __construct( $options = array() ) {
     43        $dir = __DIR__ . '/../../../../../../';
    2844
    29         foreach ($keys as $key) {
    30             if (is_array($data) && array_key_exists($key, $data)) {
    31                 $data = $data[$key];
    32             } else {
    33                 $data = null;
    34             }
    35         }
     45        if ( ! empty( $options ) && isset( $options['paths']['root'] ) ) {
     46            $dir = rtrim( $options['paths']['root'], '/' ) . '/';
     47        }
    3648
    37         if (!$data) {
    38             $data = $default;
    39         }
     49        foreach ( glob( $dir . 'config/*.php' ) as $file ) {
     50            $index                  = pathinfo( $file )['filename'];
     51            $this->config[ $index ] = require_once $file;
     52        }
     53    }
    4054
    41         return $data;
    42     }
     55    /**
     56     * Get the config value by key.
     57     *
     58     * @since    1.0.0
     59     * @param   string $config The config keys.
     60     * @param   string $default The default value.
     61     *
     62     * @return  mixed
     63     */
     64    public function get( $config, $default = null ) {
     65        $keys     = explode( '.', $config );
     66        $filename = array_shift( $keys );
     67        $data     = $this->config[ $filename ];
     68
     69        foreach ( $keys as $key ) {
     70            if ( is_array( $data ) && array_key_exists( $key, $data ) ) {
     71                $data = $data[ $key ];
     72            } else {
     73                $data = null;
     74            }
     75        }
     76
     77        if ( ! $data ) {
     78            $data = $default;
     79        }
     80
     81        return $data;
     82    }
    4383}
  • oauth2-server/trunk/src/Support/Facades/Route.php

    r2333274 r2334413  
    55use Illuminate\Support\Facades\Facade;
    66
    7 class Route extends Facade
    8 {
    9     /**
    10      * Get the registered name of the component.
    11      *
    12      * @return string
    13      */
    14     protected static function getFacadeAccessor()
    15     {
    16         return \Codexshaper_Oauth_Server\Router::class;
    17     }
     7/**
     8 * Route facade.
     9 *
     10 * @link       https://github.com/maab16
     11 * @since      1.0.0
     12 *
     13 * @package    Codexshaper_Oauth_Server
     14 * @subpackage Codexshaper_Oauth_Server/src/Support/Facades
     15 */
     16
     17/**
     18 *  Route facade.
     19 *
     20 * @since      1.0.0
     21 * @package    Codexshaper_Oauth_Server
     22 * @subpackage Codexshaper_Oauth_Server/src/Support/Facades
     23 * @author     Md Abu Ahsan basir <maab.career@gmail.com>
     24 */
     25class Route extends Facade {
     26
     27    /**
     28     * Get the registered name of the component.
     29     *
     30     * @return string
     31     */
     32    protected static function getFacadeAccessor() {
     33        return \Codexshaper_Oauth_Server\Router::class;
     34    }
    1835}
  • oauth2-server/trunk/src/helpers.php

    r2333274 r2334413  
    44use Illuminate\Container\Container;
    55
    6 if (!function_exists('codexshaper_oauth_server_csrf_token')) {
    7     function codexshaper_oauth_server_csrf_token($action = 'codexshaper_oauth_server_nonce')
    8     {
    9         return wp_create_nonce($action);
    10     }
     6if ( ! function_exists( 'codexshaper_oauth_server_csrf_token' ) ) {
     7    /**
     8     * Generate wp nonce.
     9     *
     10     * @param string|null $action   This is the nonce action name.
     11     *
     12     * @return null|string
     13     */
     14    function codexshaper_oauth_server_csrf_token( $action = 'codexshaper_oauth_server_nonce' ) {
     15        return wp_create_nonce( $action );
     16    }
    1117}
    1218
    13 if (!function_exists('codexshaper_oauth_server_app')) {
    14     /**
    15      * Get the available container instance.
    16     *
    17      * @param string|null $abstract
    18      * @param array       $parameters
    19      *
    20      * @return mixed|\Illuminate\Contracts\Foundation\Application
    21      */
    22     function codexshaper_oauth_server_app($abstract = null, array $parameters = [])
    23     {
    24         $app = new Application();
    25         if (is_null($abstract) && $container != null) {
    26             return $container;
    27         }
     19if ( ! function_exists( 'codexshaper_oauth_server_config' ) ) {
     20    /**
     21     * Get / set the specified configuration value.
     22    *
     23     * If an array is passed as the key, we will assume you want to set an array of values.
     24     *
     25     * @param array|string|null $key This is the key for config array.
     26     * @param mixed             $default This is the default config value.
     27     *
     28     * @return mixed|\Illuminate\Config\Repository
     29     */
     30    function codexshaper_oauth_server_config( $key = null, $default = null ) {
     31        if ( is_null( $key ) ) {
     32            return app( 'config' );
     33        }
    2834
    29         return Container::getInstance()->make($abstract, $parameters);
    30     }
     35        if ( is_array( $key ) ) {
     36            return app( 'config' )->set( $key );
     37        }
     38
     39        return app( 'config' )->get( $key, $default );
     40    }
    3141}
    3242
    33 if (!function_exists('codexshaper_oauth_server_config')) {
    34     /**
    35      * Get / set the specified configuration value.
    36      *
    37      * If an array is passed as the key, we will assume you want to set an array of values.
    38      *
    39      * @param array|string|null $key
    40      * @param mixed             $default
    41      *
    42      * @return mixed|\Illuminate\Config\Repository
    43      */
    44     function codexshaper_oauth_server_config($key = null, $default = null)
    45     {
    46         if (is_null($key)) {
    47             return app('config');
    48         }
     43if ( ! function_exists( 'codexshaper_oauth_server_view' ) ) {
     44    /**
     45     * Render blade view.
     46     *
     47     * @param string $view   This is the filename.
     48     * @param array  $data   This is the view data.
     49     * @param array  $merge_data   This is the merge data for view.
     50     *
     51     * @throws \Exception This will throw an exception if view class doesn't exists.
     52     * @return null|string
     53     */
     54    function codexshaper_oauth_server_view( $view, $data = array(), $merge_data = array() ) {
     55        if ( ! class_exists( \CodexShaper\Blade\View::class ) ) {
     56            throw new \Exception( 'View not resolved. Please install View' );
     57        }
    4958
    50         if (is_array($key)) {
    51             return app('config')->set($key);
    52         }
    53 
    54         return app('config')->get($key, $default);
    55     }
     59        return ( new \CodexShaper\Blade\View( array( __DIR__ . '/../resources/views' ), __DIR__ . '/../storage/cache' ) )->make( $view, $data = array(), $merge_data = array() );
     60    }
    5661}
    57 
    58 if (!function_exists('codexshaper_oauth_server_view')) {
    59     function codexshaper_oauth_server_view($view, $data = [], $mergeData = [])
    60     {
    61         if (!class_exists(\CodexShaper\Blade\View::class)) {
    62             throw new \Exception('View not resolved. Please install View');
    63         }
    64 
    65         return (new \CodexShaper\Blade\View([__DIR__ . '/../resources/views'], __DIR__ . '/../storage/cache'))->make($view, $data = [], $mergeData = []);
    66     }
    67 }
Note: See TracChangeset for help on using the changeset viewer.