how to retrieve the current user id in cakephp - cakephp

I am trying to retrieve the id of the current user logged in so i can save it to another table. I've been around stack overflow and found a few ways of doing this but nothing seems to work.
This throws the error: Call to a member function user() on a non-object
$this->Auth->user('id');
This returns a null value:
$this->Session->read('User.id');
I played around with this for a bit https://github.com/mcurry/cakephp_static_user but for some reason it complained that I was calling unregistered functions when I know I had implemented them.
I've tried a few variations of the auth and session lines but they all return null or throw an error. Can anyone shed some light on what I might be missing or doing wrong?

Try this:
$loggedInUser = AuthComponent::user();
This gives the whole user array, if you're just after the id then you need this:
$userId = $loggedInUser['User']['id'];
It's what I'm using where I need it, and it works well for me.

It seems like you are not using CakePHP's built-in Auth component.
Your code says:
$components = array('DebugKit.Toolbar', 'Session', 'DataTable', 'RequestHandler', 'Usermgmt.UserAuth')
To include CakePHP's Auth component:
$components = array('...', 'Auth')

Related

Cakephp 3 - CRUD plugin - Use id from auth component

Currently, I'm using the CRUD v4 plugin for Cakephp 3. For the edit function in my user controller it is important that only a user itself can alter his or her credentials. I want to make this possible by inserting the user id from the authentication component. The following controller method:
public function edit($id = null){
$this->Crud->on('beforeSave', function(\Cake\Event\Event $event) {
$event->subject()->entity->id = $this->Auth->user('id');
});
return $this->Crud->execute();
}
How can I make sure I don't need to give the id through the url? The standard implementation requires the url give like this: http://domain.com/api/users/edit/1.json through PUT request. What I want to do is that a user can just fill in http://domain.com/api/users/edit.json and send a JSON body with it.
I already tried several things under which:
$id = null when the parameter is given, like in the example above. Without giving any id in the url this will throw a 404 error which is caused by the _notFound method in the FindMethodTrait.php
Use beforeFind instead of beforeSave. This doesn't work either since this isn't the appropriate method for the edit function.
Give just a random id which doesn't exist in the database. This will through a 404 error. I think this is the most significant sign (combined with point 1) that there is something wrong. Since I try to overwrite this value, the CRUD plugin doesn't allow me to do that in a way that my inserting value is just totally ignored (overwriting the $event->subject()->entity->id).
Try to access the method with PUT through http://domain.com/api/users.json. This will try to route the action to the index method.
Just a few checks: the controllerTrait is used in my AppController and the crud edit function is not disabled.
Does anyone know what I'm doing wrong here? Is this a bug?
I personally would use the controller authorize in the Auth component to prevent anyone from updating someone else's information. That way you do not have to change up the crud code. Something like this...
Add this line to config of the Auth component (which is probably in your AppController):
'authorize' => ['Controller']
Then, inside the app controller create a function called isAuthorized:
public function isAuthorized($user) {
return true;
}
Then, inside your UsersController you can override the isAuthorized function:
public function isAuthorized($user) {
// The owner of an article can edit and delete it
if (in_array($this->request->action, ['edit'])) {
$userId = (int)$this->request->params['pass'][0];
if ($user['id'] !== $userId) {
return false;
}
}
return parent::isAuthorized($user);
}

Error: field is required

I have done a code, in which i create events. When i create event there was a field named "detailed_address" which i have removed now, from database, from model,from the edit page, from every where.
Creating an event works fine. but when i edit that event and save it, there is error as:
The detailed address field is required.
I have checked my code for at-least 5 times there is no word detailed address now used.
controller methods:
public function update(EventRequest $request, $id)
{
$event = Event::findOrFail($id);
$input = $request->all();
$input['days_of_week'] = serialize(Input::get('days_of_week'));
$query = $event->update($input);
return redirect('event');
}
public function store(Request $request)
{
$checkbox = Input::get('days_of_week');
$checkbox_selection = Input::get('agree');
$input = $request->all();
$input['days_of_week'] = serialize($checkbox);
$query = Event::create($input);
return view('event.create');
}
Can any one tell what will be my problem?
As #manix suggested, try running php artisan clear-compiled, then i'd suggest running php artisan cache:clear as well just to make doubly sure it's not a cache issue.
Something that could also be worth looking into is your requests folder (app\http\requests), if you weren't validating the input on the controller it was likely being done via requests which might still be checking for input that isn't coming through.
Is the field also still registered as mass assignable on the model?
Can't see why it'd throw a validation error but it's worth making doubly sure it's gone from there too

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.

Cakephp - Having Issue when submitting form to plugin controller action

I am a 3+ years old in cakephp and facing a somewhat strange issue
with submitting a form to plugin controller's action (i am using
plugin first time). After trying different known things i am posting
this one.
Going straight into the matter here is the form in my "forum" plugin's search_controller.php's "index" view:
echo $form->create("Search", array('url'=>array('controller' =>
'search', 'action' => 'index','plugin'=>'forum'),
'id'=>'searchFormMain'));
<input type="text" name="data[Search][keyword]" style="width:357px; margin-left:9px;"><p><span id="searchButton"><input
type="image" src="/img/button_search.jpg" style="height:40px;width:
136px;border:0;" class="handcursor"></span></p>
</form>
As i am submitting this form to "index" action of search controller of
forum plugin, the following code does print nothing:
public function index($type='') {
if(!empty($this->data)) {
pr($this->data);
die;
}
}
While if i try the same code within beforeFilter of the same
controller i.e. search_controller.php it works well and prints as
follows:
Array
(
[Search] => Array
(
[keyword] => Hello Forum
)
)
And finally here is the beforeFilter code (of search_controller.php):
public function beforeFilter() {
parent::beforeFilter();
if(!empty($this->data)) {
pr($this->data);
}
}
Fyi, it does not matter if i comment out "parent::beforeFilter();" or
even disable $uses of my controller (if they look doubtful to you)
the result is same i.e. the control is not going in to "index" action
in the case of form submit while is working fine in the case of page
call. The url/action to page is http://localhost.rfdf.org/forum/search/index.
If i call the url directly it loads the form fine but when i submit it, it
never gets into the "index" action of the controller thus no view
rendered.
If i try the same set of code out of "forum" plugin environment i.e. in normal application it works just fine
I have been trying to find a way out of this for last 3+ hours now but
no success. I would appreciate any help in solving this puzzle.
I got it, finally!
It was Securty compontent dropping the request into the blackHole whenever it failed to find a security token with the form data. I learned that "Security" component "interferes" with $form->create() method and places a token as a hidden field with each $form->create() call. On the form submit, just after beforeFilter and right before getting into the controller "action" it checks for this token and simply dies everything on a validation failure. Unfortunately there is no error message or entry to cake log.
In my case i had been creating my own custom tag and not with the help of $form->create method so no token was being generated which lead to all the pain.
I resolved it by placing
$this->Security->validatePost = false;
at the end of beforeFilter.
Thanks everyone!
Have you tried putting an else into that if(!empty($this->data)) and doing a pr() as it could be that your post is not empty.
Either that or the format of your url array is not correct.
From ln759, http://api.cakephp.org/view_source/router/#line-757
$defaults = $params = array('plugin' => null, 'controller' => null, 'action' => 'index');
So I guess you need plugin first?
Are you using ACL or any of the like? In the beforeFilter, do a pr of the request. See which action is being requested to make sure that the request is correct

cakephp Session->write problem in linux

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

Resources