Create RESTful API with Code Igniter #5 : Get user data, Encode data, and Generate token
Repository
https://github.com/bcit-ci/CodeIgniter
What Will I Learn?
- Get user data for data payload to encode
- Encode data
- Generate token
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, we will continue the previous tutorial series, in the previous tutorial, We have checked whether the email and password of a user are valid or not. Then we will start using the token system in our authentication system. We have checked a valid user or not like the picture below:
Get input user
We have checked a valid user, now we will encode user data. to get user data we can take the value like the following:
- Get user data from email
public function login() {
if (!$this->user->is_valid()) { //CHECK IF USER VALID OR NOT
return $this->response([
'success' => false,
'message' => 'Password or Email is wrong'
]);
}
// IF USER VALID GET USER DATA FROM EMAIL
$email = $this->input->post('email'); //GET USER INPUT 'email'
$user = $this->user->get_all('email',$email); //GET USER DATA
}
Get user input: We can take input values that are POST by the user like this
$email = $this->input->post('email);
. 'email' is the key that was POST.Get user data: If the user is valid then we will fetch user data from the email
$user = $this->user->get_all('email',$email);
. We can use the functionget_all()
in the modelsUser.php
. The following is the code snippet from User.php that we created in the previous tutorial series.
public function get_all($key = null, $value = null) {
if($key != null) {
$query = $this->db->get_where('users', array($key => $value));
return $query->result();
}
$query = $this->db->get('users');
return $query->result();
}
in the function get_all('email',$email)
We have two parameters, key and value. the key is the 'email'
and the value is $email
. The following are the data that we managed to take from $user = $this->user->get_all('email',$email);
array(1) {
[0]=>
object(stdClass)#18 (5) {
["id"]=>
string(1) "9"
["email"]=>
string(20) "[email protected]"
["password"]=>
string(60) "$2y$10$KJnQm6seBE6J61ARqjT8MeuniH.D2grQhBQho4Q4aiit0aIQnCBL2"
["created_at"]=>
string(19) "2018-10-24 22:06:05"
["updated_at"]=>
string(19) "0000-00-00 00:00:00"
}
}
Encode token
Encode is the process of converting information from a source (object) into data, which is then sent to the recipient or observer, as in the data processing system. Now we will encode based on user data and some other additional data.
- Collect data
Before we encode data to generate tokens, we need to collect the data needed to encode tokens. The following are the data that we will use to encode:
$date = new DateTime();
// Collect data
$payload['id'] = $user[0]->id
$payload['email'] = $user[0]->email;
$payload['iat'] = $date->getTimestamp();
$payload['exp'] = $date->getTimestamp() + 60*60*2;
var_dump ($payload);
$payload
is a variable in the form of an array. The keys are:
$payload['id']
is id value from$user[0]->id;
$payload['email']
is email value from$user[0]->email;
$payload['iat']
iat is just a key that stands for in At$payload['exp']
exp is just a key for expired time.
The Display when we do var_dump ($payload)
to see the $payload data structure.
array(4) {
["id"]=>
string(1) "9"
["email"]=>
string(20) "[email protected]"
["iat"]=>
int(1540702117)
["exp"]=>
int(1540709317)
}
- Encode token
After we get all the data that we need, then we will encode all data. to encode we can use JWT: :($payload, $this->secret)
. $payload is the data that we will encode and $this-> secret is a secret key to be combined with encoded data.
public function login() {
if (!$this->user->is_valid()) {
return $this->response([
'success' => false,
'message' => 'Password or Email is wrong'
]);
}
//Get User data
$email = $this->input->post('email');
$user = $this->user->get_all('email',$email);
// Collect data
$date = new DateTime();
$payload['id'] = $user[0]->id;
$payload['email'] = $user[0]->email;
$payload['iat'] = $date->getTimestamp();
$payload['exp'] = $date->getTimestamp() + 60*60*2;
// Encode data
$output['id_token'] = JWT::encode($payload, $this->secret);
$this->response($output); // Show the result to JSON
}
We can save the encoded data results in an array that is $output['id_token']
. Tokens are encoded from $payload
and $this-> secret
We can create a $secret
as a variable like this:
private $secret = "This is a secret key"; // CREATE VARIABLE TO PRIVATE
and then we can see the results in POSTMAN because we have displayed the data in JSON $this->response($output);
, the following is an example:
You can see as the picture above, we have succeeded to get the token that results from generating the data that we have collected from user data. Now we can save this token as access to our RESTfull API.
We have successfully generated tokens based on the data we encode. in the next tutorial, we will use this token as access to recognize valid users and we will also use it as a middleware so we can set any endpoints that can be accessed by the user. thank you for following this tutorial, hopefully, can help you.
Curriculum
Create RESTful API with Code Igniter #2 : Create API register, Models and Controllers, JSON Response
Thank you for your contribution @duski.harahap.
After an analysis of your tutorial, we only suggest the following point to improve:
Thanks for your work on 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!