Unsupported Protocol in Codeigniter Rest Library - php

I'm trying to build a rest API for an existing database. I was suggested to use Rest API from Chris Kacerguis, but his latest build came up with some constant errors. I decided to then use a prior version that still works but have an "unsupported protocol" error. I copy-pasted the code from his basic GET example and still have the same unsupported protocol error.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use chriskacerguis\RestServer\RestController;
class Api extends RestController {
function __construct()
{
// Construct the parent class
parent::__construct();
}
public function users_get()
{
// Users from a data store e.g. database
$users = [
['id' => 0, 'name' => 'John', 'email' => 'john#example.com'],
['id' => 1, 'name' => 'Jim', 'email' => 'jim#example.com'],
];
$id = $this->get( 'id' );
if ( $id === null )
{
// Check if the users data store contains users
if ( $users )
{
// Set the response and exit
$this->response( $users, 200 );
}
else
{
// Set the response and exit
$this->response( [
'status' => false,
'message' => 'No users were found'
], 404 );
}
}
else
{
if ( array_key_exists( $id, $users ) )
{
$this->response( $users[$id], 200 );
}
else
{
$this->response( [
'status' => false,
'message' => 'No such user found'
], 404 );
}
}
}
}
https://github.com/chriskacerguis/codeigniter-restserver

Check this option in the REST config file
$config['force_https'] = TRUE;

Related

I have a problem on API Resources Laravel (Maximum stack depth exceeded)

i have a problem when i use API Resources inside another API Resources class like this:
if (! Route::is('job.*')) {
$data['sites']= SiteResource::collection($this->sites);
$data['jobs'] = JobResource::collection($this->jobs);
}
but when I remove the class the problem disappears like this :
if (! Route::is('job.*')) {
$data['sites']= $this->sites;
$data['jobs'] = $this->jobs;
}
this is -> image for error
this is my code :
class CustomerResource extends JsonResource
{
public function toArray($request)
{
$data = [
'id' => $this->id,
'name' => $this->name,
'billing_details' => $this->billing_details,
'billing_info' => [
'address' => $this->billing->address,
'street_num' =>$this->billing->street_num,
'country' =>$this->billing->country->name,
'city' =>$this->billing->city,
'postal_code' =>$this->billing->postal_code,
'credit_limit' =>$this->billing->credit_limit,
'payment_term_id' =>$this->billing->payment_term_id,
'send_statement' =>$this->billing->send_statement
],
'contacts' => $this->contacts,
'sitecontact' => $this->sitecontact,
];
if (! Route::is('job.*')) {
$data['sites']= SiteResource::collection($this->sites);
$data['jobs'] = JobResource::collection($this->jobs);
}
return $data;
}
}
I called CustomerRessource class on JobRessource class which leads to an infinite loop between them
JobRessource class
if (! Route::is('job.*')) {
$data['sites']= SiteResource::collection($this->sites);
$data['jobs'] = JobResource::collection($this->jobs);
}
I fixed it by using this condition on JobRessource
if (Route::is('job.*')) {
$data['customer' ] = new CustomerResource($this->customer);
}
JobRessource with condition
#N69S thank you for your comment

Displaying Error Message in CodeIgniter 4

I am humbly seeking a help on how to go about displaying error message in CI4. i have create a controller like this:
public function login()
{
$validation = \config\services::validation();
$errors = array('email' => 'bad email',
'pass' => 'bad pass ');
if(!$this->validate(array('email' => 'required',
'pass' => 'required')))
{
echo view('login', array('validation' => $this->validator));
}
else
{
print 'success';
}
}
while a tested each of the error reporting function below:
$validation->listErrors();
$validation->listErrors('list');
$validation->showError();
$validation->showError('sigle');
$validation->showError('email');
but non of these function work, if i entered correct data it print success as assign but upon wrong data it all show the same error message which is:
Call to a member function listErrors() on null.
Call to a memberfunction listErrors() on null.
Call to a member function showError()on null.
Call to a member function ShowError() on null.
call form helper in your controller before your validation start
helper('form');
and i re-arrange ur code like this
public function login()
{
$data = [
'validation' => \config\services::validation()
];
if ($this->request->getMethod() == "post") { // if the form request method is post
helper('form');
$rules = [
'email' => [
'rules' => 'required',
'errors' => [
'required' => 'bad email'
]
],
'pass' => [
'rules' => 'required',
'errors' => [
'required' => 'bad pass'
]
]
];
if (!$this->validate($rules)) {
echo view('login', array('validation' => $this->validator));
} else {
// whatever you want todo
}
}
echo view('login', $data);
}
in your login view, if you want to call all error list you got use this method $validation->listErrors();
if you want to call a specific error use this method $validation->listErrors('email');
if you want to check is the specific field returning an error use this method $validation->hasError('email'))
i hope this help you to solve your problem

How to make Restful API in Codeigniter?

I am having problems when trying the API that I made. When I tested it in Postman, it appeared false, even though my username and password were correct. Can you identify the problem with my code?
I really appreciate your help.
Auth_admin.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require APPPATH . '/libraries/REST_Controller.php';
class Auth_admin extends REST_Controller
{
public function signin_post()
{
$this->load->model('model_admin', 'admin');
$params = array(
'username' => $this->post('username'),
'password' => md5($this->post('password'))
);
$result = $this->admin->admin_check($params);
if ($result){
if ($result->level == "admin"){
$response = array(
"status" => true,
"message" => "Authentication seccessfully",
"auth" => array(
"username" => $result->username
)
);
$this->set_response($response, REST_Controller::HTTP_OK);
}else{
$response = array(
"status" => false,
"message" => "This features does'nt exist for your Account"
);
$this->set_response($response, REST_Controller::HTTP_OK);
}
}
}
}
Model_admin.php
<?php
class Model_admin extends CI_Model
{
var $tablename;
public function __construct()
{
parent::__construct();
$this->tablename = "m_admin";
}
public function admin_check($data = array())
{
$params = array(
'username' => $data['username'],
'password' => $data['password'],
);
$this->db->where($params);
$query = $this->db->get($this->tablename);
return $query->row();
}
}
You have to pass function name after the controller name.
Like your path: http://192.168.122.1/project_name/auth_admin/signin it will work.
If that does not work, then please add index.php and check it because it depends on how you setup the project.

