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
***
"require": {
"php": "^7.4 || ^8.0",
"codeigniter4/framework": "^4.0",
"mongodb/mongodb": "^1.12",
"firebase/php-jwt": "^6.3"
},
***
.env file
***
JWT_SECRET_KEY = SomeThing$089
JWT_TIME_TO_LIVE = 3600
app.baseURL = 'http://ci4-api.localhost'
***
Route.php
***
$routes->get('/', 'Home::index');
$routes->resource('api/users');
$routes->post('api/auth', [\App\Controllers\Api\Auth::class, 'index']);
***
JWT_Helper.php
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
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
***
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
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
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
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
***
app.baseURL = 'http://ci4-test.localhost'
***
Routes.php
***
$routes->get('/rest', [\App\Controllers\Rest\RestClient::class, 'index']);
***
RestClient.php
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/56700991/codeigniter-301-moved-permanently[3]
Is there anyone have same issue or solution, thanks in advance.
After trying some few more time, i found the problem. It still around about url similiar like in case of Codeigniter 301 Moved Permanently, but my problem i added "/" on my url.
eg
RestClient.php
//Read all users
$url = "http://ci4-api.localhost/api/users/";
Maybe i added it after copy paste process
so the correct url is
RestClient.php
//Read all users
$url = "http://ci4-api.localhost/api/users";
hopefully help some people facing same problem
Related
I need Basic authentication in Yii2 rest API:
Api controller:
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator']['class'] = HttpBasicAuth::className();
$behaviors['authenticator']['auth'] = function ($username, $password) {
return \app\models\User::findOne([
'username' => $username,
'password' => $password,
]);
};
}
My Requwest:
login:password#api/users
How fix it?
Error:
Invalid argument supplied for foreach()
if ($this->_behaviors === null) {
$this->_behaviors = [];
foreach ($this->behaviors() as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
Line with "foreach".
In controller:
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => HttpBasicAuth::className(),
];
return $behaviors;
}
Url for Get: username:password#api/users
Configure modules in api.suite.yml
class_name: ApiTester
modules:
enabled:
- REST:
url: http://xxxx
depends: Yii2
- \backend\tests\Helper\Api
config:
- Yii2
class UserLoginCest
public function tryToTest(ApiTester $I)
{
$I->haveHttpHeader('Authorization', 'Basic Og==');
$I->sendPOST('/admin/user/login', ['username' => 'wen', 'password' => '123456']);
$I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK); // 200
$I->seeResponseIsJson();
$I->seeResponseContains('{"result":"ok"}');
}
in UserController $behaviors
$behaviors['authenticator'] = [
'class' => CompositeAuth::class,
'authMethods' => [
[
'class' => HttpBasicAuth::class,
'auth' => function ($username, $password) {
$request = Yii::$app->request;
$username = $username ?: $request->post('username');
$password = $password ?: $request->post('password');
if (!$user = User::findByUsername($username)) {
return null;
}
if (!$user->validatePassword($password)) {
return null;
}
if ($user->login()) {
return $user;
}
return null;
}
],
]
];
in Yii2 HttpBasicAuth
$username = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : null;
$password = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : null;
var_dump($_SERVER) is not set $_SERVER['PHP_AUTH_USER'] response 401 Unauthorized
Use amHttpAuthenticated method: https://codeception.com/docs/modules/REST#amHttpAuthenticated
$I->amHttpAuthenticated('username', 'password');
I am new in laravel 5. This code is ok in pure php. But I don't know how to convert this to laravel 5. Can you tell me how to transfer this code to laravel 5.
client.php:
<?php class client {
public function __construct()
{
$params = array('location' => 'http://localhost:8888/csoap/server.php',
'uri' => 'urn://localhost:8888/csoap/server.php');
/* Initialize webservice */
$this->instance = new SoapClient(NULL, $params);
}
public function getString($id)
{
return $this->instance->__soapCall('getOutputString', $id);
}
}
$client = new client();
$id = array('id' => '1');
echo $client->getString($id);
?>
csoap/server.php:
<?php class server {
public function getOutputString($id)
{
$str = 'Youre ID is ' . $id . '.';
return $str;
}
}
$params = array('uri' => 'http://localhost:8888/csoap/server.php');
$server = new SoapServer(NULL, $params);
$server->setClass('server');
$server->handle();
?>
This is how I performed my installation in laravel 5.1
"require": {
"artisaninweb/laravel-soap": "0.2.*"
}
run: composer install or composer update
Add the service in config/app.php.
'providers' => [
...
...
Artisaninweb\SoapWrapper\ServiceProvider',
]
'aliases' => [
...
...
'SoapWrapper' => 'Artisaninweb\SoapWrapper\Facades\SoapWrapper'
]
This is my client soap:
use Artisaninweb\SoapWrapper\Facades\SoapWrapper;
class DataSoap {
public function demo()
{
// Add a new service to the wrapper
SoapWrapper::add(function ($service) {
$service
->name('mydata')
->wsdl('http://localhost:8888/csoap/Server.php')
->trace(true)
});
$data = [
'str' => 'Hello World',
];
// Using the added service
SoapWrapper::service('mydata', function ($service) use ($data) {
var_dump($service->getFunctions());
var_dump($service->call('getString', [$data])->getSringResult);
});
}
}
When I run the this code, I get an error
Class 'Artisaninweb\SoapWrapper\ServiceProvider' not found
You should change:
Artisaninweb\SoapWrapper\ServiceProvider
to:
Artisaninweb\SoapWrapper\ServiceProvider::class
and also:
SoapWrapper' => 'Artisaninweb\SoapWrapper\Facades\SoapWrapper
to:
SoapWrapper' => Artisaninweb\SoapWrapper\Facades\SoapWrapper::class
folks. The uniqueness validator in my form works as expected on adding new records, but on updating an exsisting record, it throws an error that the url already exists. It exists, in fact, but only in the current record.
Here is my controller:
$feed = Feeds::findFirst($id);
$feedForm = new FeedForm($feed, array('edit' => true));
if ($this->request->isPost() == true) {
$feedData = $this->request->getPost();
if ($feedForm->isValid($feedData, $feed)) {
if ($feed->save()) {
$this->flash->success("Feed successfuly updated.");
} else {
$this->flash->error("Update failed.");
}
} else {
foreach ($feedForm->getMessages() as $message) {
$this->flash->error($message);
}
}
}
And my form class:
class FeedForm extends FormBase {
public $options;
public function initialize($entity = null, $options = null) {
parent::initialize();
$this->setEntity($entity);
$this->options = $options;
$status = new Radio('status');
$status->addValidator(
new PresenceOf(
array(
'message' => 'The status is required.'
)
));
$this->add($status);
$name = new Text('name');
$name->addValidator(
new PresenceOf(
array(
'message' => 'The name is required.'
)
));
$name->addValidator(
new StringLength(
array(
'max' => 50,
'messageMaximum' => 'The name you entered is too long.'
)
));
$this->add($name);
$xml = new Text('xml');
$xml->addValidator(
new PresenceOf(
array(
'message' => 'The URL address is required.'
)
));
$xml->addValidator(
new StringLength(
array(
'max' => 2048,
'messageMaximum' => 'The URL address you entered is too long.'
)
));
$xml->addValidator(
new Url(
array(
'message' => 'The URL you entered is invalid.'
)
));
$xml->addValidator(
new Uniqueness(
array(
'model' => 'Sravnisite\Admin\Models\Feeds',
'table' => 'feeds',
'column' => 'xml',
'message' => 'The entered URL address already exists.'
)
));
$periodOptions = array();
for ($i = 4; $i <= 24; $i++) {
array_push($periodOptions, $i);
}
$this->add($xml);
$period = new Select('period', $periodOptions);
$period->addValidator(
new PresenceOf(
array(
'message' => 'The period is required.'
)
));
$this->add($period);
$shopID = new Select('shop_id', Shops::find(), array('using' => array('id', 'name')));
$shopID->addValidator(
new PresenceOf(
array(
'message' => 'The shop is required.'
)
));
$this->add($shopID);
}
}
Any ideas?
The form validation doesn't know to ignore the record you are updating - so for uniqueness it finds the record you're trying to update and gives an error. You could do some complicated find logic to keep the uniqueness validation in the form but it is better moved to the model. Your result would end up something like:
Controller
$feed = Feeds::findFirst($id);
$feedForm = new FeedForm($feed, array('edit' => true));
if ($this->request->isPost() == true) {
$feedData = $this->request->getPost();
if ($feedForm->isValid($feedData, $feed)) {
if ($feed->save()) {
$this->flash->success("Feed successfuly updated.");
} else {
$this->flash->error("Update failed.");
// Get each of the validation messages from the model
foreach ($feed->getMessages() as $message) {
$this->flash->error($message);
}
}
} else {
foreach ($feedForm->getMessages() as $message) {
$this->flash->error($message);
}
}
}
Form
// Exactly the same as you currently have but without the Uniqueness Validator
Model
class Feeds extends Phalcon\Mvc\Model
/**
* Validate that xml URLs are unique
*/
public function validation()
{
$this->validate(new Uniqueness(array(
"field" => "xml",
"message" => "The url must be unique."
)));
return $this->validationHasFailed() != true;
}
I'm having hard time with a weird behaviour of fileinput.
This is my form:
namespace Frontend\Form;
use NW\Form\Form;
use Zend\InputFilter;
use Zend\Form\Element;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
class EnrollStructure extends Form implements ServiceManagerAwareInterface
{
protected $sm;
public function __construct($name=null) {
parent::__construct("frmEnrollStructure");
$this->setAttribute("action", "/registrazione_struttura/submit")
->setAttribute('method', 'post')
->setAttribute("id", "iscrizione_struttura")
->setAttribute("class", "form fullpage");
$this->addInputFilter();
}
public function init()
{
$structureFs = $this->sm->get('Structure\Form\Fieldsets\Structure');
$structureFs->setUseAsBaseFieldset(true);
$structureFs->remove("id")
->remove("creationTime")
->remove("latLon");
$file = new Element\File("images");
$file->setAttribute('multiple', true);
$this->add($structureFs)->add($file);
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Iscriviti',
'id' => 'sbmtEnrollStructure',
'class' => 'submit_btn'
),
));
$this->setValidationGroup(
array(
'structure' =>
array(
'companyname',
'vatNumber',
'addressStreet',
'addressZip',
'addressCity',
'addressRegion',
'fax',
'publicPhone',
'publicEmail',
'website',
'status',
'ownerNotes',
'category',
'subcategory',
"facilities",
"agreeOnPolicy",
"agreeOnPrivacy",
"subscribeNewsletter",
"contact" => array("name", "surname", "email", "role", "phone"),
),
"images"
));
}
/**
* Set service manager
*
* #param ServiceManager $serviceManager
*/
public function setServiceManager(ServiceManager $serviceManager)
{
$this->sm = $serviceManager;
}
public function addInputFilter()
{
$inputFilter = new InputFilter\InputFilter();
// File Input
$fileInput = new InputFilter\FileInput('images');
$fileInput->setRequired(true);
$fileInput->getValidatorChain()
->attachByName('filesize', array('max' => "2MB"))
->attachByName('filemimetype', array('mimeType' => 'image/png,image/x-png,image/jpg,image/jpeg'))
->attachByName('fileimagesize', array('maxWidth' => 2048, 'maxHeight' => 2048));
$inputFilter->add($fileInput);
$this->setInputFilter($inputFilter);
}
}
Basically, I mainly use a fieldset which contains most of the data I request to the user, plus a File input field.
This is the Fieldset Structure: (most important parts..)
use Zend\Form\Element;
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Zend\Validator\Identical;
use Zend\Validator\NotEmpty;
use Zend\Validator\Regex;
use Zend\Validator\StringLength;
class Structure extends Fieldset implements InputFilterProviderInterface, ServiceManagerAwareInterface
{
protected $sm;
public function __construct()
{
parent::__construct('structure');
}
public function init()
{
$this->setHydrator(new DoctrineHydrator($this->_entityManager(),'Structure\Entity\Structure'));
$this->setObject($this->sm->getServiceLocator()->get("Structure_Structure"));
$id = new Element\Hidden("id");
$name = new Element\Text("companyname");
$name->setLabel("Ragione Sociale");
...........
}
public function getInputFilterSpecification()
{
return array
(
"id" => array(
"required" => false,
),
"companyname" => array(
"required" => true,
"validators" => array(
array('name' => "NotEmpty", 'options' => array("messages" => array( NotEmpty::IS_EMPTY => "Inserire la ragione sociale")))
),
),
.....
}
}
This is my controller:
public function submitAction()
{
try {
$this->layout("layout/json");
$form = $this->getForm('Frontend\Form\EnrollStructure');
//$form->addInputFilter();
$structure = $this->getServiceLocator()->get("Structure_Structure");
$viewModel = new ViewModel();
$request = $this->getRequest();
if ($request->isPost())
{
$post = array_merge_recursive
(
$request->getPost()->toArray(),
$request->getFiles()->toArray()
);
$form->setData($post);
if ($form->isValid())
{
$structure = $form->getObject();
$contact = $structure->getContact();
$this->getServiceLocator()->get('Structure_ContactService')->save($contact);
$files = $request->getFiles()->toArray();
if(isset($files['images']))
{
$count = 3;
foreach($files['images'] as $pos => $file)
{
$fpath = $this->getServiceLocator()->get('RdnUpload\Container')->upload($file);
if(!empty($fpath))
{
if(--$count ==0) break;
$asset = $this->getServiceLocator()->get("Application_AssetService")->fromDisk($fpath, $file['name']);
$this->getServiceLocator()->get("Application_AssetService")->save($asset);
$structure->addImage($asset);
}
}
}
$this->getServiceLocator()->get('Structure_StructureService')->save($structure);
$retCode = RetCode::success(array("iscrizione_struttura!" => array("form_submit_successfull")), true);
}
else
{
$messages = $form->getMessages();
if(empty($messages))
$retCode = RetCode::error(array("iscrizione_struttura" => array("need_at_least_one_file" => "missing file")), true);
else
$retCode = RetCode::error(array("iscrizione_struttura" => $messages), true);
}
$viewModel->setVariable("retcode", $retCode);
return $viewModel;
}
} catch(Exception $e)
{
throw $e;
}
}
The strange thing is that if i remove from the field "images" the "multiple" attribute everything works fine, causing the form not to validate and i get this message:
[images] => Array
(
[fileUploadFileErrorFileNotFound] => File was not found
)
While, if i set the attribute multiple, and the user does not upload a file i get no error, but the form gets invalidated (this is the reason for this "bad" code in my controller:)
$messages = $form->getMessages();
if(empty($messages))
$retCode = RetCode::error(array("iscrizione_struttura" => array("need_at_least_one_file" => "missing file")), true);
else
$retCode = RetCode::error(array("iscrizione_struttura" => $messages), true);
I found the problem was caused by the Jquery form plugin, without it it works fine. :( In case somebody needs, I think the correct action code can be found here (I haven't tryied it anyway)
https://github.com/cgmartin/ZF2FileUploadExamples/blob/master/src/ZF2FileUploadExamples/Controller/ProgressExamples.php