Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connecting Android Application With CakePhp website

Is it possible to communicate an android Application with cakePhp website and share data? If it is possible, I want to create an application that can login into the website; my doubt is:

  1. How to pass user name and password from our application to cakephp websites login page? Can anybody show me an example program?

  2. How cakephp controller handle this request and respond to this request? Please show me an example program?

(I am a beginner in android and cakephp.)

like image 507
Sibin Francis Avatar asked Feb 18 '23 22:02

Sibin Francis


2 Answers

Quick answer -- YES!

We just finished pushing an Android app to the market place that does this exact thing. Here's how we did it:

1) Download and learn to use Cordova PhoneGap (2.2.0 is the latest version) within Eclipse. This makes the whole thing so much easier with just some HTML and a lot of Javascript.

2) In your JS, create methods that push the login information using AJAX parameters. Example:

document.addEventListener('deviceready', onDeviceReady, false);

function onDeviceReady() {

    $("#login").click(function() {
        $email = $("#UserEmail").val();
        $pass = $("#UserPassword").val();
            $.ajax({
                    url : yourURL + 'api/users/login',
                    async : false,
                    data : {
                        'email' : $email,
                        'password' : $pass
                    },
                    dataType : 'json',
                    type : 'post',
                    success : function(result) {
                            /**
                             * do your login redirects or 
                             * use localStorage to store your data 
                             * on the phone. Keep in mind the limitations of 
                             * per domain localStorage of 5MB
                             */
                            // you are officially "logged in"
                            window.location.href = "yourUrl.html";
                            return;
                    },
                    error : function(xhr, status, err) {
                        // do your stuff when the login fails
                    }
            });
    }
}

3) In Cake / PHP, your Users controller here will take the username and password data in the AJAX call and use that for its authentication.

<?php

class UsersController extends AppController {

    public $name = 'Users';

    public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('api_login');
    }

    public function api_login() {
        $this->autoRender = false;

        if ($this->request->data && isset($this->request->data['email']) && isset($this->request->data['password'])) {

            $arrUser  = $this->User->find('all',array(
                    'conditions'=>array(
                            'email'=> $this->request->data['email'],
                            'password' => $this->Auth->password($this->request->data['password']),
                    )
                )
            );

            if (count($arrUser) > 0) {
                $this->Session->write('Auth.User',$arrUser[0]['User']);

                // Do your login functions

                $arrReturn['status'] = 'SUCCESS';
                $arrReturn['data'] = array( 'loginSuccess' => 1,'user_id' => $arrUser[0]['User']['id'] );

            } else {
                $arrReturn['status'] = 'NOTLOGGEDIN';
                $arrReturn['data'] = array( 'loginSuccess' => 0 );
            }
        } else {
            $arrReturn['status'] = 'NOTLOGGEDIN';
            $arrReturn['data'] = array( 'loginSuccess' => 0 );
        }
        echo json_encode($arrReturn);
    }
}
?>

That's pretty much it. You are now authenticated to CakePHP.

You do not need to use "api_", you can use any function name you want, but this helped us keep a handle on what we allowed mobile users to do versus web users.

Now, these are just the building blocks. You basically have to create a whole version of your site on the phone using HTML and Javascript, so depending on your application it may be easier just to create a responsive design to your site and allow mobile browsing.

HTH!

like image 175
J.R. Avatar answered Feb 27 '23 06:02

J.R.


Use Admad JWT Auth Plugin

If you use cakephp3 change your login function with this one :

public function token() {

        $user = $this->Auth->identify();


        if (!$user) {

            throw new UnauthorizedException('Invalid username (email) or password');
        }

        $this->set([
            'success' => true,
            'data' => [
                'token' => JWT::encode([
                    'sub' => $user['id'],
                    'exp' =>  time() + 604800
                ],
                Security::salt())
            ],
            '_serialize' => ['success', 'data']
        ]);
}

You can read this tutorial about REST Api and JWT Auth Implementation

http://www.bravo-kernel.com/2015/04/how-to-add-jwt-authentication-to-a-cakephp-3-rest-api/

like image 21
user3343097 Avatar answered Feb 27 '23 07:02

user3343097