BEdita API doc | 3-corylus
  • Class
  • Tree
  • Deprecated
  • Download

Classes

  • Addon
  • AddressbookController
  • AddressbookShell
  • AdminController
  • Alias
  • Annotation
  • ApiAuthComponent
  • ApiBaseController
  • ApiFormatterComponent
  • ApiUploadComponent
  • ApiValidatorComponent
  • AppController
  • AppError
  • AppHelper
  • Application
  • AppModel
  • Area
  • AreasController
  • Audio
  • AuthenticationsController
  • BannedIp
  • BEAppModel
  • BEAppObjectModel
  • BeAuthComponent
  • BeAuthFacebookComponent
  • BeAuthGoogleComponent
  • BeAuthTwitterComponent
  • BeCallbackManager
  • BeConfigure
  • BeCustomPropertyComponent
  • BeditaAnnotationModel
  • BeditaBaseShell
  • BeditaCollectionModel
  • BeditaContentModel
  • BeditaExportFilter
  • BeditaImportFilter
  • BeditaObjectModel
  • BeditaProductModel
  • BeditaShell
  • BeditaSimpleObjectModel
  • BeditaSimpleStreamModel
  • BeditaStreamModel
  • BeEmbedFlashHelper
  • BeEmbedHtml5Helper
  • BeEmbedMediaHelper
  • BeErrorCode
  • BeExceptionHandler
  • BEFile
  • BeFileHandlerComponent
  • BeFormHelper
  • BeFrontHelper
  • BeHashComponent
  • BeHtmlHelper
  • BeLangTextComponent
  • BeLib
  • BeMailComponent
  • BEObject
  • BeObjectCache
  • BePaginatorToolbarHelper
  • BeSchema
  • BeSecurityComponent
  • BeSystem
  • BeSystemComponent
  • BeThumb
  • BeTimeHelper
  • BeToolbarHelper
  • BeTreeComponent
  • BeTreeHelper
  • BeUploadToObjComponent
  • BeurlHelper
  • BeVimeoComponent
  • BeYoutubeComponent
  • BuildFilterBehavior
  • CacheableBehavior
  • CacheShell
  • CallbackBehavior
  • CaptchaComponent
  • Caption
  • CaptionsBehavior
  • Card
  • CardsImportFilter
  • Category
  • CleanupDataTask
  • CleanupTask
  • Comment
  • CommentsController
  • CompactResultBehavior
  • Content
  • CreateIndexFieldsBehavior
  • DataShell
  • DataTransfer
  • DateItem
  • DbadminShell
  • DeleteDependentObjectBehavior
  • DeleteObjectBehavior
  • DeployShell
  • Document
  • DocumentsController
  • DumpModel
  • EditorialContentsShell
  • EditorNote
  • Event
  • EventLog
  • EventsController
  • FilesController
  • ForeignDependenceSaveBehavior
  • FrontendController
  • FrontendShell
  • GalleriesController
  • Gallery
  • GeoTag
  • GettextShell
  • Git
  • GravatarHelper
  • Group
  • HashJob
  • History
  • HomeController
  • Image
  • ImageInfoHelper
  • JsonExportFilter
  • JsonImportFilter
  • JsonView
  • LangText
  • Link
  • MailGroup
  • MailGroupCard
  • MailJob
  • MailLog
  • MailMessage
  • MailShell
  • MailTemplate
  • Mask
  • MediaShell
  • MigrateDumpModel
  • MigrateShell
  • Migration
  • MigrationBase
  • MigrationDateItemsShell
  • Module
  • ModulesController
  • ModuleShell
  • MultimediaController
  • NewsController
  • NewsletterController
  • NewsletterShell
  • NotifyBehavior
  • ObjectEditor
  • ObjectProperty
  • ObjectRelation
  • ObjectType
  • ObjectUser
  • PagesController
  • Permission
  • PermissionModule
  • PermsHelper
  • Product
  • Property
  • PropertyOption
  • PublicationShell
  • RedisShell
  • RelationCheck
  • RelationRepair
  • RelationShell
  • RelationStats
  • RemoveDummyNameBehavior
  • ResponseHandlerComponent
  • RestClientModel
  • Revision
  • RevisionObjectBehavior
  • SearchText
  • SearchTextSaveBehavior
  • Section
  • SectionDummy
  • SessionFilterComponent
  • SessionFilterHelper
  • ShortNews
  • SmartyView
  • SoapClientModel
  • SplitterSql
  • StatisticsController
  • Stream
  • StreamLog
  • StreamsController
  • Svn
  • TagsController
  • ThemeSmartyView
  • ThumbnailHelper
  • ThumbShell
  • TransactionComponent
  • TransactionFS
  • TranslationsController
  • Tree
  • TrHelper
  • User
  • UserProperty
  • UsersController
  • Utility
  • Version
  • Video
  • VimeoHelper
  • WebmarksController
  • XmlExportFilter
  • XmlImportFilter
  • XmlJsonConverter
  • XmlView
  • YoutubeHelper

Interfaces

  • ApiAuthInterface
  • MediaProviderInterface
  • UploadableInterface

Exceptions

  • BeditaAjaxException
  • BEditaAllowURLException
  • BeditaBadRequestException
  • BeditaConflictException
  • BEditaDeleteStreamObjException
  • BeditaException
  • BEditaFileExistException
  • BeditaForbiddenException
  • BeditaFrontAccessException
  • BeditaHashException
  • BEditaInfoException
  • BeditaInternalErrorException
  • BEditaIOException
  • BeditaLengthRequiredException
  • BeditaMailException
  • BEditaMediaProviderException
  • BeditaMethodNotAllowedException
  • BEditaMIMEException
  • BeditaNotFoundException
  • BeditaNotImplementedException
  • BeditaPublicationException
  • BeditaRuntimeException
  • BEditaSaveStreamObjException
  • BeditaServiceUnavailableException
  • BeditaUnauthorizedException
  • BEditaUploadPHPException
  • BEditaURLException
  1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 
<?php
/*-----8<--------------------------------------------------------------------
 *
 * BEdita - a semantic content management framework
 *
 * Copyright 2015 ChannelWeb Srl, Chialab Srl
 *
 * This file is part of BEdita: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * BEdita is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with BEdita (see LICENSE.LGPL).
 * If not, see <http://gnu.org/licenses/lgpl-3.0.html>.
 *
 *------------------------------------------------------------------->8-----
 */

App::import('Vendor', 'BeforeValidException', array('file' => 'php-jwt' . DS . 'Exceptions' . DS . 'BeforeValidException.php'));
App::import('Vendor', 'ExpiredException', array('file' => 'php-jwt' . DS . 'Exceptions' . DS . 'ExpiredException.php'));
App::import('Vendor', 'SignatureInvalidException', array('file' => 'php-jwt' . DS . 'Exceptions' . DS . 'SignatureInvalidException.php'));
App::import('Vendor', 'JWT', array('file' => 'php-jwt' . DS . 'Authentication' . DS . 'JWT.php'));
App::import(
    'File',
    'ApiAuthInterface',
    array('file' => BEDITA_CORE_PATH . DS . 'controllers' . DS . 'components' . DS  . 'api_auth_interface.php')
);

/**
 * REST API auth component
 * 'access_token' used for authentication is a JSON Web Token (JWT)
 *
 * @see http://jwt.io
 * @see https://tools.ietf.org/html/rfc7519 (for full specs)
 */
class ApiAuthComponent extends Object implements ApiAuthInterface {

    /**
     * The Controller
     *
     * @var Controller
     */
    protected $controller;

    /**
     * The authenticate user
     * It's false if user is not authenticated
     *
     * @var array|bool
     */
    protected $user = false;

    /**
     * The JWT generated or read from request
     *
     * @var string
     */
    protected $token = null;

    /**
     * The payload used for token generation
     *
     * @var array
     */
    protected $payload = array();

    /**
     * Configuration used to customize token generation.
     * - `JWT` contains configurations to generate the `access_token`
     * - `refreshTokenExpiresIn` is the `refresh_token` expires time from now.
     *   It can be configured with relative time from now. See `strtotime()`.
     *
     * @var array
     */
    public $config = array(
        'JWT' => array(
            'expiresIn' => 600, // in seconds (10 minutes)
            'alg' => 'HS256',
        ),
        'refreshTokenExpiresIn' => '1 month',
    );

    /**
     * Initialize component callback
     *
     * @param Controller $controller the controller
     * @param array $settings component configuration
     * @return void
     */
    public function initialize(Controller $controller, $settings = array()) {
        Configure::write('Session.start', false);
        $this->controller = $controller;
        $this->token = null;
        $authConf = Configure::read('api.auth');
        if ($authConf && is_array($authConf)) {
            $this->config = Set::merge($this->config, $authConf);
        }
    }

    /**
     * Startup component callback
     * Set up JWT 'iss' to public_url if it's not set
     *
     * @param Controller $controller the controller
     * @param array $settings component configuration
     * @return void
     */
    public function startup($controller , $settings = array()) {
        if (empty($this->config['JWT']['iss'])) {
            $this->config['JWT']['iss'] = $controller->viewVars['publication']['public_url'];
        }
    }

