Skip to content

Instantly share code, notes, and snippets.

@paulobunga
Last active May 22, 2017 10:39
Show Gist options
  • Save paulobunga/30602a624f64176327c53889803dea7d to your computer and use it in GitHub Desktop.
Save paulobunga/30602a624f64176327c53889803dea7d to your computer and use it in GitHub Desktop.
<?php defined('BASEPATH') OR exit('No direct script access allowed');
Class Api extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('api_model','api');
//I stumbled into issues when testing on my local development server
// adding this simple piece of code helps me send a request from a frontend on a different server
// to this api on a different server
// I was making a request from Angular login from localhost:4200 to PHP webserver localhost:8090
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding");
if ( "OPTIONS" === $_SERVER['REQUEST_METHOD'] ) {
die();
}
}
public function login()
{
//Do form validation with codeigniter
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if($this->form_validation->run() == FALSE)
{
//If form validation failes store error array
$output['errors'] = $this->form_validation->error_array();
} else {
// If everything is Okay. Capture username and password post data
$username = $this->input->post('username');
$password = $this->input->post('password');
//Get userdata from the Api_model
$userdata = $this->api->authenticate($username, $password);
//Get the ID & Token
$id = $userdata['user_id'];
$token = $userdata['token'];
//Check if id exists
if($id != false) {
//If token does not exist the we generate one using PHP-JWT library
if(! isset($token)) {
$key = base64_encode('add some randome key here');
$payload = array(
"iss" => "Add website address here",
"iat" => time(),
"exp" => time() + (3600 * 24 * 15),
"context" => [
"user" => [
"username" => $username,
"user_id" => $id
]
]
);
$jwt = JWT::encode($payload, $key);
//Output the token and user_id
$output['errors'] = "";
$output['token'] = $jwt;
$output['user_id'] = $id;
} else {
//Output the token and user_id
$output['errors'] = "";
$output['token'] = $token;
$output['user_id'] = $id;
}
} else {
$output['errors'] = 'User does not exist';
}
}
echo json_encode($output);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment