Giter Site home page Giter Site logo

Comments (14)

evan108108 avatar evan108108 commented on July 26, 2024

You sure can! You have complete control over what users are authorized. You simply have to hook this event "req.auth.ajax.user" and return true to authorize and false to deny. You can do this globally in your main config or on the controller level;

Example 1 (Doing it Globally). In your config/main.php:

$config = array(
    ..,
    'params'=>[
        'RestfullYii' => [
            'rreq.auth.ajax.user'=>function() {
                return true;
            },
        ]
    ]
);

Example 2 (doing it in your controller). Add this method to your controller:

public function restEvents()
{
        $this->onRest('req.auth.ajax.user', function() {
            return true;
        });
}

Now keep in mind you will have to be careful because this will grant all access to unlogged-in users. You can add some fine grained control either here or by hooking one of the other 'auth' events like 'req.auth.uri' which will allow you to deny access to particular routes / resources and particular HTTP verbs (GET, PUT, POST, DELETE). Take a look. I think once you get a hang of using the event system to change behavior you will be hooked.

from restfullyii.

elviskudo avatar elviskudo commented on July 26, 2024

sorry to open this closed issue,

because i have the problem that not soluted yet,
i choose the example 2 in my controller, but still 401 unathorized, please give me solution, thanks
great extension by the way

from restfullyii.

evan108108 avatar evan108108 commented on July 26, 2024

Please supply your controller code.

from restfullyii.

elviskudo avatar elviskudo commented on July 26, 2024
class ApiBusinessController extends ERestController {
/**
     * @return array action filters
     */
    public function _filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }
    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function _accessRules() {
        return array(
            array('allow', // allow authenticated user to perform 'create' and 'update' actions\
                'users'=>array('@'),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }
    /**
     * Returns the model assosiated with this controller.
     * The assumption is that the model name matches your controller name
     * If this is not the case you should override this method in your controller
     */
    public function getModel()
    {
        if ($this->model === null) {
            $modelName = 'Company';
            $this->model = new $modelName;
        }
        $this->_attachBehaviors($this->model);
        return $this->model;
    }
}
public function restEvents()
    {
        $this->onRest('req.auth.ajax.user', function() {
            return true;
        });
    }
    /**
     * This is broken out as a sperate method from actionRestList
     * To allow for easy overriding in the controller
     * and to allow for easy unit testing
     */
    public function doRestList()
    {
        $this->outputHelper(
            'Business Retrieved Successfully',
            // $this->getModel()
                // ->filter($this->restFilter)->orderBy($this->restSort)
                // ->limit($this->restLimit)->offset($this->restOffset)
            Company::model()->findAll()
        );
    }
    public function outputHelper($message, $results, $totalCount = 0, $model = null)
    {
        if (is_null($model))
            $model = lcfirst(get_class($this->model));
        else
            $model = lcfirst($model);
        $this->renderJson(array(
            'data' => array(
                'success' => true,
                'totalCount' => $totalCount,
                'message' => $message,
                $model => $this->allToArray($results)
            )
        ));
    }
    /**
     * This is broken out as a sperate method from actionResUpdate
     * To allow for easy overriding in the controller
     * and to allow for easy unit testing
     */
    public function doRestUpdate($id, $data)
    {
        $model = $this->loadOneModel($id);
        if (is_null($model)) {
            $this->HTTPStatus = $this->getHttpStatus(404);
            throw new CHttpException(404, 'Business Not Found');
        } else {
            $model->attributes = $data;
            if ($model->save()) {
                header('success', true, 200);
                echo CJSON::encode(array(
                        'data' => array(
                            'success' => true,
                            strtolower(get_class($model)) => $model->attributes
                        )
                    )
                );
                exit;
            } else {
                header('error', true, 400);
                $errors = $model->getErrors();
                echo CJSON::encode(array(
                        'data' => array(
                            'success' => false,
                            'errors' => $errors
                        )
                    )
                );
                exit;
            }
        }
    }
    public function doRestDelete($id)
    {
        $model = $this->loadOneModel($id);
        if (is_null($model)) {
            $this->HTTPStatus = $this->getHttpStatus(404);
            throw new CHttpException(404, 'Business Not Found');
        } else {
            if ($model->delete())
                $data = array('success' => true, 'message' => 'Business Deleted', 'id' => $id);
            else {
                $this->HTTPStatus = $this->getHttpStatus(406);
                throw new CHttpException(406, 'Could not delete Business with ID: ' . $id);
            }
            $this->renderJson(array('data' => $data));
        }
    }
    public function doRestCreate($data)
    {
        $model = new Company;
        $model->attributes = $data;
        $model->com_created_date = time();
        if ($model->save()) {
            header('success', true, 200);
            echo CJSON::encode(array(
                    'data' => array(
                        'success' => true,
                        strtolower(get_class($model)) => $model->attributes
                    )
                )
            );
            exit;
        } else {
            header('error', true, 400);
            $errors = $model->getErrors();
            echo CJSON::encode(array(
                    'success' => false,
                    'message' => $errors,
                    'errorCode' => '400'
                )
            );
            exit;
        }
    }
    public function onException($event)
    {
        if (!$this->developmentFlag && ($event->exception->statusCode == 500 || is_null($event->exception->statusCode)))
            $message = "Internal Server Error";
        else {
            $message = $event->exception->getMessage();
            if ($tempMessage = CJSON::decode($message))
                $message = $tempMessage;
        }
        $errorCode = (!isset($event->exception->statusCode) || is_null($event->exception->statusCode)) ? 500 : $event->exception->statusCode;
        $this->renderJson(array('errorCode' => $errorCode, 'message' => $message, 'success' => false));
        $event->handled = true;
        header('error', true, $errorCode);
    }
}

