How to make Restful API in Codeigniter? - php

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.

Related

Facing issue with Broadcast video through Vonage (tokbox)

I am facing issue when i try to broadcast my video in
When I use 'startVideo' its working fine for me.
But my 'connectVideo' giving me issue, I have pasted code below. I have attached error screenshot also.
In my first function 'startVideo' I wrote code to start video its taking my webcam video, through second function 'connectVideo' i just want share/broadcast my video with my user.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use OpenTok\OpenTok;
use OpenTok\MediaMode;
use OpenTok\ArchiveMode;
use OpenTok\Role;
use OpenTok\Session;
use OpenTok\Broadcast;
use OpenTok\Layout;
class Welcome extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->view('welcome_message');
}
public function startVideo()
{
$opentok = new OpenTok($this->config->item('opentok_key'), $this->config->item('opentok_secret'));
$sessionOptions = array(
'archiveMode' => ArchiveMode::ALWAYS,
'mediaMode' => MediaMode::ROUTED
);
$session = $opentok->createSession($sessionOptions);
$iSessionId = $session->getSessionId();
date_default_timezone_set('Asia/Kolkata');
$created_date = date("Y-m-d H:i:s");
$data = array(
'apiKey' => $this->config->item('opentok_key'),
'sessionId' => $iSessionId,
'token' => $session->generateToken(),
'created_date' => $created_date
);
$archiveOptions = array(
'name' => 'Important Presentation', // default: null
'hasAudio' => true, // default: true
'hasVideo' => true, // default: true
// 'outputMode' => OutputMode::COMPOSED, // default: OutputMode::COMPOSED
'resolution' => '1280x720' // default: '640x480'
);
$this->load->view('video_11', $data);
}
public function connectVideo() // connect to a session
{
$opentok = new OpenTok($this->config->item('opentok_key'), $this->config->item('opentok_secret'));
$session = $opentok->createSession();
$sessionOptions = array(
'archiveMode' => ArchiveMode::ALWAYS,
'mediaMode' => MediaMode::ROUTED
);
$session = $opentok->createSession($sessionOptions);
$sessionId = $session->getSessionId();
$options = array(
'layout' => Layout::getBestFit(),
'maxDuration' => 5400,
'resolution' => '1280x720'
);
$broadcast = $opentok->startBroadcast($sessionId, $options);
// Store the broadcast ID in the database for later use
$broadcastId = $broadcast->id;
$token = 'T1==T1==cGFydG5lcl9pZD00NjQ5MTcwMiZzaWc9Y2MxYzkxYzNmYTkzNmNiNmQ0NDZiNWEzNzVhYjExYTliYTZkOTdlYzpzZXNzaW9uX2lkPTFfTVg0ME5qUTVNVGN3TW41LU1UWXhOVE00TXpJMU16WXdPWDVIWjB0WVp6SlJWRlJhVUV4c2FrczVOa0ZOZGk5SUwwOS1RWDQmY3JlYXRlX3RpbWU9MTYxNTM4MzI1MyZyb2xlPXB1Ymxpc2hlciZub25jZT0xNjE1MzgzMjUzLjY5ODUxOTY3MzAxNjU4';
$data = array(
'apiKey' => $this->config->item('opentok_key'),
'sessionId' => $session,
'token' => $token
);
$this->load->view('video_22', $data);
}
}
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/Q1qBY.png

Route parameter only works for one code Zend Framework 2

