ApiController::beforeAction PHP Method

beforeAction() public method

public beforeAction ( $action )
    public function beforeAction($action)
    {
        foreach (Yii::app()->log->routes as $route) {
            if ($route instanceof CWebLogRoute) {
                $route->enabled = false;
            }
        }
        // Output format can be selected using a special GET param or by Accept: header
        if (isset($_GET['_format'])) {
            if (preg_match('/json/', $_GET['_format'])) {
                $this->output_format = 'json';
            } elseif (preg_match('/xml/', $_GET['_format'])) {
                $this->output_format = 'xml';
            }
        } else {
            foreach (Yii::app()->request->preferredAcceptTypes as $type) {
                if ($type['baseType'] == 'xml' || $type['subType'] == 'xml' || $type['subType'] == '*') {
                    $this->output_format = 'xml';
                    break;
                }
                if ($type['baseType'] == 'json' || $type['subType'] == 'json') {
                    $this->output_format = 'json';
                    break;
                }
            }
        }
        if (!isset($this->output_format)) {
            $this->sendResponse(406);
        }
        // Attach error handlers as soon as we know what format to send the error in
        Yii::app()->attachEventHandler('onError', array($this, 'handleError'));
        Yii::app()->attachEventHandler('onException', array($this, 'handleException'));
        if (!isset($_SERVER['PHP_AUTH_USER'])) {
            $this->sendError('Authentication required', 401, FhirValueSet::ISSUETYPE_SECURITY_LOGIN);
        }
        $identity = new UserIdentity($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
        if (!$identity->authenticate()) {
            $this->sendError('Authentication failed', 401, FhirValueSet::ISSUETYPE_SECURITY_UNKNOWN);
        }
        Yii::app()->user->login($identity);
        if (!Yii::app()->user->checkAccess('OprnApi')) {
            $this->sendError('Not authorised', 403, FhirValueSet::ISSUETYPE_SECURITY_FORBIDDEN);
        }
        // Tags, aka HTTP categories: http://hl7.org/implement/standards/fhir/http.html#tags
        $tags = CategoryHeader::load();
        $this->general_tags = $tags->get('http://hl7.org/fhir/tag');
        $this->profile_tags = $tags->get('http://hl7.org/fhir/tag/profile');
        $this->security_tags = $tags->get('http://hl7.org/fhir/tag/security');
        return true;
    }

Usage Example

 /**
  * If Disqus comments are enabled, disable the entire API
  * @param  CAction $action   The action we are using
  * @return CAction
  */
 public function beforeAction($action)
 {
     if (Cii::getConfig('useDisqusComments') == "1") {
         throw new CHttpException(403, Yii::t('Api.comment', 'The comment API is not available while Disqus comments are enabled.'));
     }
     return parent::beforeAction($action);
 }