create account

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

View this thread on steemit.com
· @duski.harahap ·
$53.87
Create RESTful API with Code Igniter #7 : Update User data and endpoint protection with tokens
#### 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
- Code igneter - https://www.codeigniter.com/
- JSON Web tokens - https://jwt.io/

#### 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.
<br>
### 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](https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igniter-6-decode-token-and-handle-response-token-invalid-1540905123140), 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) "milleaduski@gmail.com"
  ["iat"]=>
  int(1541166769)
  ["exp"]=>
  int(1541173969)
}
```

![Screenshot_13.png](https://ipfs.busy.org/ipfs/QmQZFyFMnCU4uA1DbZFW2d8rSSFCTMPC8x6XViR2qLRN3t)

For the explanation you can follow the [tutorial](https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igniter-6-decode-token-and-handle-response-token-invalid-1540905123140).
<br>

- **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 AP**I ```$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](https://ipfs.busy.org/ipfs/QmRSUowUY89kPtsXN6H5vSR7J2TC3Apc8XgpYqvsd2wq4C)

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](https://ipfs.busy.org/ipfs/QmXFdEG4tGqn46DeYDiREBPoxb9uPEV4sHC7kDGSnZZjiJ)

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 ()```
<br>
- **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](https://ipfs.busy.org/ipfs/QmYZMAbpTeFBKZyzMcEBecyPPtmje9jjdLpLYiAD3JuPQX)

**The data we post on body:**

```
{
	"email" : "new_duski@gmail.com"
}
```

We can see email data **id = 7** has been changed to:
```
{
        "id": "7",
        "email": "new_duski@gmail.com",
        "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](https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igneter-1-basic-installation-setup-configuration-and-database-create-routes-api-1539354852182)

[Create RESTful API with Code Igniter #2 : Create API register, Models and Controllers, JSON Response](https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igneter-2-create-api-register-models-and-controllers-json-response-1539531957770)

[Create RESTful API with Code Igniter #3 : Create Endpoint for Users and User detail, Dynamic functions](https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igneter-3-create-endpoint-for-user-dan-user-detail-dynamic-functions-1539784449409)

[Create RESTful API with Code Igniter #4 : JWT(JSON Web Token) Concept, Login function and Decode password](https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igniter-4-jwt-json-web-token-concept-login-function-and-decode-password-1540395859111)

[Create RESTful API with Code Igniter #5 : Get user data, Encode data, and Generate token](https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igniter-5-get-user-data-encode-data-and-generate-token-1540704402037)

[Create RESTful API with Code Igniter #6 : Decode token and Handle response token invalid](https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igniter-6-decode-token-and-handle-response-token-invalid-1540905123140)



#### Proof of work done
https://github.com/milleaduski/RESTful-CI
πŸ‘  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,
properties (37)
authorduski.harahap
permlinkcreate-restful-api-with-code-igniter-7-update-user-data-and-endpoint-protection-with-tokens-1541172916508
categoryutopian-io
json_metadata{"app":"steeditor/0.1.2","format":"markdown","image":["https://ipfs.busy.org/ipfs/QmPLB4NCbcT7XmVPNJkWEXsrvHDfSyZZvCeios9A5VW6c4","https://ipfs.busy.org/ipfs/QmQZFyFMnCU4uA1DbZFW2d8rSSFCTMPC8x6XViR2qLRN3t","https://ipfs.busy.org/ipfs/QmRSUowUY89kPtsXN6H5vSR7J2TC3Apc8XgpYqvsd2wq4C","https://ipfs.busy.org/ipfs/QmXFdEG4tGqn46DeYDiREBPoxb9uPEV4sHC7kDGSnZZjiJ","https://ipfs.busy.org/ipfs/QmYZMAbpTeFBKZyzMcEBecyPPtmje9jjdLpLYiAD3JuPQX"],"tags":["utopian-io","tutorials","php","codeigneter"],"users":["duski","gmail"],"links":["https://github.com/bcit-ci/CodeIgniter","https://www.codeigniter.com/","https://jwt.io/","https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igniter-6-decode-token-and-handle-response-token-invalid-1540905123140","https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igneter-1-basic-installation-setup-configuration-and-database-create-routes-api-1539354852182","https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igneter-2-create-api-register-models-and-controllers-json-response-1539531957770","https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igneter-3-create-endpoint-for-user-dan-user-detail-dynamic-functions-1539784449409","https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igniter-4-jwt-json-web-token-concept-login-function-and-decode-password-1540395859111","https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igniter-5-get-user-data-encode-data-and-generate-token-1540704402037","https://github.com/milleaduski/RESTful-CI"]}
last_update2018-11-02 15:35:21
created2018-11-02 15:35:21
active2018-11-05 22:16:57
last_payout2018-11-09 15:35:21
depth0
children4
net_rshares0
vote_rshares0
children_abs_rshares0
cashout_time1969-12-31 23:59:59
max_cashout_time1969-12-31 23:59:59
total_vote_weight0
reward_weight10,000
total_payout_value40.412 SBD
curator_payout_value13.461 SBD
author_rewards51,156
net_votes56
root_authorduski.harahap
root_permlinkcreate-restful-api-with-code-igniter-7-update-user-data-and-endpoint-protection-with-tokens-1541172916508
max_accepted_payout100,000.000 SBD
percent_steem_dollars10,000
allow_repliestrue
allow_votestrue
allow_curation_rewardstrue
beneficiaries
0.
accountutopian.pay
weight500
root_title"Create RESTful API with Code Igniter #7 : Update User data and endpoint protection with tokens"
pending_payout_value0.000 SBD
total_pending_payout_value0.000 STEEM
author_reputation21,428,288,146,822
promoted0.000 SBD
body_length0
reblogged_by[]
author_curate_reward""
vote details (56)
@portugalcoin ·
$7.58
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](https://join.utopian.io/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](https://review.utopian.io/result/8/11111313).

---- 
Need help? Write a ticket on https://support.utopian.io/. 
Chat with us on [Discord](https://discord.gg/uTyJkNm). 
[[utopian-moderator]](https://join.utopian.io/)
πŸ‘  , , , , , , , , , , , ,
properties (37)
authorportugalcoin
permlinkre-duskiharahap-create-restful-api-with-code-igniter-7-update-user-data-and-endpoint-protection-with-tokens-1541172916508-20181102t222612053z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"users":["duski.harahap"],"links":["https://join.utopian.io/guidelines","https://review.utopian.io/result/8/11111313","https://support.utopian.io/","https://discord.gg/uTyJkNm","https://join.utopian.io/"],"app":"steemit/0.1"}
last_update2018-11-02 22:26:12
created2018-11-02 22:26:12
active2018-11-05 22:16:57
last_payout2018-11-09 22:26:12
depth1
children1
net_rshares0
vote_rshares0
children_abs_rshares0
cashout_time1969-12-31 23:59:59
max_cashout_time1969-12-31 23:59:59
total_vote_weight0
reward_weight10,000
total_payout_value5.736 SBD
curator_payout_value1.841 SBD
author_rewards7,262
net_votes13
root_authorduski.harahap
root_permlinkcreate-restful-api-with-code-igniter-7-update-user-data-and-endpoint-protection-with-tokens-1541172916508
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
allow_repliestrue
allow_votestrue
allow_curation_rewardstrue
beneficiaries[]
root_title"Create RESTful API with Code Igniter #7 : Update User data and endpoint protection with tokens"
pending_payout_value0.000 SBD
total_pending_payout_value0.000 STEEM
author_reputation37,282,765,650,451
promoted0.000 SBD
body_length0
reblogged_by[]
author_curate_reward""
vote details (13)
@utopian-io ·
Thank you for your review, @portugalcoin! Keep up the good work!
properties (36)
authorutopian-io
permlinkre-re-duskiharahap-create-restful-api-with-code-igniter-7-update-user-data-and-endpoint-protection-with-tokens-1541172916508-20181102t222612053z-20181105t221657z
categoryutopian-io
json_metadata"{"app": "beem/0.20.9"}"
last_update2018-11-05 22:16:57
created2018-11-05 22:16:57
active2018-11-05 22:16:57
last_payout2018-11-12 22:16:57
depth2
children0
net_rshares0
vote_rshares0
children_abs_rshares0
cashout_time1969-12-31 23:59:59
max_cashout_time1969-12-31 23:59:59
total_vote_weight0
reward_weight10,000
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
author_rewards0
net_votes0
root_authorduski.harahap
root_permlinkcreate-restful-api-with-code-igniter-7-update-user-data-and-endpoint-protection-with-tokens-1541172916508
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
allow_repliestrue
allow_votestrue
allow_curation_rewardstrue
beneficiaries[]
root_title"Create RESTful API with Code Igniter #7 : Update User data and endpoint protection with tokens"
pending_payout_value0.000 SBD
total_pending_payout_value0.000 STEEM
author_reputation113,905,967,587,039
promoted0.000 SBD
body_length0
reblogged_by[]
@steem-ua ·
#### 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](https://discord.gg/KpBNYGz)**
properties (36)
authorsteem-ua
permlinkre-create-restful-api-with-code-igniter-7-update-user-data-and-endpoint-protection-with-tokens-1541172916508-20181102t235936z
categoryutopian-io
json_metadata"{"app": "beem/0.20.9"}"
last_update2018-11-02 23:59:36
created2018-11-02 23:59:36
active2018-11-02 23:59:36
last_payout2018-11-09 23:59:36
depth1
children0
net_rshares0
vote_rshares0
children_abs_rshares0
cashout_time1969-12-31 23:59:59
max_cashout_time1969-12-31 23:59:59
total_vote_weight0
reward_weight10,000
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
author_rewards0
net_votes0
root_authorduski.harahap
root_permlinkcreate-restful-api-with-code-igniter-7-update-user-data-and-endpoint-protection-with-tokens-1541172916508
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
allow_repliestrue
allow_votestrue
allow_curation_rewardstrue
beneficiaries[]
root_title"Create RESTful API with Code Igniter #7 : Update User data and endpoint protection with tokens"
pending_payout_value0.000 SBD
total_pending_payout_value0.000 STEEM
author_reputation18,835,859,419,062
promoted0.000 SBD
body_length0
reblogged_by[]
@utopian-io ·
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](https://chrome.google.com/webstore/detail/steemplus/mjbkjgcplmaneajhcbegoffkedeankaj?hl=en) or [Steeditor](https://steeditor.app)).

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

<a href='https://steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1'>Vote for Utopian Witness!</a>
properties (36)
authorutopian-io
permlinkre-create-restful-api-with-code-igniter-7-update-user-data-and-endpoint-protection-with-tokens-1541172916508-20181103t011050z
categoryutopian-io
json_metadata"{"app": "beem/0.20.9"}"
last_update2018-11-03 01:10:51
created2018-11-03 01:10:51
active2018-11-03 01:10:51
last_payout2018-11-10 01:10:51
depth1
children0
net_rshares0
vote_rshares0
children_abs_rshares0
cashout_time1969-12-31 23:59:59
max_cashout_time1969-12-31 23:59:59
total_vote_weight0
reward_weight10,000
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
author_rewards0
net_votes0
root_authorduski.harahap
root_permlinkcreate-restful-api-with-code-igniter-7-update-user-data-and-endpoint-protection-with-tokens-1541172916508
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
allow_repliestrue
allow_votestrue
allow_curation_rewardstrue
beneficiaries[]
root_title"Create RESTful API with Code Igniter #7 : Update User data and endpoint protection with tokens"
pending_payout_value0.000 SBD
total_pending_payout_value0.000 STEEM
author_reputation113,905,967,587,039
promoted0.000 SBD
body_length0
reblogged_by[]