Sunday, April 6, 2014

CakePHP Ajax login

I've started using Cakephp for a new project that I'm doing and I've become stuck on how to login using client side technologies. The application will be accessing cake via restful api calls and I'm trying to get the login working using ajax but am unsure of how to write the request. This is my login function in the UsersController:

public function login() {
        if ((AuthComponent::user('id'))) {
            $this->Session->setFlash(__('Warning: You are already logged in as ' . AuthComponent::user('username')));
        }
        if ($this->request->is('post')) {
            if ($this->Auth->login()) {
                return $this->redirect($this->Auth->redirect());
            }
            $this->Session->setFlash(__('Invalid username or password, try again'));
        }
        else if ($this->RequestHandler->isAjax())
        {
            $tmpUser['User']['username'] = $this->request->params['username'];
            $tmpUser['User']['password'] = $this->request->params['password'];
            if($this->Auth->login($tmpUser))
            {
                $this->Session->setFlash('Login Passed');
            }
            else
            {
                $this->Session->setFlash('Login Failed');
            }
        }

        if ($this->request->is('ajax')) {
            $this->layout = 'ajax';
            if ($this->Auth->login()) {
                $message = "Logged in successfully";
                $this->set(array(
                    'message' => $message,
                    '_serialize' => array('message')
                ));
                return $this->redirect($this->Auth->redirect());
            }
            $this->Session->setFlash(__('Invalid username or password, try again'));
            $message = "Invalid username or password, try again";
            $this->set(array(
                'message' => $message,
                '_serialize' => array('message')
            ));
        }
    }

Any ideas?

--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP

---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cake-php+unsubscribe@googlegroups.com.
To post to this group, send email to cake-php@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php.
For more options, visit https://groups.google.com/d/optout.

No comments: