cakephp Session->write problem in linux - cakephp

I have problem with cakephp's Session->write method.
If I set a value like $_SESSION['..'] i'm able to read it back. But if I use the write method it's not working.
My problem is same as here: http://www.nabble.com/Session-problem-td16684956.html
The same code was working in windows but it's not working after I moved to linux.
Any permission problem would be the reason? (but i have given rw permission fully for the cake app directory).
code sample: in the link: http://www.nabble.com/Session-problem-td16684956.html
Configure::write('Session.save', 'php');
Configure::write('Session.cookie', 'CAKEPHP');
Configure::write('Session.start', true);
Configure::write('Session.checkAgent', false);
Configure::write('Security.level', 'medium');
cake version: 1.2.3.8166

Some steps to ensure it's not you:
clear the cache in your /app/tmp
check and recheck that your /app/tmp is world-writable recursively (that means drwxrwxrwx for all folders inside)
use Firebug to check your session cookie, maybe something has gone wrong with it
Last but not least, try to move your session persistence to your database (see: Session.save), just to test things out that way, you never know what you'll find.
Hopefully you'll find something if you try all these.

You should also try to use Cache::read and Cache::write
if (($session = Cache::read('session')) === false)
{
$session = 'some values';
Cache::write('session', $session);
}
Firstly, it will try to initialize Cache::read. If it returns false, Cache::write
will take part to store the values in sessions.

Prabu,
While I suspect the Configure::write() call will sometimes correctly set the session information (at least it looks like it might work), the Cake convention (aka the CakeWay) is to use the Session helper. I believe it is included by default in all Cake controllers; if not, you can always declare your controller as such:
class UsersController extends AppController {
...
var $helpers = array( 'Session', ... )
...
}
Then, when you want to write info to the session, just call:
$this->Session->write( 'checkAgent', false );
To read back values, use:
$this->Session->read( 'checkAgent');
For more information on the Session helper, check out the CakeBook # http://book.cakephp.org/view/484/Session

Related

CakePHP routing not redirecting correctly

I have a problem and i have no idea what's wrong.
I have build a basic authentication system, simple one. but what i noticed is that the URL- from the side bar is different from the one that is generatet from cakephp for example:
http://localhost/sitename/users
is the url that displays on toolbar.
When i do:
echo Router::url($this->here, true );
the result is:
http://localhost/sitename/sitename/users
The site still works, but time after time generates an error such as:
http://localhost/sitename/sitename/users/
Missing Controller
Error: SitenameController could not be found.
Error: Create the class SitenameController below in file: app\Controller\SitenameController.php
<?php class SitenameController extends AppController {
}
So i dont know what is causing the problem...
If someone, anyone could help me i would very appruciate it...
Thank you very much.
Your app is in a subdirectory so you should use
Router::url(null, true);
If the $url param is null the method will find the address to the actual controller/action. Read more here.
From the book:
$this->request->here contains the full address to the current request.
The full address includes the subdirectory as well. So if you use Router::url() with the $full param set to true it "duplicates" the subdirectory.

How to access parameters passed to Component from AppControler in CakePHP 2.4

I have created a component called ApiComponent to handle opening an HttpSocket to another server to post information. It looks like this:
class ApiComponent extends Component {
public function connect($endpoint,$data) {
App::uses('HttpSocket', 'Network/Http');
$HttpSocket = new HttpSocket();
// rest of the code
}
}
This works in the sense that I can call $this->Api->connect('/posts/add.json',$data); from my controller and the code is executed as expected.
However, I have a lot of settings in the $HttpSocket->request such as the hostname, port number, username, password etc etc that I'd like to take out of the Component and put in a config file.
According to http://book.cakephp.org/2.0/en/controllers/components.html#including-your-component-in-your-controllers I can pass parameters to the Component from the AppController like this:
public $components = array(
'Api' => array(
'host' => 'localhost',
'port' => '80'
),
'Session', 'Auth'
);
The manual says that this would pass the array to ApiComponent::__construct() but it doesn't say how I'm supposed to access the data in the component (or, it may... I'm in unfamiliar territory here).
So, my questions are:
1) Is it appropriate to put things like host, username, password etc in the AppController like this? And...
2) ...if so, how do I access them from within the Component?
...or...
3) ...if not, where exactly should I place settings like this?
In your ApiComponent your settings are stored in:
$this->settings
see API
I don't fully agree with #Lionel Chan: I don't think it's such a bad idea to store that values in the Component settings. But also using Configure class is a good practice.
No, it's not appropriate (so it's unclear). Controllers are for system/business logic, not for configurations.
(and 3.) You can probably use the following methods to store configurations:
Good, old constant way:
It's easy, just define(key, value) these credentials in your bootstrap.php and you should be fine, and it's globally accessible.
Use Configure class
Configure is pretty handy as it's global to CakePHP. You simply do Configure::write() to write the credentials in your bootstrap.php file. Yes it will have some minor overheads if you don't mind, but should not be noticeable.

