gpt4 book ai didi

php - Session 在用户认证/登录中的作用?

转载 作者:行者123 更新时间:2023-12-03 23:07:39 24 4
gpt4 key购买 nike

我希望有人能帮助我解决我遇到的问题。

我有一个 Session 对象来处理一般 session 数据的存储,我还有一个 Authentication 对象来验证用户凭据。

最初,我将所需的身份验证类名称传递给我的 session 对象,然后有一个登录方法创建身份验证对象的实例并验证凭据。我将验证的结果存储在 Session 变量中,并通过 getter 使其可用。用户数据也存储在Session中以供以后使用。除此之外,我还有一个注销方法,它从 session 中删除用户数据,从而将用户注销。

我的问题是 Session 对象在用户登录其帐户时应扮演什么角色?

还有什么其他方法可以建议我处理用户登录,就目前情况而言,我感觉好像我太专注于我的 Session 对象了。

最佳答案

简单地调用您的身份验证方法应该会触发Auth中的逻辑,以在 session (或其他一些数据存储)中存储正确的数据,并且Auth还应该专门用于检索/撤销此信息。因此,使用您的评论中的示例可能是:

class Auth {
public static function authenticate($identity, $pass)
{
// do lookup to match identity/pass if its good then

/* assume $auth is an array with the username/email or
whatever data you need to store as part of authentication */
Session::set('auth', $auth);
return true;

// if auth failed then
Session::set('auth', array('user'=>'anonymous'));
return false;
}

public function isAuthenticated()
{
$auth = Session::get('auth');
if(!$auth)
{
return false;
}

return (isset($auth['user']) && $auth['user'] !== 'anonymous');
}
}

[...] as it stands right now I feel as though I'm getting too much wrapped up in my Session object.

我也同意。理想情况下,对于身份验证/凭证,您应该只与 Auth/Acl 对象进行交互。然后他们会将 session 用作有状态存储......但您不应该关心它甚至存储在 session 中。使用 Auth/Acl 对象的代码应该完全不知道这一事实。

例如:

//Bad

if($session->get('authenticated', 'auth'))
{
// do stuff
}


// also bad

if(isset($_SESSION['authenticated']))
{
// do stuff
}


//Good

if($auth->isAuthenticated())
{
// do stuff
}

// inside $auth class it might look like this
public function isAuthenticated()
{
$store = $this->getSotrage(); // assume this returns the $_SESSION['auth']
return isset($store['authenticated']);
}

关于php - Session 在用户认证/登录中的作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2114888/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com