Create RESTful API with Code Igniter #7 : Update User data and endpoint protection with tokens

in #utopian-io5 years ago

Repository

https://github.com/bcit-ci/CodeIgniter

What Will I Learn?

  • Update User data
  • Make endpoint protection with tokens

Requirements

  • Basic PHP
  • Install Ci > 3.1
  • Local server (Xampp, Wampp, or etc)
  • Mysqli

Resources

Difficulty

Basic

Tutorial Content

in this tutorial series, we have learned a lot about the RESTfull API and also the authentication system with tokens. So far we have created a login system with tokens and how to encode-decode tokens. In this tutorial, we will update the data to the user and certainly use access tokens. The method we will use will be slightly different, as we know we have created a routing system in our application, If you have not followed this tutorial I suggest you see the previous tutorial in the curriculum section. We just start our tutorial.

Update user data

If you just followed this tutorial, it should be noted that we have created our routing API system in config/routes.php. You can see the code as below:

routes.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

//Routes
$route['api/users']['GET']          = "UsersController/all_users";
$route['api/users/(:num)']['GET']   = "UsersController/detail_user/$1";
$route['api/register']['POST']      = "UsersController/register";
$route['api/user/(:num)']['PUT']    = "UsersController/update/$1";
$route['api/user/(:num)']['DELETE'] = "UsersController/delete/$1";
$route['api/login']['POST']         = "UsersController/login";

//Endpoint to check token
$route['api/check-token']['GET']    = "UsersController/check_token";

$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
  • For Endpoints update we can use the following endpoints $route['api/user/(:num)']['PUT'] = "UsersController/update/$1";. Because we want to update the user we need to pass a unique specific key, that is the id. For that we can pass the id into a parameter using (:num) and then we use method PUT.

  • In the controller we still use UsersControllers and we will use the function update() then pass the id with $1. We have created the endpoint for the Update endpoint. Now we will make the function in the UsersController.php section.

Create Protection with tokens

We have created a token authentication system, now we will use the token system to protect the method or action. So later we will check the token before accessing our API Endpoint. In the previous tutorial, we have created a function to decode the token and the following function.

UsersController.php

public function check_token() {
        $jwt = $this->input->get_request_header('Authorization');
        try {
            //decode token with HS256 method
            $decode = JWT::decode($jwt, $this->secret, array('HS256'));
            return $decode->id;
        } catch(\Exception $e) {
            return $this->response([
                'success'   => false,
                'message'   => 'invalid token'
            ]);
        }
    }
  • In this function check_token(), We will use headers with the key 'Authorization', In that key, we put the token.

  • We will only take the ID from the decoded data we can use return $decode->id;. The following is data from decoded objects.

object(stdClass)#18 (4) {
  ["id"]=> // This is the id that we will use
  string(1) "7"
  ["email"]=>
  string(21) "[email protected]"
  ["iat"]=>
  int(1541166769)
  ["exp"]=>
  int(1541173969)
}

Screenshot_13.png

For the explanation you can follow the tutorial.

  • Create function protected_method()

We will use this function to decode the tokens so that we can see the data. After we get the data we will check whether the data $id that is passed from the API is the same as the id contained in the decode token. We will create a new function that I name protected_method(). For more details, we can see the function as below:

UsersController.php

public function protected_method($id) {
        if ($id_from_token = $this->check_token()) {
            if ($id_from_token == $id) { // Check the $id match or not with the decode->id
                return $this->response([
                    'success'   => true,
                    'message'   => "User is match."
                ]);
            } else {
                return $this->response([
                    'success'   => false,
                    'message'   => "User is different."
                ]);
            }
        }
}
  • Passing params $id: In the protected_method($id) function we pass the $id parameter that we get to the routing API $route['api/user/(:num)']['PUT'] = "UsersController/update/$1";

  • Use function $this->check_token() : We use the function check_token() because the function is called on the same controller we can use $this.

  • Check the $id parameter: The purpose of this function is to check whether the $id that we have passed is the same as the id we got from the result of decoding the token in 'Authorization' if ($id_from_token == $id).

If the result is correct then we will return, later we will replace this response to return true

return $this->response([
                    'success'   => true,
                    'message'   => "User is match."
]);

if it is wrong then we will return the response

    return $this->response([
                    'success'   => false,
                    'message'   => "User is different."
                ]);

