有没有人可以了解Auth模块中的user_token功能?什么是用途以及如何将其纳入Auth模块?
答案 0 :(得分: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模块的工作原理是一个很好的起点。