-
FreedomAce
Newbie
-
Posts: 1
Threads: 1
Joined: Jul 2022
Reputation:
0
I have Codeigniter 4 web app that run REST API with firebase/php-jwt on Laragon 5.0.0210523 environment that run Apache-2.4.47, PHP-8.1.7, and MongoDB-4.0.28. I followed a tutorial and it works fine both server REST API and it REST client. After day work, i stop laragon server. In the next day i try run REST API server then tried then run the client but it failed and gave 301 moved permanently error, but i still can access it from postman.
REST API server side
composer.json
Code: ***
"require": {
"php": "^7.4 || ^8.0",
"codeigniter4/framework": "^4.0",
"mongodb/mongodb": "^1.12",
"firebase/php-jwt": "^6.3"
},
***
.env file
Code: ***
JWT_SECRET_KEY = SomeThing$089
JWT_TIME_TO_LIVE = 3600
app.baseURL = 'http://ci4-api.localhost'
***
Route.php
PHP Code: *** $routes->get('/', 'Home::index');
$routes->resource('api/users');
$routes->post('api/auth', [\App\Controllers\Api\Auth::class, 'index']); ***
JWT_Helper.php
PHP Code: use App\Models\ModelUsers; use Firebase\JWT\JWT; use Firebase\JWT\Key;
/** * @throws Exception */ function getJWT($authHeader) { if (is_null($authHeader)){ throw new Exception("Authentication JWT failed"); } return explode(" ", $authHeader)[1]; }
function validateJWT($encodedToken) { $key = getenv('JWT_SECRET_KEY'); $decodedToken = JWT::decode($encodedToken, new Key($key, 'HS256')); $modelUsers = new ModelUsers(); $modelUsers->get_email($decodedToken->email); }
function createJWT($email): string { $timeRequest = time(); $timeToken = getenv('JWT_TIME_TO_LIVE'); $timeExpired = $timeRequest + $timeToken; $payload = [ 'email' => $email, 'iat' => $timeRequest, 'exp' => $timeExpired, ]; return JWT::encode($payload, getenv('JWT_SECRET_KEY'), 'HS256'); }
FilterJWT.php
PHP Code: namespace App\Filters;
use CodeIgniter\API\ResponseTrait; use CodeIgniter\Filters\FilterInterface; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; use Config\Services; use Exception;
class FilterJWT implements FilterInterface { use ResponseTrait;
public function before(RequestInterface $request, $arguments = null) { $header = $request->getServer('HTTP_AUTHORIZATION'); try { helper('jwt'); $encodedToken = getJWT($header); validateJWT($encodedToken); return $request; } catch (Exception $ex) { return Services::response()->setJSON( [ 'error' => $ex->getMessage(), ] )->setStatusCode(ResponseInterface::HTTP_UNAUTHORIZED); } }
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) { // TODO: Implement after() method. } }
Filters.php
PHP Code: *** public $aliases = [ 'csrf' => CSRF::class, 'toolbar' => DebugToolbar::class, 'honeypot' => Honeypot::class, 'invalidchars' => InvalidChars::class, 'secureheaders' => SecureHeaders::class, 'auth' => FilterJWT::class, ]; public $filters = [ 'auth' => [ 'before' => [ 'api/users/*', 'api/users' ] ] ]; ***
ModelUsers.php
PHP Code: namespace App\Models;
use App\Libraries\MongoDb;
class ModelUsers { private $database = 'ci4_api'; private $collection = 'user'; private $conn;
function __construct() { $mongodb = new MongoDb(); $this->conn = $mongodb->getConn(); }
function get_user_list() { try {
$filter = []; $query = new \MongoDB\Driver\Query($filter);
$result = $this->conn->executeQuery($this->database. '.' . $this->collection, $query);
return $result->toArray();
} catch (\MongoDB\Driver\Exception\RuntimeException $ex) { show_error('Error while fetching users: ' . $ex->getMessage(), 500); } } ***
Auth.php
PHP Code: namespace App\Controllers\Api;
use App\Controllers\BaseController; use App\Models\ModelUsers; use CodeIgniter\API\ResponseTrait; use CodeIgniter\Validation\Validation; use Config\Services;
class Auth extends BaseController { use ResponseTrait;
private ModelUsers $model; private Validation $validation;
function __construct() { $this->model = new ModelUsers(); $this->validation = Services::validation(); }
public function index() { $email = $this->request->getVar('email'); $password = $this->request->getVar('password'); $password_hash = password_hash($password, PASSWORD_DEFAULT);
$data1 = [ 'email' => $email, 'password' => $password ];
if (!$this->validation->run($data1, 'login')) {
$errors = $this->validation->getErrors();
$response = [ 'status' => 201, 'error' => null, 'messages' => [ 'errors' => [ $errors ] ], ];
return $this->respond($response); }
$data1 = $this->model->get_email($email); //return $this->respond($data1, 200);
if (!$data1) { $response = [ 'status' => 201, 'error' => null, 'messages' => [ 'error' => 'Data user atau password tidak ada1' ], ];
return $this->respond($response, 200); }
$password_user = $data1->password;
if (password_verify($password_hash, $password_user) != 0){ $response = [ 'status' => 201, 'error' => null, 'messages' => [ 'error' => 'Data user atau password tidak ada2' ], ];
return $this->respond($response, 200); }
helper('jwt'); $response = [ 'message' => 'Auth berhasil dilakukan', 'data' => $data1, 'access_token' => createJWT($email) ];
return $this->respond($response, 200); } ***
users.php
PHP Code: namespace App\Controllers\Api;
use App\Controllers\BaseController; use App\Models\ModelUsers; use CodeIgniter\API\ResponseTrait; use CodeIgniter\HTTP\Response; use CodeIgniter\Validation\Validation; use Config\Services;
class Users extends BaseController { use ResponseTrait;
private ModelUsers $model; private Validation $validation;
function __construct() { $this->model = new ModelUsers(); $this->validation = Services::validation(); }
public function index(): Response { $data = $this->model->get_user_list(); $count = count($data);
if ($count <= 0) { $data = [ 'status' => 201, 'error' => null, 'message' => [ 'success' => 'Tidak ada data daftar pegawai' ], ];
} return $this->respond($data, 200);
} ***
REST Client
.env file
Code: ***
app.baseURL = 'http://ci4-test.localhost'
***
Routes.php
PHP Code: *** $routes->get('/rest', [\App\Controllers\Rest\RestClient::class, 'index']); ***
RestClient.php
PHP Code: namespace App\Controllers\Rest;
use App\Controllers\BaseController; use Config\Services;
class RestClient extends BaseController { public function index() { $client = Services::curlrequest(); $token = "someToken"; $url = "http://ci4-api.localhost/api/users/"; $headers = [ 'Authorization' => 'Bearer ' . $token, ];
$response = $client->request('GET', $url, ['headers' => $headers, 'http_errors' => false]);
return $response->getBody(); } }
Postman
api auth
api all user list
I have already tried some simple solution, like reload all laragon service like apache server and mongodb, restart the windows and tried find online, but it only suggest that the url is incorectly used like in this one https://stackoverflow.com/questions/5670...ermanently
Is there anyone have same issue or solution, thanks in advance.
-
iRedds
Senior Member
-
Posts: 662
Threads: 36
Joined: Apr 2019
Reputation:
45
|