Kohana V3 Auth模块user_token功能

Asi*_*sif 5 php frameworks kohana kohana-3

任何人都可以简要了解Auth模块中的user_token功能吗?什么是用途以及它如何在Auth模块中包含?

Bri*_*man 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']);
    }
Run Code Online (Sandbox Code Playgroud)

它也被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;
}
Run Code Online (Sandbox Code Playgroud)

您可以在授权控制器中正确使用此功能.我对Kohana相对比较新,但是如果他们转到登录表单并且已经登录或者可以自动登录,我会执行一个简单的检查来重定向用户:

if (Auth::instance()->logged_in() || Auth::instance()->auto_login())
    Request::instance()->redirect('auth/');
Run Code Online (Sandbox Code Playgroud)

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