That's correct?
And please give me how to get that api with username and password, and my php is 5.3
Thanks, your extension is great

from restfullyii.

evan108108 avatar evan108108 commented on July 26, 2024

I see. You are using the 1.1x php 5.3 compatible version of RESTFullYii. For this version you will need to add the following code to your controller.

public function validateAjaxUser($action)
{
   //some logic
   return true;
}

from restfullyii.

elviskudo avatar elviskudo commented on July 26, 2024

Thanks for replay.
Then, what kind of some logic there?
and what about my question before about, how to get that api with username and password? until now, i still don't understand about that

from restfullyii.

evan108108 avatar evan108108 commented on July 26, 2024

This is how you do that. If validateAjaxUser returns true then access is granted and if it returns false access is denied. Its as simple as that. You can apply any logic you want to determine weather or not you would like to return true or false. There is no point in passing any username and password as they could not possibly be secure!!! Instead you should check the action and make sure its something you want to allow for any user that is not logged-in, if so return true, if not check that the user is logged-in and return true, false if they are not.

from restfullyii.

evan108108 avatar evan108108 commented on July 26, 2024

I should point out that this if for validating a local AJAX/Javascript user. If you want to access remotely you can simply pass the username and password in the header as showing in the documentation ( -H "X_REST_USERNAME: admin@restuser" -H "X_REST_PASSWORD: admin@Access" )

from restfullyii.

elviskudo avatar elviskudo commented on July 26, 2024

maybe there's some example link to call the api from my ajax

$.ajax({
  method: 'GET',
  url: 'http://api.mydomain.com/api/apiBusiness/1',
  success: function(data) {
    console.log(data);
  }
});

and data is json right? that's correct.
but i don't understand how to throw X_REST_USERNAME and X_REST_PASSWORD from my ajax above.
thanks again

from restfullyii.

evan108108 avatar evan108108 commented on July 26, 2024

You should not do that!!! Don't send the user and password!!! This is not secure!!! You should use the validateAjaxUser method as explained above.

That said, if you insist on doing this you may:

DO NOT DO THIS!

$.ajax({
  method: 'GET',
  url: 'http://api.mydomain.com/api/apiBusiness/1',
  headers: {
      'X_REST_USERNAME': 'admin@restuser',
      'X_REST_PASSWORD': 'admin@Access'
   },
  success: function(data) {
    console.log(data);
  }
});

from restfullyii.

evan108108 avatar evan108108 commented on July 26, 2024

You should log the user in and control access via validateAjaxUser.

from restfullyii.

evan108108 avatar evan108108 commented on July 26, 2024

Has your question been answered?

from restfullyii.

evan108108 avatar evan108108 commented on July 26, 2024

Since you are using PHP5.3.x you might try using "cccssw" PHP5.3.x port which incorporates the latest and greatest features of RESTFullYii: PHP 5.3.x port by cccssw

I have not tested this but I have been looking over the code and it looks solid.

If you decide to use this you will have to change your controller and config a bit, but all of that is explained in the README. Good Luck!

from restfullyii.

elviskudo avatar elviskudo commented on July 26, 2024

thanks a lot.
Now i understand about that
many thanks about your extension

from restfullyii.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.