I have a controller in a CakePHP application in which I have a bunch of actions. I'm using the ACL Component to manage which user is allowed to execute which actions in my controller. I have an isAuthorized() action in my controller to check if a certain logged user is allowed to execute a requested action that looks like this:
function isAuthorized()
{
switch($this->action)
{
case 'myAction':
$user_id = $this->Auth->user('id'); // the id of the connected user
if($user_id)
{
return $this->Acl->check(
array('model' => 'MyModel', 'foreign_key' => $user_id),
'controllers/MyController/myAction'
);
}
break;
}
}
As you can see above, all I'm doing is check if the connected user is allowed to execute myAction by using the method check of the Acl component. The problem I have with this approach is that this check is done every single time myAction is called. Is there a way to tell Cake to perform this check only one time (on the first call of the action for example)?. By checking every single time if a user is allowed to execute a controller action that slows down the application a lot.
Any help or suggestions is appreciated
Thank you
Technically speaking, HTTP is stateless and each request does not have any affinity to any other request from the same user. State-fullness is created by using sessions.
You could store the ACL check result in a session variable. But you would need some way to reset it if the users access were to change while logged in.
Related
Building an app in Laravel 5.3, one of the functionalities is for the admin to be able to log into the app as a user, to be able to see what that specific user can see, while maintaining his admin session to be able to go back to the user list and be possible to log in as another user without having to re-authenticate.
Currently implemented the basic out-of-the-box Laravel Auth, meaning if I start another auth session it will terminate my admin session making me having to re-login.
I have checked Laravel Multi Auth but seems to work with two tables (user,admin), which in my case we use one user table and use an ACL for managing roles and deciding whos admin and whos user.
What programming logic ideas do you guys have for this solution? Trying to find other opinions/ideas in how this could be implemented in Laravel 5.x
I've implemented the feature on a project recently. I did this using the session and a middleware. This is how I did it:
Create a controller 'ImpersonateController' and Set two routes for impersonateIn and impersonateOut for the purpose.
Route::get('impersonateIn/{user}', 'ImpersonateController#impersonateIn');
Route::get('impersonateOut', 'ImpersonateController#impersonateOut');
In the ImpersonateController#impersonateIn method just set the user id you want to log in and the URL backUrl into the session variable.
public function impersonateIn($id)
{
session(['impersonated' => $id, 'backUrl' => \URL::previous()]);
return redirect()->to('dashboard');
}
public function impersonateOut()
{
$back_url = Request::session()->get('backUrl');
Request::session()->forget('impersonated', 'secretUrl');
return $back_url ?
redirect()->to($back_url) :
redirect()->to('dashboard');
}
The first part is done. Now every request need to check the if the session has the
impersonated variable set. A good place to do that is a middleware.
Create a middleware to check the session on the handle method. If the impersonated found then log as the user using the Auth::onceUsingId() for the current request only.
class ImpersonateMiddleware
{
public function handle($request, Closure $next)
{
if(Request::session()->has('impersonated'))
{
Auth::onceUsingId(Request::session()->get('impersonated'));
}
}
}
Now you just need to apply the middleware for every request. The best place to do this from the Http/Kernel.php
protected $middlewareGroups = [
'web' => [
//....
\App\Http\Middleware\ImpersonateMiddleware::class,
],
];
The only remaining thing is you need to check the session and replace the logout route to the impersonateOut. Now when the admin logged out from the user will be redirected to the old route.
That's it!
Are you sure you really have to login?
I would stay logged in as admin and simulate user login.
You can allow admin access to all the databases.
In your controller you can use User::find($user_id) instead of Auth::user() for accessing user's data.
https://laravel.com/docs/5.3/database
https://laravel.com/docs/5.3/eloquent
Personaly, I would do this with sessions. I have not used Laravel but I use PHP often, so my answer will be in PHP.
In the header page, you most likely have some kind of session check to see if the user is logged in. For example:
<? php
session_start();
if (isset($_SESSION['user'])){
//do stuff with the user session
} else {
die('User not logged in!');
}
?>
I would change this to something like:
<? php
session_start();
if (isset($_SESSION['fakeuser'])){
//do stuff with the user session
//change logout button to destroy this session instead of logging the user out
}
elseif (isset($_SESSION['user'])){
//do stuff with the user session
} else {
die('User not logged in!');
}
?>
In the page in which you swap users, you would just simply copy the way a session starts when a user logs in. To switch users, you destroy the new 'fakeuser' and you are back to your old session + admin permissions without having to log back in again.
That's the logical approach I would take anyways.
I want to apply access roles to the different actions like GET action can be performed by all the users and POST or PUT action can be performed by only logged in users. I don't know how to apply different roles to different actions.
In the mentioned scenario, i would do something like this using session Authorization.
FOR PUT AND POST ACTIONS
public function postAction/putAction
{
if (Zend_Auth::getInstance()->hasIdentity()) {
//YOUR CODE
}
}
FOR GET ACTION
public function postAction/putAction
{
//YOUR CODE
}
This will ensure only logged in users can perform the post and put actions and all will be able to perform the get action.
I've to make a cakePhp authentification, and I wish to use the "Auth" component. I'm trying to see if it fill my requirement:
I need to authenticate users with their email OR their customerId, (with an addition password of course). I can't find if it is possible to have two fields(or more) on which the authentication can be done
I've several parts on which I need to be authenticated. But I need differents granularity:
For some things, it's the whole controller which should not be accessible(if possible with exception(e.g. all the "User" controller, except the login/register action) for other I really need that it's the whole controller(e.g. the cart controller)
Sometimes I need that only some actions are unavailable without being logged
Sometimes I need that only a part of the view isn't displayed(e.g. login element not displayed)
Does the component manage action like password change? Because if the user change its password I need that he did not get disconnected.
Thank you very much for your help
The short answer is that yes, you can do these things, but it seems to me that the ACL might be overkill for your needs (but I also tend to avoid the ACL if there's any opening at all to do so). To your points:
As Ivo suggests, you'll need a custom UsersController::login() method to authenticate by multiple fields (If your auth model isn't User, then use the appropriate controller). If the Auth component's login method fails, it passes control to your custom login() method. Here's a snippet from a project I've been working on:
function login() {
# Allow login by either username (legacy) or email.
# If no authenticated user exists at this point then the Auth
# component's login() method has failed and control has been passed
# here for any further handling. Since the expected credentials
# (email and password) have failed we're going to check for
# username and password.
$user = $this->Auth->user();
if( empty( $user ) && !empty( $this->Auth->data['User']['email'] ) && !empty( $this->Auth->data['User']['password'] ) ) {
$user = $this->User->find(
'first',
array(
'recursive' => -1,
'conditions' => array(
'User.username' => $this->Auth->data['User']['email'],
'User.password' => $this->Auth->data['User']['password'],
)
)
);
if( empty( $user ) || !$this->Auth->login( $user ) ) {
# Set the configured flash message b/c login failed after both checks.
$this->Session->setFlash( $this->Auth->loginError, null, array(), 'auth' );
}
}
$this->redirect( $this->Auth->redirect(), null, true );
}
For action access, just use the $this->Auth->allow() and $this->Auth->deny() methods in each relevant controller's beforeFilter() callback. For example, in the UsersController, you may want to do something like this:
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->deny('*');
$this->Auth->allow( 'login', 'logout' );
}
In views, just determine whether the user is authenticated by testing the Auth.User value to determine what to display/hide from anonymous/authenticated:
if( $this->Session->check( 'Auth.User' ) ) { ... }
If the password changes, you can re-authenticate the user transparently by calling $this->Auth->login( $user_data ). I do this, for example, when a user registers. I don't want him/her to have to then go login, so I just login automatically.
Auth doesn't do exactly what you want out of the box. It can only handle whether a user authentification is required to access an action or not. Once the user is logged in, Auth does not care about the user's level access anymore.
If you wish to use more than two fields, I suggest that you extend the AuthComponent and rewrite the login method to fit your needs. I never did it but I imagine that it is reasonably easy.
Regarding your access levels, I would use ACL that can manage access to actions of all the controllers. Once set up, you will have to manually set the permissions for each actions, either using one of the plugins written by the community or manually.
If you wish to disable part of your views you will need to read the permissions to test the user's access level from there. A good thing would be to save the permissions in a cache file or in the session as the user logs in to make it avaiable in the view. Then write your tests and echo what's needed.
(I am using CakePHP 2.0, I don't know how easily you can extend AuthComponent in 1.3 if you're using it)
With Auth, you need to have exactly 2 fields (that you can specify) to authenticate on. One field (password) will be hashed. Yes, all levels of access you want can be specified in Auth: http://book.cakephp.org/view/1251/Setting-Auth-Component-Variables
You'll have to manage the password change, but the users won't get logged out if they change password.
Sometimes I need that only a part of the view isn't displayed(e.g. login element not displayed)
wut?
Create a custom login() which tries to authenticate through either method.
You can also setup the Authenticate variable to do a custom login.
You can specify in different controllers what parts Auth should be allowing to authenticated users. See Auth methods.
You can also use ACL (see the full Cake ACL tutorial, etc) to control granular permissions.
Sometimes I need that only a part of the view isn't displayed
Create an element which checks for Auth->user() to select what content to display.
For the Allow and Deny part can be easily done with the Auth Component.
use something like
$this->allow('*'); // to allow every thing
$this->deny('*'); // to deny every thing
$this->allow('login', 'signup'); // allows login and sign up without being logged in
$this->deny('profile', 'password'); // need to be logged into to access profile and password and rest of the actions are allowed.
For the change of password you can save the changed password to the database and force logout the user and redirect him to login again
$this->Auth->logout(); this forces the user to logout of cakephp Auth
For the first question - loggin in using email or customer id is not directly possible using cakephp Auth component as you will have to define in particular which of them acts as a username.
Alternative solution is you can just copy the Auth Component into your app/controller/component and hack the code.
When you receive the user name you can test it against email and customer id and maintain the flow.
Hope this helps
I'm running Kohana 3, and having a hard time understanding the Auth module, or even if it's what I need. Basically I want to create a basic user profile site with basic username/password protection.
How do I take my existing controllers...
class Controller_Profile extends Controller
{
function action_index( $user_id )
{
// User should already be authenticated by here I think
}
}
...and use them with some sort of authentication system
For Kohana 3 you'll want to do your check in before and not __construct like JIStone suggests.
public function before()
{
parent::before();
// This automatically checks for an auto login cookie (thanks kemo).
if ( ! Auth::instance()->logged_in())
{
// Redirect to a login page (or somewhere else).
$this->request->redirect('');
}
}
Simple enough to understand. You can put this into a controller and have all the controllers that need authentication to extend that.
If you will be requiring a user to be registered for all pages on the controller you can put a check in your __construct() statement:
function __construct()
{
//Check roles for Access!!!!
parent::__construct();
$this->load_user();
if( ! $this->is_registered )
{
if(request::is_ajax())
die('This ajax call cannot be completed due to permission issues.');
// this will redirect from the login page back to this page
$this->session->set('requested_url', url::current());
url::redirect('user/login');
}
}
This is the code we use, but it is Kohana 2, not 3, so you will need to adjust a bit for your purposes.
I have provided a link to a short walkthrough for the installation and basic usage of the Auth Module in Kohana 3
Once you have your Auth process working, you can protect certain controllers by checking for a logged in user and proper authentication role in your before() method, or create a base controller for all your controllers that will need this check. If the user is not logged in, redirect them to the login page, if they do not have the proper access level (or role), then you can show them an "Access Denied" page.
In CakePHP we can use $this->Auth->allow('someMethod'); to make a page viewable without having to login. How do I make some the same page is not viewable when a user is logged in? An example of this would be a register page which we want to be accessible without user logged in ... but not accessible once a user logged in.
I put $this->Auth->deny('someMethod') in isAuthorized() but it seems to me that if the method is in the allow list then isAuthorized is not called when we try to run that page.
Any input? Thank you
There are no complex rules like that built into Cake Auth. You'll have to manually check for conditions like this. It's very simple though:
// Controller
function register() {
if ($this->Auth->user()) {
$this->redirect(/* somewhere else */);
}
}
Contrary to mlevits answer, you don't need to store anything in the Session, the info is readily available from the AuthComponent itself. http://book.cakephp.org/view/387/user
There's also an example how to do it by dynamically using deny(), but that's not as clear in a simple case like this IMHO. http://book.cakephp.org/view/383/deny
Also, deny() produces an error message ("You're not authorized to access this location"), which is probably not what you want for the user experience in this case.
EDIT:
Wasn't aware that CakePHP used a different syntax.
You can then use the following to set the Session variable:
$this->Session->write('user_id', '<some_user_name>');
Then use this to redirect the user if they are logged in:
if ($this->Session->check('user_id'))
{
$this->redirect('http://google.com');
}
And then to destroy a Session use:
$this->Session->destroy()
More information about CakePHP Sessions
Thanks
You can check it in method beforeFilter in AppController to allow aplication-wide check. For example:
<?php
class AppContoller extends Controller {
var $components = array('Session', 'Auth');
function beforeFilter(){
$this->Auth->allow('register', 'home');
// Check if current action allowed to access without authorization and User has login
if(array_key_exists($this->params['action'], $this->Auth->allowedActions) && $this->Auth->user()){
$this->redirect(/* somewhere else */);
}
}
}
?>
Of course you can also implements it in some controller instead of AppController.