How to load all rows in codeigniter-base-model? REST api

I am trying to load all rows for my REST API through Postman.
I am using codeigniter-base-model MY_Model.php.
https://github.com/jamierumbelow/codeigniter-base-model
This is how my code currently looks like both in my controller/model:
Controller(api_news.php):
class Api_News extends REST_Controller {
function __construct()
{
parent::__construct();
}
function index_get()
{
$id = $this->uri->segment(3);
$this->load->model('News_model');
$news = $this->News_model->get_by(array('id' => $id));
if(isset($news['id'])) {
$this->response(array(
'message' => 'success',
'status' => 'true',
'data' => $news));
} else {
$this->response(array(
'message' => 'unsuccess',
'status' => 'false'));
}
}
}
Model(news_model.php):
class News_model extends MY_Model{
protected $_table = 'news';
protected $primary_key = 'id';
protected $return_type = 'array';
}
At the moment if I access:
localhost/my_api/api_news/id/1, 2, 3, etc...
I can access any record by its individual ID and it shows up which is great.
BUT I also want to be able to see all rows by doing this:
localhost/my_api/api_news/id/
and have all rows showing at once.
But I am not sure how to do this...and am getting an unsuccess/false if I try.
Can you please show me how? I am new to PHP in general and I appreciate any help.
Thank you so much!!
Make some changes in your Controller function as below -
function index_get(){
$id = $this->uri->segment(3);
$this->load->model('News_model');
// pass $id to model
$news = $this->News_model->get_by( $id );
if( !empty( $news ) ) {
$this->response(array(
'message' => 'success',
'status' => 'true',
'data' => $news));
} else {
$this->response(array(
'message' => 'unsuccess',
'status' => 'false'));
}
}
And in your model make id parameter optional and then check that if id is passed get data based on id otherwise return all data as below -
// $id variable is optional here
function get_by( $id = '' ) {
if ( $id == '' ) {
$news = $this->db->get( 'news' );
}
else {
$news = $this->db->get_where( 'news', array( 'id' => $id ) );
}
// return data to controller
return $news->result();
}
So if you enter id in API then data will be based on that id otherwise all data will be returned.

Cakephp AuthComponent: Login successfull despite wrong password

I'm running a 2.2.2 CakePHP Application, everything works as desired. Now I'm developing a Android App for it and therefore need to create the interfaces between those two apps. That's why I need to login users manually. So I created a whole new controller, the AndroidController, in order to bundle everything at one place. First thing to do would be the Login-Action. So I setup the following controller:
<?php
App::uses('AppController', 'Controller');
/**
* Android Controller
*
* #package app.Controller
*/
class AndroidController extends AppController {
public $components = array('RequestHandler','Auth');
public $uses = array('User');
public function beforeFilter() {
$this->Auth->allow();
}
public function login() {
//For testing purposes
$postarray = array('_method' => 'POST','data' => array('User' => array('email' => 'user#gmail.com', 'password' => 'THISisDEFINITELYaWRONGpassword')));
$id = $this->tryToGetUserID($postarray['data']['User']['email']);
if($id == 0){
//return Error json, unknown User
$this->set('result', array(
'tag' => 'login',
'success' => 0,
'error' => 1,
'error_msg' => 'Unknown User'
));
}else{
// if ($this->request->is('post')) {
$postarray['data']['User'] = array_merge($postarray['data']['User'], array('id' => $id));
$this->User->id = $id;
if ( $this->Auth->login($postarray['data']['User'])) {
// Login successfull
$this->User->saveField('lastlogin', date(DATE_ATOM));
$user = $this->User->find('all', array(
'recursive' => 0, //int
'conditions' => array('User.id' => $id)
));
$loggedInUser = array(
'tag' => 'login',
'success' => 1,
'error' => 0,
'uid' => '??',
'user' => array(
'name' => $user['0']['User']['forename'].' '.$user['0']['User']['surname'],
'email' => $user['0']['User']['email'],
'created_at' => $user['0']['User']['created'],
'updated_at' => $user['0']['User']['lastlogin']
)
);
$this->set('result', $loggedInUser);
} else {
// Login failed
$this->set('result', array(
'tag' => 'login',
'success' => 0,
'error' => 2,
'error_msg' => 'Incorrect password!'
));
}
// }
}
}
public function tryToGetUserID($email = null) {
$user = $this->User->find('list', array(
'conditions' => array('User.email' => $email)
));
if(!empty($user)){
return array_keys($user)['0'];
}else{
return 0;
}
}
}
You need to know that this method will be called as a POST request, but for testing purposes I manually created a post-array. In future I will use the $_POST array.
So, what happens: The Login with a registered user works, but it works every time! Even though the password is wrong or missing! The program never reaches the part in code with the "Login failed" comment.
Am I missing something here..?
Thank you!
If you take a closer look at the documentation you will notice that AuthComponent::login() will ...
In 2.x $this->Auth->login($this->request->data) will log the user in with whatever data is posted

Categories