5

有人可以简要介绍 Auth 模块中的 user_token 功能吗?什么是用途以及如何将其合并到 Auth 模块中?

4

1 回答 1

12

当用户选中您网站上的“记住我”框时使用它。为用户生成一个令牌并存储在 user_tokens 表中。

如果您查看_login函数中的 Kohana_Auth_ORM 类,您可以看到它是如何创建的:

    if ($remember === TRUE)
    {
        // Create a new autologin token
        $token = ORM::factory('user_token');

        // Set token data
        $token->user_id = $user->id;
        $token->expires = time() + $this->config['lifetime'];
        $token->save();

        // Set the autologin cookie
        cookie::set('authautologin', $token->token, $this->config['lifetime']);
    }

它也被 Kohana_Auth_ORM 类中的auto_login()函数使用:

/**
 * Logs a user in, based on the authautologin cookie.
 *
 * @return  boolean
 */
public function auto_login()
{
    if ($token = cookie::get('authautologin'))
    {
        // Load the token and user
        $token = ORM::factory('user_token', array('token' => $token));

        if ($token->loaded() AND $token->user->loaded())
        {
            if ($token->user_agent === sha1(Request::$user_agent))
            {
                // Save the token to create a new unique token
                $token->save();

                // Set the new token
                cookie::set('authautologin', $token->token, $token->expires - time());

                // Complete the login with the found data
                $this->complete_login($token->user);

                // Automatic login was successful
                return TRUE;
            }

            // Token is invalid
            $token->delete();
        }
    }

    return FALSE;
}

在您的授权控制器中正确使用此功能取决于您。我对 Kohana 比较陌生,但是如果用户进入登录表单并且已经登录或可以自动登录,我会执行一个简单的检查来重定向用户:

if (Auth::instance()->logged_in() || Auth::instance()->auto_login())
    Request::instance()->redirect('auth/');

Auth 模块的代码并不难理解。如果您是 Kohana 的新手,那么了解 ORM 模块的工作原理是一个很好的起点。

于 2010-03-30T13:52:19.013 回答