I'm trying to have a verification process after registration (by a randomly generated verification code), but after I verify one code, it will not verify another one even though I am using the code that is stored in the database upon registration. For instance:
verify/c42557235936ed755d3305e2f7305aa3
...works fine, but when I try and use another code (like /verify/3bc056ff48fec352702652cfa4850ac4), it generates the default layout for the application and does nothing. I don't know what is causing it.
Here is the code I have for this:
VerifyController -
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
class VerifyController extends AbstractActionController
{
public $verify;
public function indexAction()
{
$code = $this->params()->fromRoute('code');
if ($this->getVerifyInstance()->authenticateCode($code) !== false) {
$this->flashMessenger()->addSuccessMessage("Verification Successful, you can now login.");
return $this->redirect()->toRoute('verify', array('action' => 'success'));
} else {
$this->flashMessenger()->addErrorMessage("Oops! Something went wrong while attempting to verify your account, please try again.");
return $this->redirect()->toRoute('verify', array('action' => 'failure'));
}
}
public function successAction()
{
}
public function failureAction()
{
}
public function getVerifyInstance()
{
if (!$this->verify) {
$sm = $this->getServiceLocator();
$this->verify = $sm->get('Application\Model\VerifyModel');
}
return $this->verify;
}
}
VerifyModel -
namespace Application\Model;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Insert;
use Zend\Db\Adapter\Adapter;
class VerifyModel
{
/**
* #var TableGateway
*/
protected $table_gateway;
/**
* #var mixed
*/
protected $code;
/**
* Constructor method for VerifyModel class
* #param TableGateway $gateway
*/
public function __construct(TableGateway $gateway)
{
// check if $gateway was passed an instance of TableGateway
// if so, assign $this->table_gateway the value of $gateway
// if not, make it null
$gateway instanceof TableGateway ? $this->table_gateway = $gateway : $this->table_gateway = null;
}
public function authenticateCode($code)
{
// authenticate the verification code in the url against the one in the pending_users table
$this->code = !empty($code) ? $code : null;
$select = $this->table_gateway->select(array('pending_code' => $this->code));
$row = $select->current();
if (!$row) {
throw new \RuntimeException(sprintf('Invalid registration code %s', $this->code));
} else {
// verification code was found
// proceed to remove the user from the pending_users table
// and insert into the members table
$data = array(
'username' => $row['username'],
'password' => $row['password'],
);
$sql = new Sql($this->table_gateway->getAdapter());
$adapter = $this->table_gateway->getAdapter();
$insert = new Insert('members');
$insert->columns(array(
'username',
'password'
))->values(array(
'username' => $data['username'],
'password' => $data['password'],
));
$execute = $adapter->query(
$sql->buildSqlString($insert),
Adapter::QUERY_MODE_EXECUTE
);
if (count($execute) > 0) {
// remove the entry now
$delete = $this->table_gateway->delete(array('pending_code' => $this->code));
if ($delete > 0) {
return true;
}
}
}
}
}
the route:
'verify' => array(
'type' => 'Segment',
'options' => array(
'route' => 'verify/:code',
'constraints' => array(
'code' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
'controller' => 'Application\Controller\Verify',
'action' => 'index',
),
),
),
and the layout configurer in Module.php:
public function init(ModuleManager $manager)
{
$events = $manager->getEventManager();
$shared_events = $events->getSharedManager();
$shared_events->attach(__NAMESPACE__, 'dispatch', function ($e) {
$controller = $e->getTarget();
if (get_class($controller) == 'Application\Controller\SetupController') {
$controller->layout('layout/setup');
} else if (get_class($controller) == 'Application\Controller\MemberLoginController' || get_class($controller) == 'Application\Controller\AdminLoginController') {
$controller->layout('layout/login');
} else if (get_class($controller) == 'Application\Controller\RegisterController') {
$controller->layout('layout/register');
} else if (get_class($controller) == 'Application\Controller\VerifyController') {
$controller->layout('layout/verify');
}
}, 100);
}
Your route is defined
'options' => array(
'route' => 'verify/:code',
'constraints' => array(
'code' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
So, it should start with a letter (upper or lower case), and be followed by any (even none) number of characters (letters, numbers, underscores, and dashes).
So, valid routes:
verify/c42557235936ed755d3305e2f7305aa3 (the one you where trying)
verify/abcde
verify/N123-123
verify/Z
verify/X-1
etc.
Any of those should work. But the other code you provide in your question:
/verify/3bc056ff48fec352702652cfa4850ac4
starts with a number, so it wont be caught by your router. You need to either change how you generate your codes so they match your route, or change your route so it matches your codes. E.g.:
'options' => array(
'route' => 'verify/:code',
'constraints' => array(
'code' => '[a-zA-Z0-9][a-zA-Z0-9_-]{28,32}',
),

call_user_func_array() expects parameter 1 to be a valid callback, no array or string given Kohana 3.3.4

Hey guys i have read and studied the kohana orm and auth modules. so i want to implement am admin section to my website. i get the error above and i have googled but can't seem to find the answer. am using Kohana 3.3.4
so a created a controller called admin:
<?php defined('SYSPATH') or die('No direct script access!');
class Controller_Admin extends Controller_Dev
{
public $template = 'login_template';
public function action_index()
{
if (Auth::instance()->logged_in()) {
$this->redirect->body('admin/dashboard', 302);
}
$this->redirect('admin/login');
}
//lets login user
public function action_login()
{
$view = new View('admin_login');
$this->template->title = "Log in";
if ($_POST) {
$user = ORM::factory('user');
$status = $user->login($_POST);
if ($status) {
$this->redirect('admin/dashboard', 302);
}
else {
$errors = $_POST->errors('admin/login');
}
}
// Display the login form
$this->template->content = $view;
}
//lets logout user
public function action_logout()
{
Auth::instance()->logout();
$this->redirect('admin/login', 302);
}
//lets register new users
public function action_register()
{
$view = View::factory('admin_register')
->set('values', $_POST)
->bind('errors', $errors);
$this->template->title = "Registration Page";
if ($_POST)
{
$user = ORM::factory('User');
// The ORM::values() method is a shortcut to assign many values at once
/* $external_values = array(
// The unhashed password is needed for comparing to the password_confirm field
'password' => Arr::get($_POST, 'password'),
// Add all external values
) + Arr::get($_POST, '_external', array());
$extra = Validation::factory($external_values)
->rule('confirm_password', 'matches', array(':validation', ':field', 'password')); */
try
{
//$test = $extra; //Arr::get($_POST, 'password');
//$view->test = $test;
$data = $this->request->post();
$user->register($data);
// Redirect the user to his page
$this->redirect('admin/login');
}
catch (ORM_Validation_Exception $e)
{
$errors = $e->errors('models');
}
}
$this->template->content = $view;
}
and i created a model called user to help me validate the new user account before save it to the database:
<?php defined('SYSPATH') or die('No direct access allowed.');
class Model_User extends Model_Auth_User {
//public $_table_name = 'users';
protected $_has_many = array(
'user_tokens' => array('model' => 'user_token'),
'roles' => array('model' => 'role', 'through', 'roles_users'),
// for facbook, google+, twitter and yahoo indentities
'user_identity' => array(),
);
protected $_ignored_columns = array('confirm_password');
public function rules()
{
return array(
'username' => array(
array('not_empty'),
array('min_length', array(':value', 4)),
array('max_length', array(':value', 32)),
array(array($this, 'username_available')),
),
'password' => array(
'not_empty' => NULL,
'min_length' => array(5),
'max_length' => array(42),
),
'password_confirm' => array(
'matches' => array('password'),
),
'email' => array(
'not_empty' => NULL,
'min_length' => array(4),
'max_length' => array(127),
'email' => NULL,
),
);
}
public function filters()
{
return array(
'password' => array(
array(array($this, 'hash_password')),
),
);
}
public function username_available($username)
{
// There are simpler ways to do this, but I will use ORM for the sake of the example
//return ORM::factory('Member', array('username' => $username))->loaded();
// Check if the username already exists in the database
return ! DB::select(array(DB::expr('COUNT(username)'), 'total'))
->from('users')
->where('username', '=', $username)
->execute()
->get('total');
}
public function hash_password($password)
{
// Do something to hash the password
}
public function register($array)
{
$this->values($array);
$this->save();
// Create a new user record in the database
// Save the new user id to a cookie
cookie::set('user', $id);
return $id;
}
}
When i visit the admin registration page. it fails displaying an error which says:
ErrorException [ Warning ]: call_user_func_array() expects parameter 1 to be a valid callback, no array or string given
so please help me out because i think i might be missing something. Thanks in advance guys. Am using Kohana 3.3.4
I had the same error recently. You need to change line:
array(array($this, 'username_available')),
to line (for username):
array(array($this, 'unique'), array('username', ':value')),
as stated in https://kohanaframework.org/3.3/guide-api/Model_Auth_User#rules
I hope this helps you.

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

CakePHP: saving information in session

I am writing my own Auth component for CakePHP 2, which inherit from BaseAuthenticate. This component use an external lib (located in /usr/share/php) which save information in the $_SESSION variable.
My problem is that when I change of page, all this information is removed from $_SESSION, so the external lib do not sees that I am already connected.
I tried to save the content of $_SESSION added by the lib by using $this->Session->write in Auth.MyAuthenticateComponent, but this is also removed.
Thanks for your help.
edit :
The code :
class AppController extends Controller {
public $use = array('User');
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'Sheets', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'Users', 'action' => 'login')
)
);
public function beforeFilter()
{
$this->Auth->authenticate = array('Arise');
}
}
class UsersController extends AppController
{
public $helpers = array('Html', 'Form');
public function beforeFilter()
{
parent::beforeFilter();
$this->Auth->allow('login');
$this->Auth->authenticate = array('Arise');
}
public function login()
{
if ($this->request->is('post')) {
if ($this->Auth->login())
return $this->redirect($this->Auth->redirect());
else
$this->Session->setFlash('Error');
}
}
public function logout()
{
$this->redirect($this->Auth->logout());
}
}
App::uses('BaseAuthenticate', 'Controller/Component/Auth');
require_once('/usr/share/php/openid/consumer/consumer.php');
class AriseAuthenticate extends BaseAuthenticate
{
protected function _ariseAuthenticate($openid_url)
{
$consumer =& AriseOpenID::getInstance();
$required = array(
'http://somewhere/types/identifiant',
'http://axschema.org/namePerson/first',
'http://axschema.org/namePerson/friendly'
);
$consumer->setReturnTo('http://mysite/users/login');
$consumer->setTrustRoot('http://mysite/users/login');
$consumer->authenticate($openid_url, $required);
if ($consumer->isLogged()) {
$first_name = $consumer->getSingle('http://axschema.org/namePerson/first');
$nick = $consumer->getSingle('http://axschema.org/namePerson/friendly');
$id_arise = $consumer->getSingle('http://openid.iiens.net/types/identifiant');
return array(
'id_arise' => $id_arise,
'first_name' => $first_name,
'nick' => $nick
);
}
return false;
}
public function checkUser($result)
{
$User = ClassRegistry::init('User');
$result = $User->find('first', array(
'conditions' => array(
'id_arise' => $result['id_arise']
)
));
if (!$result) {
$User->create();
$User->save(array(
'id_arise' => $result['id_arise'],
'first_name' => $result['first_name'],
'nick' => $result['nick']
));
$result = $User->find('first', array(
'conditions' => array(
'id_arise' => $result['id_arise']
)
));
}
$user = $result['User'];
unset($result['User']);
return array_merge($user, $result);
}
public function authenticate(CakeRequest $request, CakeResponse $response)
{
if (!$request->is('post'))
return false;
$openid_url = (array_key_exists('login', $request->data))
? $request->data['login']['openid_url']
: NULL;
$openid_url = ($openid_url == '') ? NULL : $openid_url;
if ($result = $this->_ariseAuthenticate($openid_url))
return $this->checkUser($result);
return false;
}
public function getUser()
{
if ($result = $this->_ariseAuthenticate(NULL))
return $this->checkUser($result);
return false;
}
}
Are you unit testing your auth adapter? It is hard to tell what is wrong but I'm more or less sure authenticate() does not return the array but always false? Because if authenticate() returns valid user data it would be written to the session.
See http://api.cakephp.org/2.3/source-class-AuthComponent.html#543, that calls http://api.cakephp.org/2.3/source-class-AuthComponent.html#690 which calls all configured auth adapters. If your adapter returns an user array it should work. So I assume your adapter fails to return the array.

Categories