Home > Enterprise >  How to pass calculated/final value of one function to other functions in a controller of Codeigniter
How to pass calculated/final value of one function to other functions in a controller of Codeigniter

Time:11-08

Using sessions we can achieve this, but need this without sessions or cookies.

<?php
class Employees extends CI_Controller
{
    public function __construct() {
        parent::__construct();
    }

    public function auth() {
        $adminEmail = $this->input->post('adminEmail');
        $adminPassword =  $this->input->post('adminPassword');
        if ($adminEmail != "" && $adminPassword != "") {
            $query = $this->db->query("select * from admin_tbl where email= '$adminEmail' and password = '$adminPassword'");
            //if user exist
            if ($query->num_rows() <= 0) {
                $response = array();
                $jwtoken = "";
                $this->session->set_flashdata("invalid", "Wrong email or password");
                $response = array(
                    'status' => 'invalid',
                    'message' => $_SESSION['invalid'],
                    'token' => $jwtoken,
                );
                //used to send finalized values
                $this->output
                    ->set_content_type('application/json')
                    ->set_output(json_encode($response));
                return $jwtoken;  //return value
            } else {
                //  $this->session->set_userdata('adminEmail', $adminEmail);
                $response = array();
                $jwt = new JWT();
                $data = array(
                    'adminEmail' => $adminEmail,
                    'iat' => time()
                );
                $jwtoken = $jwt->encode($data, jwtSecretKey, 'HS256');
                // I want to pass $jwtoken's variable to all the functions in a controller
                $this->session->set_flashdata("login", "Scucessfully login!");
                //  if (isset($_SESSION['adminEmail'])) {
                if ($jwtoken != "") {
                    $response = array(
                        'status' => 'valid',
                        'message' => $_SESSION['login'],
                        'token' => $jwtoken
                    );
                }
                $abc = $jwtoken;
                //used to send finalized values
                $this->output
                    ->set_content_type('application/json')
                    ->set_output(json_encode($response));
                return $jwtoken; //return value
            }
        }
    }

    public function addNew() {
        $response = array();
        $this->auth(); // this value is always null returned by auth() method
    }
}

CodePudding user response:

This is more of a OOP programming basics question. If you want to re-use a variable in another function of the same controller object, you have to set the variable globally for the Employees class and then set/get its value in your functions by using $this->yourVariableName. But the set value of the object instance can only be reused in that instance only. Which means that after the auth() function, another function should be called subsequently to "access" the $this->yourVariableName. Another way is to pass the $jwtoken as a parameter to a function.

But the following code answers your question "How to pass calculated/final value of one function to other functions in a controller of Codeigniter application", if it doesn't, then your question should be corrected I guess.

Edit: Ow ok, first the auth() function is being called, then you would like to pass the $jwtoken value to another function, am I right? Well once a function is finished executing, the variable "disappears" if not passed to another function. If you would like to process the $jwtoken value immediately within the auth() function, then the answer is to pass the $jwtoken value to another function from within the auth() function:

<?php
class Employees extends CI_Controller
{
    public function __construct() {
        parent::__construct();
    }

    public function auth() {
        $adminEmail = $this->input->post('adminEmail');
        $adminPassword =  $this->input->post('adminPassword');
        if ($adminEmail != "" && $adminPassword != "") {
            $query = $this->db->query("select * from admin_tbl where email= '$adminEmail' and password = '$adminPassword'");
            //if user exist
            if ($query->num_rows() <= 0) {
                $response = array();
                $jwtoken = "";
                $this->session->set_flashdata("invalid", "Wrong email or password");
                $response = array(
                    'status' => 'invalid',
                    'message' => $_SESSION['invalid'],
                    'token' => $jwtoken,
                );
                //used to send finalized values
                $this->output
                    ->set_content_type('application/json')
                    ->set_output(json_encode($response));
                return $jwtoken;  //return value
            } else {
                //  $this->session->set_userdata('adminEmail', $adminEmail);
                $response = array();
                $jwt = new JWT();
                $data = array(
                    'adminEmail' => $adminEmail,
                    'iat' => time()
                );
                $jwtoken = $jwt->encode($data, jwtSecretKey, 'HS256');
                // I want to pass $jwtoken's variable to all the functions in a controller
                
                // this is one way you can pass the value to another function, depending on what you want to do, you can also place a condition and continue only if the return value of the following function is respected:
                $this->addNew($jwtoken);
                // What is the addNew() supposed to do?

                $this->session->set_flashdata("login", "Scucessfully login!");
                //  if (isset($_SESSION['adminEmail'])) {
                if ($jwtoken != "") {
                    $response = array(
                        'status' => 'valid',
                        'message' => $_SESSION['login'],
                        'token' => $jwtoken
                    );
                }
                $abc = $jwtoken;
                //used to send finalized values
                $this->output
                    ->set_content_type('application/json')
                    ->set_output(json_encode($response));
                return $jwtoken; //return value
            }
        }
    }

