开发者

Kohana V3 Auth module user_token functionality

开发者 https://www.devze.com 2022-12-24 22:05 出处:网络
Could anybody brief about user_token functionality in Auth module? What is a use开发者_JAVA百科 and how this incorporates in Auth module?It is used when a user checks the \'Remember me\' box on your s

Could anybody brief about user_token functionality in Auth module? What is a use开发者_JAVA百科 and how this incorporates in Auth module?


It is used when a user checks the 'Remember me' box on your site. A token is generated for the user and stored in the user_tokens table.

If you look at the Kohana_Auth_ORM class in the _login function, you can see how it is created:

    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']);
    }

It is used by the auto_login() function also in the Kohana_Auth_ORM class:

/**
 * 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;
}

It is up to you to correctly use this capability within your authorization controller. I'm relatively new to Kohana, but I perform a simple check to redirect a user if they go to the login form and are already logged in or can automatically login:

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

The code for the Auth module isn't too difficult to understand. If you're new to Kohana, it's a good starting point to see how the ORM module works.

0

精彩评论

暂无评论...
验证码 换一张
取 消