2

I was creating a REST API for logging in using CakePHP. My question is:

  1. In routes.php, what do I fill in mapresources("xxx")?
  2. POST /XXX.format XXXController::add() <= this is given in documentation. If my app folders are like this: /localhost/FC/app/webroot/ etc. What would the URL be for the post request through which I would send JSON format username and password? Currently I access index.php in webroot by typing localhost/FC.
  3. If i name my controller Apis instead of recipes below, like ApisController.php, where do I do changes in the code below? And how do I use add? it's not given in the documentation:

    class RecipesController extends AppController {
    
    public $components = array('RequestHandler');
    
    public function index() {
        $recipes = $this->Recipe->find('all');
        $this->set(array(
            'recipes' => $recipes,
            '_serialize' => array('recipes')
        ));
    }
    
    public function view($id) {
        $recipe = $this->Recipe->findById($id);
        $this->set(array(
            'recipe' => $recipe,
            '_serialize' => array('recipe')
        ));
    }
    
    public function edit($id) {
        $this->Recipe->id = $id;
        if ($this->Recipe->save($this->request->data)) {
            $message = 'Saved';
        } else {
            $message = 'Error';
        }
        $this->set(array(
            'message' => $message,
            '_serialize' => array('message')
        ));
    }
    
    public function delete($id) {
        if ($this->Recipe->delete($id)) {
            $message = 'Deleted';
        } else {
            $message = 'Error';
        }
        $this->set(array(
            'message' => $message,
            '_serialize' => array('message')
        ));
    }
    
    }
    
  4. Lastly, if I send a user-id password in json to this url, what command do I do to return a 200 ok response?

I know its a bit much, but I'm really a novice and I'm not able to grasp this concept even though I've been at it for 3 days and am about to faint of exhaustion. Please help!

Right now, the controller is customer:

public function login() {
           if ($this->Session->check('Customer')) {  //to check if already logged in



            $this->Session->setFlash('You are already logged in as ' . $this->Session->read('Customer.Customer.fname') . ' ' . $this->Session->read('Customer.Customer.sname'));
            $this->redirect($this->Session->read('ref'));
        } else {
            if ($this->request->is('post')||$this->request->is('ajax')) {   //receives data by ajax from popup of login


                $name = $this->request->data('name');
                $pwd = $this->request->data('pwd');
                $pwd = md5($pwd);   //hashing of password
                $customer = $this->Customer->findByEmail($name);
                if (!$customer) {
                    $msg = 'Wrong Username or password/false';
                }   
                if ($customer['Customer']['active'] == 1) {


                    $customer = $this->Customer->findByEmailAndPassword($name, $pwd);

                    if (@$customer) {
                        $this->Session->write('Customer', $customer);
                      $msg = $customer['Customer']['fname'].'/true';

                        if ($this->Session->check('order')) {
                            $msg = $this->Session->read('loc_id').'/set';

                        } 
                    } else {
                        $msg = 'Wrong Username or password/false';
                    }
                } else {
                    $msg = 'Your account in not active. Please check your mails to get the activation link/false';
                }


            }
        }
        echo $msg;
1
  • 2
    Just FYI, I don't know how you do save passwords, but you seem to only md5 them. Please note that md5 is not a secure hashing and should only be used as an identifier (example file md5 checksum). Please check out bcrypt, scrypt or pbkdf2 hashings which are a lot more secure! CakePHP has a default implementation of bcrypt so it's not too hard to use! Commented Sep 10, 2013 at 20:39

1 Answer 1

1
  1. If you use a controller named ApisController, you have to fill mapresource with api. Example: Router::mapResources('api');

  2. These are the default routes created:

    • GET /apis.format RecipesController::index()
    • GET /apis/123.format RecipesController::view(123)
    • POST /apis.format RecipesController::add()
    • PUT /apis/123.format RecipesController::edit(123)
    • DELETE/apis/123.format RecipesController::delete(123)
    • POST /apis/123.format RecipesController::edit(123)

So if your homepage is at: http://localhost/FC/, you can access the resources at http://localhost/FC/apis.format .

You have to substitute format with json or xml. If you want to use XML or JSON you have to declare it in routes.php adding Router::parseExtensions();

  1. You have to rename your controller in ApisController and change every occurence of $this->Recipe in $this->Api, also you have to create a Model for Api and a table on the db. For xml and json you have to create views in /app/Views/Apis/xml/index.ctp and so on.

    // app/View/Apis/xml/index.ctp // Do some formatting and manipulation on // the $recipes array. $xml = Xml::fromArray(array('response' => $apis)); echo $xml->asXML();

Last answer, your server normally answer with a 200 when there are no errors.

I suggest you to begin with something easier and to look to Cakephp conventions. http://book.cakephp.org/2.0/en/getting-started/cakephp-conventions.html

Good work!

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks so much! So if I'm sending a JSON request with data containing username and password, what do I declare in the controller? Also, what does the 123 represent? I've declared json in Router::parseextensions('json'); I've created a view in apis/json/index.ctp which has this: <?php echo json_encode ($url); ?> What do i fill in $url? is it gotten from the controller? I want to send uid and pwd and check, then if authenticated send a json response message saying "user authenticated". Thanks!
123 is the id of the api. When in a controller you do $this->set('info',$user) in a view you can use a var $info with the value of the $user var. I think you need also login logic in the controller.
Edit in the answer is my current controller. Could you tell me how to modify that to send a json request back as a message? Does $user contain the message string?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.