CakePHP reverse routing issues

I've been using routing with "slug" as a named parameter, for example:
Router::connect('/category/:slug', array('controller'=>'categories', 'action'=>'view'), array('pass'=>array('slug'), 'slug'=>'[a-z0-9\-]+'));
I've now stumbled across a problem because I want to restrict the above route to logged in users only, so I've put this in the beforeFilter() function of my CategoriesController:
if(!$this->Auth->loggedIn()) {
$this->Auth->deny('view');
}
Now if I go to /category/my-category (while logged out) I'll be redirected to my application's login page, unfortunately after I log in I'm redirected to /categories/view/my-category/slug:my-category
This is due to line 317 of AuthComponent.php, where we have:
$this->Session->write('Auth.redirect', Router::reverse($request));
So it seems when I do Router::reverse($request) on the above route it doesn't work properly (because it thinks "my-category" should be both a passed and a named parameter).
Is this a problem with the way I've set up this route, or is it a bug with CakePHP? Surely Router::reverse($request) should always return the URL we're currently at?
Any advice appreciated...
I'm not 100% sure if it is a bug or not, but until we find out a work-around could be to manually set the new loginRedirect in your category controller like so:
if(!$this->Auth->loggedIn()) {
$this->Auth->deny('view');
$this->Auth->loginRedirect = '/categories/' . $this->request->params['slug'];
}
Note, check that $this->request->params['slug'] is the right var to use, not 100% off the top of my head.

Redirect to maintenance page in CakePHP doesn't work