    /**
     * Identify and return an user starting from JWT
     * If user was already identified return it immediately
     * Return false if no token exists or no user found
     *
     * @return array|bool
     */
    public function identify() {
        if (!empty($this->user)) {
            return $this->user;
        }
        $this->user = false;
        $token = $this->getToken();
        if ($token) {
            $this->user = $this->findUser($token);
        }
        return $this->user;
    }

    /**
     * Authenticate user starting from username and password
     *
     * @param string $username the username
     * @param string $password the user password
     * @param array $authGroupName an array of groups authorized to login
     * @return bool
     */
    public function authenticate($username, $password, array $authGroupName = array()) {
        $userModel = ClassRegistry::init('User');
        $conditions = array(
            'User.userid' => $username,
            'User.passwd' => md5($password),
            'User.valid' => 1
        );
        $userModel->containLevel('default');
        $u = $userModel->find($conditions);
        if (!$u) {
            return false;
        }

        // check group auth
        $authorized = false;
        foreach ($u['Group'] as $g) {
            // check backend_auth???
            if ($g['backend_auth'] == 1 || in_array($g['name'], $authGroupName)) {
                $authorized = true;
                break;
            }
        }

        if ($authorized === false) {
            // avoid userid in logs / use ID instead or partially hide userid
            $this->log(sprintf('User login not authorized: %s', Mask::email($username)));

            return false;
        }

        $userModel->compact($u, true);

        $this->user = $u;
        return true;
    }

    /**
     * Generate and return a new JWT.
     * If user is not identified in return null.
     * 
     * The garbage collection of refresh_token is also applied.
     *
     * @return string|null
     */
    public function generateToken() {
        $this->token = null;
        if (!empty($this->user)) {
            $iat = time();
            $this->payload = array(
                'iss' => $this->config['JWT']['iss'],
                'iat' => $iat,
                //'jti' => uniqid(), // a unique id for this token (for revocation purposes, it should be blacklisted)
                'exp' => $iat + $this->config['JWT']['expiresIn'],
                'id' => $this->user['id']
            );

            $this->token = JWT::encode($this->payload, Configure::read('Security.salt'), $this->config['JWT']['alg']);
        }

        // refresh_token garbage collection
        $this->gc();

        return $this->token;
    }

    /**
     * Renew a JWT using a refresh token
     * If it fails to renew JWT then return false
     *
     * @param string $refreshToken the refresh token
     * @return string|bool
     */
    public function renewToken($refreshToken) {
        $token = false;
        // @todo missing to check against groups permissions to verify nothing was changed
        $this->user = $this->findUser($refreshToken, 'refresh');
        if ($this->user) {
            $token = $this->generateToken();
        }
        return $token;
    }

    /**
     * Garbage collection for `refresh_token`.
     * Delete from `hash_jobs` table the reference to expired `refresh_token`
     * with some probability
     *
     * @return void
     */
    protected function gc() {
        if (mt_rand(1, 100) > 5) {
            return;
        }

        $hashJob = ClassRegistry::init('HashJob');
        $now = date('Y-m-d H:i:s');
        $hashJob->deleteAll(array(
            'service_type' => 'refresh_token',
            'expired <' => $now,
        ));
    }

    /**
     * Generate a refresh token to use for renew JWT
     * The refresh token is saved in hash_jobs table
     * If user is not identified then return false
     *
     * @return string|bool
     */
    public function generateRefreshToken() {
        if (!$this->identify()) {
            return false;
        }

        $refreshToken = Security::generateAuthKey();
        $hashJob = ClassRegistry::init('HashJob');
        $data = array(
            'service_type' => 'refresh_token',
            'user_id' => $this->user['id'],
            'hash' => $refreshToken,
            'expired' => $this->getRefreshTokenExpireDate(),
            'used_for' => 'JWT'
        );
        if (!$hashJob->save($data)) {
            return false;
        }
        return $refreshToken;
    }

    /**
     * Return the expire date for `refresh_token`
     *
     * @return string
     * @throws BeditaInternalErrorException When calculation of expired time for refresh_token fails.
     */
    protected function getRefreshTokenExpireDate() {
        $expireDate = date('Y-m-d H:i:s', strtotime($this->config['refreshTokenExpiresIn']));
        if ($expireDate === false) {
            throw new BeditaInternalErrorException('Error calculating the expired time for refresh_token using ' . $this->config['refreshTokenExpiresIn']);
        }

        return $expireDate;
    }

