Codeigniter web services

后端 未结 2 530
忘了有多久
忘了有多久 2020-12-30 03:31

I\'m using Codeigniter 1.7. Does anyone have any experience of creating web services with PHP, particularly within the CodeIgniter framework? What are security measures need

相关标签:
2条回答
  • 2020-12-30 03:56
    <?php 
    //First Create Api file in controller name Api.php
    /*
    api call in postman
    login : 
        email , password
        http://localhost/demo/api/login
        https://prnt.sc/pbs2do
    register (user): : 
        fullname , email ,  password , recipeunit
        http://localhost/demo/api/signup
        https://prnt.sc/pbs3cc
    
    profile and list (user profile and all user ) : 
        View Profile : email, if all then pass blank  
    http://localhost/demo/api/userlist
    
    
    change password :  
        http://localhost/demo/api/change_password
        email ,password ,newpassword , conformnewpassword (if needed)
        https://prnt.sc/pbs3rt
    
    */
    
    if(!defined('BASEPATH')) exit('No direct script access allowed');
    
    require APPPATH . '/libraries/BaseController.php'; // this file will download first and pest in library
    
    class Api extends BaseController
    {
        /**
         * This is default constructor of the class
         */
        public function __construct()
        {
            parent::__construct();
           $this->load->model('api/signup_model','signup_model');
        }
    
        /**
         * Index Page for this controller.
         */
        public function index()
        {
    
        }
        public function signup() 
        {
            $this->signup_model->signup();
        }
        public function login()
        {
            $this->signup_model->login();
        }
        public function userlist()
        {
            $this->signup_model->userlist();
        }
        public function edit_user()
        {
            $this->signup_model->edit_user();
        }
        public function change_password()
        {
            $this->signup_model->change_password();
        }
        public function testpass()
        {
            $this->signup_model->testpass();
        }
    }
    
    // then create model in model folder create api folder create signup_model.php file 
    //after that
    
    
    if (!defined('BASEPATH')) exit('No direct script access allowed');
    
    class Signup_model extends CI_Model {
    
        public function __construct() 
        {
            parent::__construct();
            $this->load->database(); /* load database library */
    
        }
        // User register (signin) process 
        public function signup($data = array())
        {
            // another db field update like dt_createddate  
            if(!array_key_exists('dt_createddate', $data)){
                $data['dt_createddate'] = date("Y-m-d H:i:s");
            }
            if(!array_key_exists('dt_updateddate', $data)){
                $data['dt_updateddate'] = date("Y-m-d H:i:s");
            }
            if(!array_key_exists('dt_updateddate', $data)){
                $data['dt_updateddate'] = date("Y-m-d H:i:s");
            }
            $data['var_fullname'] = $this->input->post('fullname');
            $data['var_email'] = $this->input->post('email');
            $data['var_password'] =getHashedPassword($this->input->post('password')) ;
    
            $data['int_recipeunit'] = $this->input->post('recipeunit');
           // if(!empty($data['var_fullname']) && !empty($data['var_email']) && !empty($data['var_password']) ){ }
    
            /* check emailid  all ready exist or not */
            $email_check=$this->input->post('email');
            $this->db->select('var_email');
            $this->db->from('tbl_user');
            $this->db->where('var_email', $email_check);
            $query = $this->db->get();
    
            $user = $query->result();
            if(!empty($user))
            {           
                echo "{\"status\" : \"404\",\"message\" : \"Email all ready register\",\"data\":".str_replace("<p>","",'{}'). "}";
            }
            else 
            {
                $insert = $this->db->insert('tbl_user', $data);
                if($insert){
                $this->db->select('var_email as email,var_fullname as fullname,dt_createddate as createdate');
                $insert_id = $this->db->insert_id();
                $query = $this->db->get_where('tbl_user', array('int_id' => $insert_id));
                echo "{\"status\" : \"200\",\"message\" : \"User added sucessfully\",\"data\":".str_replace("<p>","",json_encode($query->row_array())). "}";
                // return $this->db->insert_id();
    
                }else
                {
                    $message="Something Wrong";
                    echo "{\"status\" : \"400\",\"data\":".str_replace("<p>","",json_encode($message)). "}";
                    // return false;
                }
            }
    
        }
    
        /* Login user   $email, $password*/
        function login()
        {
            $email=$this->input->post('email');
            $password=$this->input->post('password');
            $this->db->select('int_id,var_email,var_password');
            $this->db->from('tbl_user');
            $this->db->where('var_email', $email);
            $this->db->where('chr_status', 'A');
            $query = $this->db->get();
    
            $user = $query->result();
            if(!empty($user))
            {
                if(verifyHashedPassword($password, $user[0]->var_password))
                {
                    $this->db->select('var_email as email,var_fullname as fullname,dt_createddate as createdate');
                    $query = $this->db->get_where('tbl_user', array('var_email' => $email));
                echo "{\"status\" : \"200\",\"message\" : \"Login sucessfully\",\"data\":".str_replace("<p>","",json_encode($query->row_array())). "}";
                }
                else 
                {
                     echo "{\"status\" : \"404\",\"message\" : \"Password does not match\",\"data\":".str_replace("<p>","",'{}'). "}";
                }
            }
            else 
            {
                echo "{\"status\" : \"404\",\"message\" : \"Invalid email \",\"data\":".str_replace("<p>","",'{}'). "}";
            }
        }
        /* Fetch user data all or single    */
        function userlist()
        {
            $email=$this->input->post('email');  // post id of which user data you will get
    
            if(!empty($email))
            { 
                $email=$this->input->post('email');
                $password=$this->input->post('password');
                $this->db->select('int_id,var_email,var_password');
                $this->db->from('tbl_user');
                $this->db->where('var_email', $email);
                $this->db->where('chr_status', 'A');
                $query = $this->db->get();
    
                $user = $query->result();
                if(!empty($user))
                {       
                    $this->db->select('var_email as email,var_fullname as fullname,dt_createddate as createdate');  
                    $query = $this->db->get_where('tbl_user', array('var_email' => $email));
                    $responce_json=json_encode($query->row_array());
                    echo "{\"status\" : \"200\",\"message\" : \"User data\",\"data\":".str_replace("<p>","",$responce_json). "}";
                }
                else
                {
                     echo "{\"status\" : \"404\",\"message\" : \"Invalid email \",\"data\":".str_replace("<p>","",'{}'). "}";
                }
            }
            else
            {
                $this->db->select('var_email as email,var_fullname as fullname,dt_createddate as createdate');
                $query = $this->db->get('tbl_user');
                $responce_json=json_encode($query->result_array());
                echo "{\"status\" : \"200\",\"message\" : \"User data\",\"data\":".str_replace("<p>","",$responce_json). "}";
            }
        } 
    
        /*  Update user data   */
         function edit_user($data = array()) {
    
                $id = $this->input->post('id');
                $data['first_name'] = $this->input->post('first_name');
                /* $data['last_name'] = $this->input->post('last_name');
                $data['email'] = $this->input->post('email');
                $data['phone'] = $this->input->post('phone'); */
            if(!empty($data) && !empty($id)){
                if(!array_key_exists('modified', $data)){
                    $data['modified'] = date("Y-m-d H:i:s");
                }
    
                $update = $this->db->update('users', $data, array('id'=>$id));
                if($update){
                $message="User Update Sucessfully";
                $responce_json=json_encode($message); 
                echo "{\"status\" : \"200\",\"data\":".str_replace("<p>","",$responce_json). "}";
                }
    
            }
            else
            {
                return false;
            }
        } 
        /* change password  */
        function change_password()
        {
    
            $email=$this->input->post('email');
            $password=$this->input->post('password');
            $newpassword=$this->input->post('newpassword');
            //$conformnewpassword=$this->input->post('conformnewpassword');
            $this->db->select('int_id,var_email,var_password');
            $this->db->from('tbl_user');
            $this->db->where('var_email', $email);
            $this->db->where('chr_status', 'A');
            $query = $this->db->get();
    
            $user = $query->result();
            if(!empty($user))
            {
                if(verifyHashedPassword($password, $user[0]->var_password))
                {
                    //if($newpassword==$conformnewpassword)
                    //{
                        $data['var_password'] = getHashedPassword($newpassword);
                        $update = $this->db->update('tbl_user', $data, array('var_email'=>$email));
                        $this->db->select('var_email as email,var_fullname as fullname,dt_createddate as createdate');
                        $query = $this->db->get_where('tbl_user', array('var_email' => $email));
                        echo "{\"status\" : \"200\",\"message\" : \"Password change sucessfully\",\"data\":".str_replace("<p>","",json_encode($query->row_array())). "}";
                    /* }
                    else
                    {
                        echo "{\"status\" : \"404\",\"message\" : \"New pass and conform pass does not match \",\"data\":".str_replace("<p>","",'{}'). "}"; 
                    } */
                }
                else 
                {
                     echo "{\"status\" : \"404\",\"message\" : \"Invalid old password \",\"data\":".str_replace("<p>","",'{}'). "}";
                }
            }
            else 
            {
                echo "{\"status\" : \"404\",\"message\" : \"Invalid email \",\"data\":".str_replace("<p>","",'{}'). "}";
            }
        }
    
        /*
         * Delete user data
         */
        /* public function delete($id){
            $delete = $this->db->delete('users',array('id'=>$id));
            return $delete?true:false;
        } */
    
    }
    
     ?>
    
    0 讨论(0)
  • 2020-12-30 04:03

    It depends on the kind of web service you are inquiring about. Is the web service going to be a daemon for example? or a typical online web service. For either of these you must implement a RESTful type. RESTful meaning a stateless connection. This is where API keys are used; to identity a user for example.

    Luckily Codeigniter is one with many libraries and extensions. An example of such libraries can be here: https://github.com/philsturgeon/codeigniter-restserver

    Now for security concerns: API keys would replace sessions or any state. You would have to make full checks on the api. Many sites that implement APIs offer different solutions to the same end result.

    Authentication with API keys are simple. You would check it against a storage type(database).

    Here is a tutorial using codeigniter and the library linked previously: http://net.tutsplus.com/tutorials/php/working-with-restful-services-in-codeigniter-2/

    This might be somewhat vague, but since you dont have any specific problems or apparent needs its hard to be specific.

    EDIT:

    In that case it would be better implementing a RESTful interface so that your iphone app can also use all of the user functionalities that your service provides. The best way would be to make everything accessible in one way. Meaning not having different controllers / models for the iphone connections and web connections.

    So for example you could have the following controller:

    <?php
    
    class Auth extends CI_Controller{
    
        public function login(){
          //Check if their accessing using a RESTful interface;
          $restful = $this->rest->check();
          if($restful){
             //Check for the API keys;
             $apiKey    = $this->input->get('apiKey');
             $secretKey = $this->input->get('secretKey');
    
             //If you have any rules apon the keys you may check it (i.e. their lengths,                 
             //character restrictions, etc...)
             if(strlen($apiKey) == 10 and strlen($secretKey) == 14)
             {
               //Now check against the database if the keys are acceptable;
               $this->db->where('apiKey', $apiKey);
               $this->db->where('secretKey', $secretKey);
               $this->db->limit(1);
               $query = $this->db->get('keys');
               if($this->db->count_all_results() == 1)
               {
                 //It's accepted the keys now authenticate the user;
                 foreach ($query->result() as $row)
                 {
                    $user_id = $row->user_id;
                    //Now generate a response key;
                    $response_key = $this->somemodel->response_key($user_id);
                    //Now return the response key;
                    die(json_encode(   array(
                                             'response_key' => $response_key, 
                                             'user_id' => $user_id
                                       )
                                   )
                       );
    
                 } //End of Foreach
               }//End of Result Count
             }//End of length / character check;
          } else {
            //Perform your usual session login here...;
    
          }
       }
    }
    
    ?>
    

    Now this is just a small example for performing these types of requests. This could apply to any type of controller. Though there are a few options here. You could make every request pass the apikey, and the secret each time and verify it at each request. Or you could have some sort of whitelist that once you have been verified the first time each request after that would be whitelisted, and or black listed on the opposite.

    Hope this helps, Daniel

    0 讨论(0)
提交回复
热议问题