I am trying to set a maintenance page so that when the site is disabled, it should appear no matter what page was requested.
I currently tried doing this with $this->cakeError():
in app_controller.php:
function beforeFilter(){
....
if($this->__get_config('maintenance_status') == 1){
$this->cakeError('maintenance', array('message' => $this->__get_config('maintenance_message')));
}
....
}
and in app_error.php:
function maintenance($message){
$this->controller->set('message', $message['message']);
($this->controller->RequestHandler->isAjax()) ? $this->_outputMessage('ajax_maintenance') : $this->_outputMessage('maintenance');
}
The problem is that a Fatal Error occurs, which says: Call to a member function isAjax() on a non-object. But I have obviously set the RequestHandler Component in app_controller.php. Moreover, I have tried calling this error from within another controller and it doesn't give me any Fatal Error.
What could be the problem? Why doesn't it recognize that I have initalized the Component?
From the CakePHP book:
Calling this method will show an error page to the user and halt any further processing in your application
I am assuming that you're calling the error in some callback in AppController.
If that is the case you may very likely be halting execution of your script before your components are instantiated. This would certainly cause your error.
Now, I think this error is a good chance to reevaluate how you're dealing with the problem. Is this really an error? You know the maintenance status is set so it's expected that the user be shown this page. It isn't an error. Furthermore, you certainly wouldn't want 10,000 messages in your log telling you that you turned maintenance on!
I think this could be better solved by utilizing some controller callbacks and a little bit of code.
I don't know what _get_config() is so I assume it is a custom user function that you can call in this callback.
We'll be using the beforeFilter() controller callback.
class AppController extends Controller {
public function beforeFilter() {
if ($this->_get_config('maintenance_status') === 1) {
$this->redirect('/maintenance');
}
}
}
Now, you can just setup a maintenance controller, attached to its own view, that will properly show your maintenance message, and won't log all those connection attempts during maintenance in your error log.
Slightly better would also be to use the Configure::read( "System.maintenance" ) or similar. (I tend to namespace my config data, System being the namespace for stuff like maintenance flags etc.)
Also, as Charles said - don't use an error page for an expected event. Errors are to show the user, and for the application to handle notifications etc, about unexpected failures. The maintenance page could simply be a view file in the /app/views/pages/ folder. Redirect to that if the config key is set to true/1.
Your approach seems to be intelligent, but you might be overdoing it a little.
I have a similar setup in a site I am currently developing and I simply use the auth component to take care of it for me.
To help out, I setup a new offline layout that I force the application to use if status of the site is 0 (offline). If the status is 0 app_controller denies access to the entire site.
$this->Auth->deny('*');
$this->layout = "offline";
Also, in this layout I have a hidden login form that appears if the user clicks the message.If user is able to authenticate (all users for now - development) access is granted to the entire site using the default template.
Check it out, it might help you out...
Click Here
Some of the code, but you can read more about it in the link above
function beforeFilter(){
// Site Offline = 0 , Site Online = 1
if($this->Configuration->get_site_status() == 1){
// Allow access to the site to all users and perform all required
// beforeFilter code
}else{
...
// If site is OFFLINE but User is logged in allow access.
// Later I will need to change it to only allow admin access if logged in as I am still developing
// Everyone else will be denied access even if they are able to authenticate
if(!$this->Auth->user() == null){
$this->layout = 'default';
$this->Auth->allow('*');
}else{
$this->layout = 'offline';
$this->Auth->deny('*');
}
...
}
}

How can I use cookies for authentication in CakePHP?

I am trying to use a cookie that is set by other page in my domain to authenticate the user.
Say I have needpassword.example.com written using cakephp,
and the cookie is generated by auth.example.com (using a Perl CGI program).
To login in to needpassword.example.com, I need to redirect to auth.example.com to set the cookie, and then use CakePHP to parse the cookie.
How do I parse this cookie? And how do I modify the Auth component to do these?
And how can I override the Auth class to instead go to the auth.example.com to authenticate, and not using the User model? By overriding the identify method in Auth.php?
Many thanks.
Since your needs sound outwith AuthComponent's originally intended design you have two options.
Firstly, if it really doesn't fit your needs, you could create and maintain your very own AuthComponent. Do this by copying /cake/libs/controller/components/auth.php to /app/controller/components/auth.php.
This would allow you to rewrite the component completely, but the downside is you will no longer receive updates to AuthComponent when you upgrade cake.
Secondly, you can extend just about anything in CakePHP using the following pattern:
// save as: /app/controllers/components/app_auth.php
App::import('Component', 'Auth');
class AppAuthComponent extends AuthComponent {
function identify($user = null, $conditions = null) {
// do stuff
return parent::indentify($user, $conditions);
}
}
.. and replace all instances of AuthComponent in your controllers with your AppAuthComponent.
You only need to define the methods you wish to replace.
You can run methods from the original AuthComponent (even ones you have redefined) at any point during your methods using parent::...
The method arguments should remain in the same order as the original API for consistency.
If you wish to add more method arguments, put them after the API ones, eg:
function identify($user = null, $conditions = null, $custom = array()) { ... }
This approach allows you to make application-specific customisation while still using the latest methods defined in the core where necessary.
Presuming I understand your question... As long as auth.example.com sets the cookie with the domain ".example.com" the users browser will send it along with the request to needpassword.example.com and you will be able to access it in your PHP script with the following:
$auth = $_COOKIE['auth'];
You can then make changes to the cookie with the following:
setcookie( "auth", "value", time() + 300, "/", ".example.com" );
(Note: time() + 300 sets the cookies expiry date to 5 minutes in the future, you may want to change this)

Resources