    /**
     * Revoke a refresh token
     *
     * @param string $refreshToken the rfresh token to remove
     * @return bool
     * @throws BeditaNotFoundException When missing refresh token to revoke
     */
    public function revokeRefreshToken($refreshToken) {
        if (!$this->identify()) {
            return false;
        }

        $hashJob = ClassRegistry::init('HashJob');
        $hashId = $hashJob->field('id', array(
            'service_type' => 'refresh_token',
            'hash' => $refreshToken,
            'user_id' => $this->user['id']
        ));
        if (!$hashId) {
            throw new BeditaNotFoundException('missing token or already removed');
        }

        return $hashJob->delete($hashId);
    }

    /**
     * Return the payload used to generate JWT
     *
     * @return array
     */
    public function getPayload() {
        return $this->payload;
    }

    /**
     * Return the token reading from Authorization header or from query url
     * If token is been already read return it
     * Return false if no token is found
     *
     * @return string|bool
     */
    public function getToken() {
        if (!empty($this->token)) {
            return $this->token;
        }

        $token = env('HTTP_AUTHORIZATION') ? env('HTTP_AUTHORIZATION') : env('REDIRECT_HTTP_AUTHORIZATION');

        if (!$token && function_exists('getallheaders')) {
            $headers = getallheaders();
            if (isset($headers['Authorization'])) {
                $token = $headers['Authorization'];
            }
        }

        if ($token && substr($token, 0, 7) === 'Bearer ') {
            $this->token = substr($token, 7);
        } elseif (!empty($this->params['url']['access_token'])) {
            $this->token = $this->params['url']['access_token'];
        }

        return $this->token ? $this->token : false;
    }

    /**
     * Return the updated time to token expiration (in seconds)
     *
     * @return int
     */
    public function expiresIn() {
        return (!empty($this->payload)) ? $this->payload['exp'] - time() : 0;
    }

    /**
     * Find the user starting from a token and a token type:
     *
     * - if $type is 'jwt' try to get user starting from JWT
     * - if $type is 'refresh' try to get user starting from refresh token saved in `hash_jobs` table.
     *   `hash_jobs` table is touched to update `expired` field.
     *
     * If no user was found return false
     *
     * @param string $token the token
     * @param string $type the token type ('jwt' or 'refresh')
     * @return array|bool
     */
    protected function findUser($token, $type = 'jwt') {
        if ($type == 'jwt') {
            try {
                $salt = Configure::read('Security.salt');
                $decodedToken = JWT::decode($token, $salt, array($this->config['JWT']['alg']));
            } catch (ExpiredException  $e) {
                throw new BeditaUnauthorizedException('token_expired');
            } catch (Exception $e) {
                throw new BeditaUnauthorizedException('token_not_valid');
            }

            // Token missing data
            if (!isset($decodedToken->id)) {
                throw new BeditaUnauthorizedException('token_not_valid');
            }

            $userId = $decodedToken->id;
            $this->payload = (array) $decodedToken;
        // refresh
        } elseif ($type == 'refresh') {
            $hashJob = ClassRegistry::init('HashJob');
            $hash = $hashJob->find('first', array(
                'conditions' => array(
                    'hash' => $token,
                    'NOT' => array(
                        'status' => 'expired'
                    )
                )
            ));

            if (empty($hash)) {
                return false;
            }

            // update expired field
            $hash['HashJob']['expired'] = $this->getRefreshTokenExpireDate();
            $hashJob->save($hash);

            $userId = $hash['HashJob']['user_id'];
        } else {
            return false;
        }

        $userModel = ClassRegistry::init('User');
        $userModel->containLevel('default');
        $user = $userModel->find('first', array(
            'conditions' => array(
                'User.id' => $userId,
                'User.valid' => 1
            )
        ));

        if (empty($user)) {
            return false;
        }

        $userModel->compact($user, true);
        return $user;
    }

    /**
     * Return the userid
     * It replaces BeAuthComponent::userid() in API context
     *
     * @return string
     */
    public function userid() {
        return !empty($this->user['userid']) ? $this->user['userid'] : '';
    }

    /**
     * Return the user data
     * it replaces BeAuthComponent::getUserSession() in API context
     *
     * @return array
     */
    public function getUserSession() {
        return $this->user ? $this->user : array();
    }

    /**
     * Get the current identified user
     * It replaces BeAuthComponent::getUser() in API context
     *
     * @return array
     */
    public function getUser() {
        return $this->getUserSession();
    }

}
BEdita API doc | 3-corylus API documentation generated by ApiGen