I am working in CakePHP 2.6.1 and I have a project in which I have to create an API. So I have created a function and its working fine when I am logged in but when I try to access without login, it redirects to the login page.
My function looks like :
class AndroidController extends AppController {
public function admin_survey_question()
{
$this->loadModel('Question');
Configure::write('debug', '2');
$survey_id = $_REQUEST['survey_id'];
$this->layout = "";
//$condition = "Question.survey_id = '".$survey_id."'";
$this->Question->unbindModel(
array('hasMany' => array('Result'))
);
$info = $this->Question->find('all', array(
'fields' => array('Question.id,Question.question, Question.options'),
'conditions' => array(
"Question.survey_id" => $survey_id /*dont use array() */
)
));
echo json_encode($info);
exit;
}
}
Here,In core.php there is a Routing.prefixes used as admin.
Configure::write('Routing.prefixes', array('admin','services'));
When I call this api
http://navyon.com/dev/mt/admin/android/survey_question?survey_id=2
then it redirects to the login page.
I need access api without login.So how can I resolve this problem?
To make accessible this method admin_survey_question without authentication, you need to allow it in beforeFilter
class AndroidController extends AppController {
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('admin_survey_question');
}
public function admin_survey_question()
{
$this->loadModel('Question');
Configure::write('debug', '2');
$survey_id = $_REQUEST['survey_id'];
$this->layout = "";
//$condition = "Question.survey_id = '".$survey_id."'";
$this->Question->unbindModel(
array('hasMany' => array('Result'))
);
$info = $this->Question->find('all', array(
'fields' => array('Question.id,Question.question, Question.options'),
'conditions' => array(
"Question.survey_id" => $survey_id /*dont use array() */
)
));
echo json_encode($info);
exit;
}
}
See Docs
Related
Somehow, I have to create admin pages of my module. And this is how I am creating tabs
private function createTab()
{
$data = array(
'id_tab' => '',
'id_parent' => 0,
'class_name' => 'AdminSomeMenu',
'module' => $this->name,
'position' => 1, 'active' => 1
);
$res = Db::getInstance()->insert('tab', $data);
$id_tab = Db::getInstance()->Insert_ID();
$lang = (int)Configuration::get('PS_LANG_DEFAULT');
//Define tab multi language data
$data_lang = array(
'id_tab' => $id_tab,
'id_lang' => $lang,
'name' => $this->name
);
// Now insert the tab lang data
$res &= Db::getInstance()->insert('tab_lang', $data_lang);
$arrayTabs = array('TAB1','TAB2','TAB3');
foreach ($arrayTabs as $requiredTabs)
{
$tab = new Tab();
// Need a foreach for the language
$tab->name[$lang] = $this->l($requiredTabs);
$tab->class_name = 'Admin'.$requiredTabs;
$tab->id_parent = $id_tab;
$tab->module = $this->name;
$tab->add();
}
return true;
}
I hope I am going fine.
Once the tabs are created am trying linking with the following code.
<?php
class AdminMenuController extends ModuleAdminController
{
public function __construct()
{
$module = "mymodulename"
Tools::redirectAdmin('index.php?controller=AdminModules&configure='.$module.'&token='.Tools::getAdminTokenLite('AdminModules'));
}
}
This way the controller not found was gone. But I can create only the configure page through such link.
How should I go to achieve personalized page for each tabs.
Ah ! That was a missing parent::__construct(); in controllers causing the problem for not letting tabs behave the way they should.
<?php
class AdminTAB1Controller extends ModuleAdminController
{
public function __construct()
{
parent::__construct();
/* Tools::redirectAdmin('index.php?controller=AdminModules&configure='.$module.'&token='.Tools::getAdminTokenLite('AdminModules')); */
echo "Support page";
/* or further function can be called to load tpl files from views/templates/admin/ */
}
}
Now I have different pages for my tabs in both PS 1.6 and 1.7 !
I am working with 2.6.1 version of CakePHP. I have created one controller named as AndroidController.php and that looks like
<?php
class AndroidController extends AppController {
public function survey_question()
{
Configure::write('debug', '2');
$survey_id = $_REQUEST['survey_id'];
$this->layout = "";
//$condition = "Question.survey_id = '".$survey_id."'";
$info = $this->Question->find('all', array(
'conditions' => array(
"Question.survey_id" => $survey_id /*dont use array() */
)
));
echo json_encode($info);
exit;
}
}
?>
So, it gives an error like
Error: The action admin_survey_question is not defined in controller
AndroidController
Error:Create AndroidController::admin_survey_question() in file: app/Controller/AndroidController.php.
Note :My website url is
http://navyon.com/dev/mt/admin/android/survey_question?survey_id=2
So how can I resolve this?
You have enable admin routing for that action so your action should preceded admin_
Then your action look like below:
<?php
class AndroidController extends AppController {
public function admin_survey_question()
{
Configure::write('debug', '2');
$survey_id = $_REQUEST['survey_id'];
$this->layout = "";
//$condition = "Question.survey_id = '".$survey_id."'";
$info = $this->Question->find('all', array(
'conditions' => array(
"Question.survey_id" => $survey_id /*dont use array() */
)
));
echo json_encode($info);
exit;
}
}
?>
If you don't want enable admin routing for that action then remove admin from url and access like this :
http://navyon.com/dev/mt/android/survey_question?survey_id=2
I've created a module to authenticate a user. Now, after login I go to the index action and the system tells me that the authentication is all working fine. But What I want is to print some more user details from the Users table. When I try:
print_r($this->getServiceLocator()->get('AuthService')->getAdapter()->getResultRowObject());
I get no result. What am I doing wrong?
Thanks for your help.
In my module.php I've the following code(snippet):
public function getServiceConfig()
{
return array(
'abstract_factories' => array(),
'aliases' => array(),
'factories' => array(
// Some more code here but removed for simplicity
// Autentication
'AuthService' => function ($sm) {
$adapter = $sm->get('master_db');
$dbAuthAdapter = new DbAuthAdapter ( $adapter, 'Users', 'email', 'password' );
$auth = new AuthenticationService();
$auth->setAdapter ( $dbAuthAdapter );
return $auth;
},
// Some more code here but removed for simplicity
}
In my IndexController.php I've the following (snippets):
public function indexAction()
{
if(!$this->getServiceLocator()->get('AuthService')->hasIdentity()){
return $this->redirect()->toUrl('login');
}
echo "hello, it works!";
exit;
}
public function loginAction(){
$form = $this->getServiceLocator()->get('LoginForm');
$viewModel = new ViewModel(array('form' =>
$form));
return $viewModel;
}
public function processAction(){
// Lots of code here
if($bcrypt->verify($loginData['password'], $userData->password))
{
$this->getAuthService()
->getAdapter()
->setIdentity($loginData['email'])
->setCredential($userData->password);
$result = $this->getAuthService()->authenticate();
}
// Lots of code here where I check if $result->isValid and route to the
// correct action
}
public function getAuthService() {
if(!isset($this->authservice)) {
$this->authservice = $this->getServiceLocator()->get('AuthService');
}
return $this->authservice;
}
Instead of refering to the authentication result object (which properly only exists in the authentication request) you can simply store user details in the authentication identity (#see http://framework.zend.com/manual/2.1/en/modules/zend.authentication.intro.html).
For your case you could also store user specific details right after the validation of the authentication result in the authentication storage:
if ($result->isValid()) {
//authentication success
$resultRow = $this->authService->getAdapter()->getResultRowObject();
$this->authService->getStorage()->write(array(
'id' => $resultRow->id,
'user_agent' => $request->getServer('HTTP_USER_AGENT'))
);
}
(This information was taken from this authentication tutorial http://samsonasik.wordpress.com/2013/05/29/zend-framework-2-working-with-authenticationservice-and-db-session-save-handler/)
I am looking for a way to access and change the DATABASE_CONFIG variables, based on user input. Using CakePHP I created a custom datasource, based on the one provided in the docs, to access an external API. The API returns a JSON string containing the 12 most recent objects. I need to be able to change the page number in the API request to get the next 12 results, as well as accept a free text query entered by the user.
app/Config/Database.php
class DATABASE_CONFIG {
public $behance = array(
'datasource' => 'BehanceDatasource',
'api_key' => '123456789',
'page' => '1',
'text_query' => 'foo'
);
}
app/Model/Datasource/BehanceDataSource.php
App::uses('HttpSocket', 'Network/Http');
class BehanceDatasource extends DataSource {
public $description = 'Beehance datasource';
public $config = array(
'api_key' => '',
'page' => '',
'text_query' => ''
);
public function __construct($config) {
parent::__construct($config);
$this->Http = new HttpSocket();
}
public function listSources($data = null) {
return null;
}
public function describe($model) {
return $this->_schema;
}
public function calculate(Model $model, $func, $params = array()) {
return 'COUNT';
}
public function read(Model $model, $queryData = array(), $recursive = null) {
if ($queryData['fields'] === 'COUNT') {
return array(array(array('count' => 1)));
}
$queryData['conditions']['api_key'] = $this->config['api_key'];
$queryData['conditions']['page'] = $this->config['page'];
$queryData['conditions']['page'] = $this->config['text_query'];
$json = $this->Http->get('http://www.behance.net/v2/projects', $queryData['conditions']);
$res = json_decode($json, true);
if (is_null($res)) {
$error = json_last_error();
throw new CakeException($error);
}
return array($model->alias => $res);
}
}
Is there anyway to access and change the $behance array, or is there another way to go about accessing an external API with cakePHP that I am totally missing?
In zf2 I have the option to make fake requests with a Zend/Request object. Thus I can do an internal Request. I want to execute a part of my site with a few data. Thus, I must use a Controller, Module and a Action.
How would I do that?
Here's a snippet of code from zf2 from a previous question:
/application/controller/IndexController.php
<?php
class IndexController extends Zend_Controller_Action
{
public function init(){}
public function indexAction()
{
//process some data from $_GET, $_POST, maybe (via framework, ofc).
}
}
/public/index2.php
<?php
//--cut--
$application->bootstrap();
$options = array(
'action' => 'index',
'controller' => 'index',
'module' => 'default'
);
if( isset($options['action'], $options['module'], $options['controller']) )
{
//*
$request = new Zend_Controller_Request_Http ();
$request->setModuleName($options['module'])->setActionName($options['action'])->setControllerName($options['controller']);
$frontController = Zend_Controller_Front::getInstance ()->returnResponse ( true );
//*/
$response = new Zend_Controller_Response_Http ();
$frontController->getDispatcher ()->dispatch ( $request, $response );
var_dump($response);
}
Thank you!