I used this tutorial: http://book.cakephp.org/2.0/en/tutorials-and-examples/blog-auth-example/auth.html
To build my first form/create user app, but it fails with an error message:
Fatal error: Call to a member function allow() on a non-object in /home/public_html/cake/app/Controller/UsersController.php on line 18
This ius the 18 line:
$this->Auth->allow('add', 'logout');
The above line is a member of function:
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add', 'logout');
}
My whole UsersController.php:
<?php
class UsersController extends AppController {
public function login() {
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
public function logout() {
$this->redirect($this->Auth->logout());
}
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add', 'logout');
}
public function index() {
$this->User->recursive = 0;
$this->set('users', $this->paginate());
}
public function view($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
$this->set('user', $this->User->read(null, $id));
}
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
public function edit($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
} else {
$this->request->data = $this->User->read(null, $id);
unset($this->request->data['User']['password']);
}
}
public function delete($id = null) {
if (!$this->request->is('post')) {
throw new MethodNotAllowedException();
}
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->User->delete()) {
$this->Session->setFlash(__('User deleted'));
$this->redirect(array('action'=>'index'));
}
$this->Session->setFlash(__('User was not deleted'));
$this->redirect(array('action' => 'index'));
}
}
?>
Why does it happends?
Make sure the Auth compenent is actually called in your AppController. If you don't have an AppController create AppController.php in your Controllers directory with the following code:
<?php
class AppController extends Controller {
}
?>
The Auth component is called in a public variable in the AppController, so the controller would look like this:
<?php
class AppController extends Controller {
public $components = array('Auth');
}
?>
Auth is now available throughout your application. You could also call the AuthComponent in your UsersController, but that would make it only available to that particular controller. You probably want to use authentication in your entire application.
Related
I have 2 class, ListenUser class get new user and push in ReadSocket class the ressource socket of this new user.
The problem is when I pushed the new user in the stack, I lost automatically the ressource socket IN the stack but it's continue to works in ListenUser class.
How can I put a new user in the ReadSocket stack and keed the connection ?
ListenUser class code after receiving server socket
class ListenUser
{
/*
*/
public function __construct($socket, $debug = false)
{
$this->socket = $socket
$this->StackSocket = new StackSocket; // class StackSocket extends Threaded {}
$this->ReadSocket = new ReadSocket($this->StackSocket);
}
/*
*/
public function run()
{
while (true) {
if (($user = socket_accept($this->socket)) !== false)
{
//
$this->ReadSocket->synchronized(function($thread) {
if ($thread->statutThread == true) {
$thread->wait();
}
$thread->statutUsers = true;
$thread->notify();
}, $this->ReadSocket);
//
$this->ReadSocket->synchronized(function($thread, $user) {
$thread->addUser($user); // Add user
$thread->statutUsers = false;
$thread->notify();
}, $this->ReadSocket, $user);
}
}
}
}
And my ReadSocket class code
<?php
class ReadSocket extends Thread
{
/*
*/
public function __construct($stack, $debug = false)
{
$this->stack = $stack;
}
/*
*/
public function run()
{
while (true)
{
$this->synchronized(function($thread) {
if ($thread->statutUsers == true) {
$thread->wait();
}
$thread->statutThread = true;
$thread->notify();
}, $this);
$this->statutThread = false;
}
return $this;
}
/*
*/
public function addUser($user)
{
print_r($user); // my ressource socket is ok
$this->stack[] = $user;
print_r($this->stack[0]); // I lost ressource socket
return $this;
}
}
I found the solution, socket (socket_create, socket_bind and socket_listen) was used/declared in no-thread class. So I extended to thread class and it's be ok :)
This is the error:
Fatal error: Class 'Admin_Controller' not found in C:\xampp\htdocs\ci-blog-master\application\modules\admin\controllers\Settings.php on line 4
A PHP Error was encountered
Severity: Error
Message: Class 'Admin_Controller' not found
Filename: controllers/Settings.php
Line Number: 4
Backtrace:
And here is my code for :
Admin_controller.php
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Admin_Controller extends MY_Controller {
function __construct()
{
parent::__construct();
}
}
And here is my Settings.php
class Settings extends Admin_Controller {
public function __construct(){
parent::__construct();
$this->allow_group_access(array('admin'));
$this->load->model('Category');
$this->data['parent_menu'] = 'post';
}
public function index(){
$this->session->set_flashdata('message',message_box('Setting is the coming soon feature!','danger'));
redirect('admin/posts/index');
$config['base_url'] = site_url('admin/categories/index/');
$config['total_rows'] = count($this->Category->find());
$config['per_page'] = 10;
$config["uri_segment"] = 4;
$this->data['categories'] = $this->Category->find($config['per_page'], $this->uri->segment(4));
$this->data['pagination'] = $this->bootstrap_pagination($config);
$this->render('admin/categories/index');
}
public function add(){
$this->form_validation->set_rules('name', 'name', 'required|is_unique[categories.name]');
$this->form_validation->set_rules('status', 'status', 'required');
if($this->form_validation->run() == true){
$category = array(
'name' => $this->input->post('name'),
'status' => $this->input->post('status')
);
$this->Category->create($category);
$this->session->set_flashdata('message',message_box('Category has been saved','success'));
redirect('admin/categories/index');
}
$this->render('admin/categories/add');
}
public function edit($id = null){
if($id == null){
$id = $this->input->post('id');
}
$this->form_validation->set_rules('name', 'name', 'required');
$this->form_validation->set_rules('status', 'status', 'required');
if($this->form_validation->run() == true){
$category = array(
'name' => $this->input->post('name'),
'status' => $this->input->post('status')
);
$this->Category->update($category, $id);
$this->session->set_flashdata('message',message_box('Category has been saved','success'));
redirect('admin/categories/index');
}
$this->data['category'] = $this->Category->find_by_id($id);
$this->render('admin/categories/edit');
}
public function delete($id = null){
if(!empty($id)){
$this->Category->delete($id);
$this->session->set_flashdata('message',message_box('Category has been deleted','success'));
redirect('admin/categories/index');
}else{
$this->session->set_flashdata('message',message_box('Invalid id','danger'));
redirect('admin/categories/index');
}
}
public function update_multiple(){
#test commit
#test commit di branch sendiri
}
}
You can put more classes in MY_Controller.php file:
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class MY_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function some_mycontr_method()
{
// appropriate code here
}
}
class Admin_Controller extends MY_Controller
{
public function __construct()
{
parent::__construct();
}
public function some_admin_method()
{
// appropriate code here
}
}
I am creating a custom Registration form. On submitting the form it has to generate a mail but now it is throwing a new Exception(); error. Guide me on how to solve this problem
my code
<?php
class Huntgather_Registration_IndexController extends Mage_Core_Controller_Front_Action
{
const XML_PATH_EMAIL_RECIPIENT = 'contacts/huntgather_registration/recipient_email';
const XML_PATH_EMAIL_SENDER = 'contacts/huntgather_registration/sender_email_identity';
const XML_PATH_EMAIL_TEMPLATE = 'contacts/huntgather_registration/email_template';
const XML_PATH_ENABLED = 'contacts/huntgather_registration/enabled';
public function preDispatch()
{
parent::preDispatch();
if( !Mage::getStoreConfigFlag(self::XML_PATH_ENABLED) ) {
$this->norouteAction();
}
}
public function indexAction()
{
$this->loadLayout();
$this->getLayout()->getBlock('registrationForm')
->setFormAction( Mage::getUrl('*/*/post') );
$this->_initLayoutMessages('customer/session');
$this->_initLayoutMessages('catalog/session');
$this->renderLayout();
}
public function postAction()
{
$post = $this->getRequest()->getPost();
if ( $post ) {
$translate = Mage::getSingleton('core/translate');
/* #var $translate Mage_Core_Model_Translate */
$translate->setTranslateInline(false);
try {
$postObject = new Varien_Object();
$postObject->setData($post);
$error = false;
if (!Zend_Validate::is(trim($post['product-name']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['serial-number']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['date']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['name']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['address']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is($post['data-privacy'], 'NotEmpty')) {
$error = true;
}
if (Zend_Validate::is(trim($post['hideit']), 'NotEmpty')) {
$error = true;
}
if ($error) {
throw new Exception();
}
$mailTemplate = Mage::getModel('core/email_template');
/* #var $mailTemplate Mage_Core_Model_Email_Template */
$mailTemplate->setDesignConfig(array('area' => 'frontend'))
->setReplyTo($post['email'])
->sendTransactional(
Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE),
Mage::getStoreConfig(self::XML_PATH_EMAIL_SENDER),
Mage::getStoreConfig(self::XML_PATH_EMAIL_RECIPIENT),
null,
array('data' => $postObject)
);
if (!$mailTemplate->getSentSuccess()) {
throw new Exception();
}
$translate->setTranslateInline(true);
Mage::getSingleton('customer/session')->addSuccess(Mage::helper('huntgather_registration')->__('Your registration has been processed. Thank you for registering your product'));
$this->_redirect('*/*/');
return;
} catch (Exception $e) {
$translate->setTranslateInline(true);
Mage::getSingleton('customer/session')->addError(Mage::helper('huntgather_registration')->__('We were unable to process your registration. Please make sure you have entered all required data in the form below'));
$this->_redirect('*/*/');
return;
}
} else {
$this->_redirect('*/*/');
}
}
}
Form submit getting error
(We were unable to process your registration. Please make sure you have entered all required data in the form below)
I think you got an exception while sending email. You should replace
Mage::getSingleton('customer/session')->addError(Mage::helper('huntgather_registration')->__('We were unable to process your registration. Please make sure you have entered all required data in the form below'));
With
Mage::getSingleton('customer/session')->addError($e->getMessage());
to get problem exactly.
I have created Zend_ACL with three roles :'administrator, guest, *edito*r'. I want guest cannot access /album/index after login. Administrator, editor can access /album/index. All other pages are accessible by all.
I created the access list below with Acl.php in helper.
/library/My/Helper/Acl.php:
public function __construct() {
$this->acl = new Zend_Acl();
}
public function setRoles() {
$this->acl->addRole(new Zend_Acl_Role('guest'));
$this->acl->addRole(new Zend_Acl_Role('editor'));
$this->acl->addRole(new Zend_Acl_Role('administrator'));
}
public function setResource () {
$this->acl->add(new Zend_Acl_Resource('album::index'));
$this->acl->add(new Zend_Acl_Resource('album::add'));
$this->acl->add(new Zend_Acl_Resource('album::edit'));
$this->acl->add(new Zend_Acl_Resource('album::delete'));
$this->acl->add(new Zend_Acl_Resource('auth::index'));
$this->acl->add(new Zend_Acl_Resource('auth::logout'));
$this->acl->add(new Zend_Acl_Resource('error::error'));
}
public function setPrivilages() {
$allowEditorAdmin=array('administrator','editor');
$allowAll=array('administrator','guest','editor');
$this->acl->allow($allowEditorAdmin,'album::index');
$this->acl->allow($allowAll,'album::add');
$this->acl->allow($allowAll,'album::edit');
$this->acl->allow($allowAll,'album::delete');
$this->acl->allow($allowAll,'auth::index');
$this->acl->allow($allowAll,'auth::logout');
$this->acl->allow($allowAll,'error::error');
Then, I create a plugin Acl.php
public function preDispatch(Zend_Controller_Request_Abstract $request) {
$acl1 = new My_Controller_Helper_Acl();
$acl = Zend_Registry::get('acl');
$userNs = new Zend_Session_Namespace('members');
if($userNs->userType=='')
{
$roleName='guest';
}
else
$roleName=$userNs->userType;
if(!$acl->isAllowed($roleName,$request->getControllerName()."::".$request->getActionname()))
{
echo $request->getControllerName()."::".$request->getActionName();
$request->setControllerName('auth');
$request->setActionName('index');
}
else
echo "got authenticated";
}
The problem is my code "isallowed" not work correctly. The 'guest,editor,administrator' cannot access to /album/index after authenticate successfully. They redirect to /auth/index
if(!$acl->isAllowed($roleName,$request->getControllerName()."::".$request->getActionname()))
{
echo $request->getControllerName()."::".$request->getActionName();
$request->setControllerName('auth');
$request->setActionName('index');
}
else
echo "got authenticated";
}
As far as I can tell, You are using 2 different ACL instances, and never set up the appropriate ACL in the first place. I can share a bit of my own code, that does almost the same thing:
In Bootstrap.php
$this->_acl = new Model_AuthAcl();
//Check for access rights
$fc = Zend_Controller_Front::getInstance();
$fc->registerPlugin(new App_Plugin_AccessCheck($this->_acl));
In App_Plugin_AccessCheck
class App_Plugin_AccessCheck extends Zend_Controller_Plugin_Abstract
{
private $_acl = null;
public function __construct(Zend_Acl $acl)
{
$this->_acl = $acl;
}
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$module = $request->getModuleName();
$resource = $request->getControllerName();
$action = $request->getActionName();
try {
if (!$this->_acl->isAllowed(Zend_Registry::get('role'), $module . ':' . $resource, $action)) {
$request->setControllerName('authentication')->setModuleName('default')
->setActionName('login');
}
}
catch (Exception $ex) {
if (APPLICATION_ENV == "development") {
var_dump($ex->getMessage());
}
}
}
}
In Model_AuthAcl
class Model_AuthAcl extends Zend_Acl
{
/**
* Creates the resource, role trees
*/
public function __construct ()
{
//Create roles
$this->addRole(new Zend_Acl_Role('guest'));
$this->addRole(new Zend_Acl_Role('user'), 'guest');
$this->addRole(new Zend_Acl_Role('admin'), 'user');
//Create resources
//Default module
$this->addResource(new Zend_Acl_Resource('default'))
->addResource(new Zend_Acl_Resource('default:authentication'), 'default')
->addResource(new Zend_Acl_Resource('default:error'), 'default')
//Admin module
->addResource(new Zend_Acl_Resource('admin'))
->addResource(new Zend_Acl_Resource('admin:index'), 'admin')
//Guest permissions
$this->deny('guest')
->allow('guest', 'default:authentication', array('index', 'login', 'logout', 'email', 'forgot'))
->allow('guest', 'default:error', array('error'))
->allow('guest', 'api:authentication', array('index', 'get', 'head', 'post', 'put', 'delete'))
//Admin permissions
->deny('admin', 'admin:admins')
;
}
}
May not be the most OOP solution, bet it sure as hell works.
Hope this helps you set up your dream ACL :)
how have I to create a custom Magento form? I don't need any extension or sample that mention the contact form. I mean that I need to understand how Magento with the modified Zend form handler works.
So the question is:
Does anybody have a code example for Magento created in a controller ?
<?php
class Mage_Contacts_IndexController extends Mage_Core_Controller_Front_Action
{
const XML_PATH_EMAIL_RECIPIENT = 'contacts/email/recipient_email';
const XML_PATH_EMAIL_SENDER = 'contacts/email/sender_email_identity';
const XML_PATH_EMAIL_TEMPLATE = 'contacts/email/email_template';
const XML_PATH_ENABLED = 'contacts/contacts/enabled';
public function preDispatch()
{
parent::preDispatch();
if( !Mage::getStoreConfigFlag(self::XML_PATH_ENABLED) ) {
$this->norouteAction();
}
}
public function indexAction()
{
$this->loadLayout();
$this->getLayout()->getBlock('contactForm')
->setFormAction( Mage::getUrl('*/*/post') );
$this->_initLayoutMessages('customer/session');
$this->_initLayoutMessages('catalog/session');
$this->renderLayout();
}
public function postAction()
{
$post = $this->getRequest()->getPost();
if ( $post ) {
$translate = Mage::getSingleton('core/translate');
/* #var $translate Mage_Core_Model_Translate */
$translate->setTranslateInline(false);
try {
$postObject = new Varien_Object();
$postObject->setData($post);
$error = false;
if (!Zend_Validate::is(trim($post['name']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['comment']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
$error = true;
}
if (Zend_Validate::is(trim($post['hideit']), 'NotEmpty')) {
$error = true;
}
if ($error) {
throw new Exception();
}
$mailTemplate = Mage::getModel('core/email_template');
/* #var $mailTemplate Mage_Core_Model_Email_Template */
$mailTemplate->setDesignConfig(array('area' => 'frontend'))
->setReplyTo($post['email'])
->sendTransactional(
Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE),
Mage::getStoreConfig(self::XML_PATH_EMAIL_SENDER),
Mage::getStoreConfig(self::XML_PATH_EMAIL_RECIPIENT),
null,
array('data' => $postObject)
);
if (!$mailTemplate->getSentSuccess()) {
throw new Exception();
}
$translate->setTranslateInline(true);
Mage::getSingleton('customer/session')->addSuccess(Mage::helper('contacts')->__('Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us.'));
$this->_redirect('*/*/');
return;
} catch (Exception $e) {
$translate->setTranslateInline(true);
Mage::getSingleton('customer/session')->addError(Mage::helper('contacts')->__('Unable to submit your request. Please, try again later'));
$this->_redirect('*/*/');
return;
}
} else {
$this->_redirect('*/*/');
}
}
}