cakephp登录重定向 [英] cakephp login redirect

查看:187
本文介绍了cakephp登录重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户前端和一个管理区域。如果用户登录并且trys转到管理员URL,他们被重定向到索引页。我希望将其重定向到管理登录页面,并显示以管理员身份登录的消息。

I have a user front end and an admin area. If a user is signed in and trys to go to the to the admin url they are redirected to the index page. I wish to redirect them to the admin login page with a message to login as administrator.

可能有一种情况,管理员以用户身份登录,然后trys登录管理区。我无法重新分配给管理员登录信息,并提供退出登录并以管理员身份登录的选项。

There may be a case where a admin is logged in as a user and then trys to login into the admin area. I have not been able to rediect to the admin login and give option to log out and log in as admin.

app_controller

app_controller

function beforeFilter() {

    $this->Auth->loginError = "Wrong credentials";
    $this->Auth->authError = "This part of the website is protected.";

    //Configure AuthComponent   
    $this->Auth->allow('display');
    $this->Auth->authorize = 'actions';
    $this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
    $this->Auth->logoutRedirect = array('controller' => 'users', 'action' => 'login');
    //$this->Auth->autoRedirect = false;
    //$this->Auth->loginRedirect = array('controller' => 'reservatins', 'action' => 'index');


} // end before filter

users_controller



users_controller

function beforeFilter() {
    parent::beforeFilter();
    $this->Auth->allowedActions = array('admin_login','admin_logout');
    //$this->Auth->allowedActions = array('*');
    $this->set('select_nav', array('admin','users'));

}


function admin_login() {
    // $this->layout = 'admin'; // nothing required
    $this->layout = 'blank'; // nothing required
}


推荐答案

做我的一个项目。用户曾经登录过(匿名,用户或管理员),根据他来自哪里以及当前的权限,我显示不同的登录错误。

I have done that on one of my projects. The user is ever logged in (as Anonymous, as User or as Admin) and, depending on from where is he coming, and the current permissions he have, I show different login errors.

这是我做的...

首先,你需要使用controller授权方法:

First, you need to use the "controller" authorize method:

$this->Auth->authorize = 'controller';

从现在开始,所有操作都将通过 isAuthorized 方法。由于我有我的用户,我的数据库和每个组的组和权限具有不同的权限,我在我的app_controller上创建了 isAuthorized 方法:

From now on, all your actions will pass through the isAuthorized method of your current controller. As I have my users, groups and permissions on my database and every group have different permissions, I created the isAuthorized method on my app_controller:

public function isAuthorized()
{
    if ( !$this->__permitted($this->name, $this->action) )
    {
        $this->cakeError('error403');
        return false;
    }
    return true;
}

我在这里做的是通过我的AppController检查用户权限 __ allowed 方法(它只是检查会话权限;如果我们没有在会话中保存它们,我在DB上检查它们,然后将它们存储在会话中)。

What I'm doing here is checking for user permissions through my AppController __permitted method (it simply checks for permissions on session; if we don't have them saved in session, I check for them on the DB and then I store them on the Session).

如果用户没有权限,我会向他显示错误403.这里是有趣的部分。

If the user don't have permissions, I show him the error 403. And here is the funny part.

在您的AppError中添加一个名为error403的方法,在这里您可以控制重定向到哪里以及向他显示什么样的消息。

In your AppError add a method called error403, and here you can control where to redirect the user and what kind of message to show to him.

代码我已经使用(显然你必须根据你的需要创建自己的代码片段):

Here is the code I've used (obviously you must create your own piece of code according to your needs):

public function error403()
{
    // Extract params
    extract($this->controller->params, EXTR_OVERWRITE);

    // Store url to be redirected on success
    if (!isset($url))
    {
        $url = $this->controller->here;
    }
    if (isset($url['url']))
    {
        $url = $url['url'];
    }
    $url = Router::normalize($url);

    // The page is trying to access is an admin page?
    $is_admin_page = isset($this->controller->params['admin']) && $this->controller->params['admin'] == true ?  true : false;

    if (!empty($url) && count($url) >= 2)
    {
        $query = $url;
        unset($query['url'], $query['ext']);
        $url .= Router::queryString($query, array());
    }
    // 403 header
    $this->controller->header("HTTP/1.0 403 Forbidden");

    // If my method is NOT an upload
    if (!preg_match('/upload/', $url))
    {
        // Write referer to session, so we can use it later
        $this->controller->Session->write('Auth.redirect', $url);
    }
    else exit; // else exit, so we prevent 302 header from redirect

    // NOTE: we can't use $this->controller->Auth->loginAction because there's no controller loaded
    $loginAction = array('controller' => 'users', 'action' => 'login');

    // If is ajax...
    if (isset($this->controller->params['isAjax']) && $this->controller->params['isAjax'] == true)
    {
        $this->controller->layout = 'ajax';

        $message = __("No tens permisos per fer aquesta acció", true);
        // If user is anonymous..
        if ( $this->controller->ISession->isAnonymous() )
        {
            // AJAX Error Message
            $message = __('La teva sessió no està iniciada.', true) 
                . ' <a href="'.Router::url($loginAction).'">' 
                . __('Fes clic aquí per iniciar-la', true) . '</a>';
        }

        $this->controller->set(compact('message'));
        $this->controller->render('error403');

        $this->controller->afterFilter();
        echo $this->controller->output;
    }
    else
    {
        $message = __("No tens permisos per fer aquesta acció", true);
        $redirect = $this->controller->referer();

        // If is anonymous...
        if ($this->controller->ISession->isAnonymous())
        {
            $message = __('La teva sessió no està iniciada.', true);
            $redirect = $loginAction;
        }
        // If user can't access the requested page, we redirect him to login
        if (!$this->controller->ISession->userCan($redirect))
        {
            $redirect = $loginAction;
        }

        // Show different auth messages for admin and user pages
        $this->controller->Session->setFlash($message, $is_admin_page ? 'default' : 'gritter', array(), 'auth');
        $this->controller->redirect($redirect, null, true);
    }
}

记住,这是我的case的代码。你应该根据自己的需要创建自己的error403页面。当然,你可以从我的方法开始得到它:)

Remember, this is the code for my case. You should create your own error403 page according to your needs. Of course, you can start with my method to get it :)

这篇关于cakephp登录重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