    public function addNew($jwtoken = "default_value_if_not_set") {
        echo $jwtoken;
    }
}

CodePudding user response:

Since you are creating an API, I assume the API is a REST api and stateless, so there is no interference of sessions and cookies.

I assume your process works like this:

  • User does a login request from the app to the api and the api returns a token when the credentials check is valid
  • The token is stored in the app (in a local database for example) and used for other requests

So the only thing you need to do is (I assume you have a route to addNew):

public function addNew() {
    $token = $this->input->get('token');
    $loginData = $this->validateToken($token);
    //... add new process 
}

And from your app you need to pass the token with the request to the api.

How do you validate the token?

To obtain the data you have set in the token, you have to decode the token:

/**
 * throws SignatureInvalidException
 */
function validateToken($token) 
{
   $jwt = new JWT();
   return $jwt->decode($token, jwtSecretKey, 'HS256');
}

Code improvement

Avoid using sessions and cookies

Since your api is stateless, you have to avoid settings cookies or sessions. So in your controller you can remove the flash data helper:

    public function auth() {
        $adminEmail = $this->input->post('adminEmail');
        $adminPassword =  $this->input->post('adminPassword');
        if ($adminEmail != "" && $adminPassword != "") {
            $query = $this->db->query("select * from admin_tbl where email= '$adminEmail' and password = '$adminPassword'");
            //if user exist
            if ($query->num_rows() <= 0) {
                $response = array();
                $jwtoken = "";
                
                # REMOVE THIS LINE 
                # $this->session->set_flashdata("invalid", "Wrong email or password");

                $response = array(
                    'status' => 'invalid',
                    'message' => "Wrong email or password", //CHANGE THIS LINE
                    'token' => $jwtoken,
                );
                //used to send finalized values
                $this->output
                    ->set_content_type('application/json')
                    ->set_output(json_encode($response));
                return $jwtoken;  //return value
            } else {
                //  $this->session->set_userdata('adminEmail', $adminEmail);
                $response = array();
                $jwt = new JWT();
                $data = array(
                    'adminEmail' => $adminEmail,
                    'iat' => time()
                );
                $jwtoken = $jwt->encode($data, jwtSecretKey, 'HS256');
                // I want to pass $jwtoken's variable to all the functions in a controller
                # REMOVE THIS LINE
                # $this->session->set_flashdata("login", "Scucessfully login!");
                //  if (isset($_SESSION['adminEmail'])) {
                if ($jwtoken != "") {
                    $response = array(
                        'status' => 'valid',
                        'message' => "Scucessfully login!", //CHANGE THIS LINE 
                        'token' => $jwtoken
                    );
                }
                $abc = $jwtoken;
                //used to send finalized values
                $this->output
                    ->set_content_type('application/json')
                    ->set_output(json_encode($response));
                return $jwtoken; //return value
            }
        }
    }

Return the output response instead of $jwtoken

In your response you have already set the the token, so you can simply return the response:

return $this->output
    ->set_content_type('application/json')
    ->set_output(json_encode($response));

Your query is vulnerable to sql injections

Use escape method around you variables or bind the params:

$sql = "select * from admin_tbl where email=? and password = ?";
$query = $this->db->query($sql, array($adminEmail, $adminPassword));
  • Related