We can see an example like the picture below:

'Authorization' :

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjciLCJlbWFpbCI6Im1pbGxlYWR1c2tpQGdtYWlsLmNvbSIsImlhdCI6MTU0MTE2Njc2OSwiZXhwIjoxNTQxMTczOTY5fQ.FqDRcsnHGSMe8AV_8Hs8kNMZvV8w1R-nYPSvWTm1L2c

ezgif.com-video-to-gif (3).gif

We can see from the picture above if the id we have passed does not match the result of the decode we will return:

{
    "success": false,
    "message": "User is different."
}

Create function update

After we have finished creating a protection system with tokens we will implement it in the Endpoint API to update user data. To update we need to enter the data that we update, for that we need to fetch the data we get from the body. For more details, we can see the update function at UsersController.php.

public function update($id) {
        $data = json_decode(file_get_contents('php://input'));
        var_dump($data);exit;
        if ($this->protected_method($id)) {
            return $this->response($this->user->update($id, $data));
        }
    }
  • get data from body: If the get and post method we can use $POST, $GET or post() and get(), but in the put method we cannot do that. For that we need additional help from the functions provided by PHP, namely json_decode(file_get_contents('php://input'));. to see an example of its use we can see in the picture below below:

ezgif.com-video-to-gif (4).gif

We can see from the picture above we have got the data entered by the user in JSON form because we use the function json_decode ()

  • Use protected_method($id) as we discussed in the previous section before we update user data. We will identify the user through the token that the user gave, If the token is valid and matches the user's id, then we will give the access.

  • Create update data in Model

If the token and ID that we have passed are matched, then we will be given access to update user data. We will create an function $this->user->update($id, $data) in the User.php model. In the function update() we will pass two parameters. Those are $id and the update data $data.

User.php

public function update($id, $data) {
        $data = ["email" => $data->email];

        $this->db->where('id', $id);

        if ($this->db->update('users', $data)) {
            return [
                'status'    => true,
                'message'   => 'Data successfully updated'
            ]
        }
    }
  • Get params data: We can get data in the body in the $data parameter and the id in $id.

  • We can use $id as a parameter to get a specific user $this->db->where('id', $id);

  • And then we can use the update() method to update the table in the database. The update('users', $data) has two parameters which the first is table names 'users' and the second is new data to update data $data.

Then we can see the results like the following:

ezgif.com-video-to-gif (5).gif

The data we post on body:

{
    "email" : "[email protected]"
}

We can see email data id = 7 has been changed to:

{
        "id": "7",
        "email": "[email protected]",
        "password": "$2y$10$b/jfxikXEheyyol50qo4neRvE8NRGzZJ.Jt8eLXYJtYoHV50g3nMu",
        "created_at": "2018-11-02 22:18:09",
        "updated_at": "0000-00-00 00:00:00"
},

We have successfully updated the data we have posted on the body and we have also used the token system when accessing the URL endpoint. now we have controls for the user not to access the endpoints we have created. thank you for following this tutorial, hopefully, this tutorial will help you..

Curriculum

Create RESTful API with Code Igniter #1 : Basic installation, Setup configuration and Database, Create Routes API

Create RESTful API with Code Igniter #2 : Create API register, Models and Controllers, JSON Response

Create RESTful API with Code Igniter #3 : Create Endpoint for Users and User detail, Dynamic functions

Create RESTful API with Code Igniter #4 : JWT(JSON Web Token) Concept, Login function and Decode password

Create RESTful API with Code Igniter #5 : Get user data, Encode data, and Generate token

Create RESTful API with Code Igniter #6 : Decode token and Handle response token invalid

Proof of work done

https://github.com/milleaduski/RESTful-CI

Sort:  

Thank you for your contribution @duski.harahap.
After an analysis of your tutorial we suggest the following point to improve your next tutorial:

  • Put more comments in your code. The comments help readers better understand what you are developing.

Your contribution is very interesting. Thanks for your good work developing this tutorial.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Thank you for your review, @portugalcoin! Keep up the good work!

Hi @duski.harahap!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

Hey, @duski.harahap!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Coin Marketplace

STEEM 0.29
TRX 0.12
JST 0.033
BTC 63071.06
ETH 3121.31
USDT 1.00
SBD 3.84