支持多种登录方式的用户表设计
- 最原始的用户登录,user表
user_id | username | password | 用户数据 |
---|---|---|---|
1 | xxxx | 123456 | 用户数据 |
2 | yyyy | 123456 | 用户数据 |
select * from user where user = :user and password = :password
搞定了
- 如果要加入微信登录如何破
加三个字段?
user_id | username | password | wechat_id | wechat_access_token | wechat_expires |
---|---|---|---|---|---|
1 | xxxx | 123456 | sasdada | qwerty | 00000000 |
再添加qq登录呢?再加三个字段,显然是要累死人的
- 靠谱的做法
用户信息和登录分开,登录分为本地登录和第三方登录
- user表
user_id | 用户数据 |
---|---|
1 | 用户数据 |
2 | 用户数据 |
- 本地登录表
user_id | username | password |
---|---|---|
1 | xxxx | 123456 |
2 | yyyy | 123456 |
- 第三方OAuth登录表
id | user_id | oauth_name | oauth_id | oauth_access_token | oauth_expires |
---|---|---|---|---|---|
1 | A1 | W-012345 | xxxxxxxxxx | 604800 |
- 还需要其他登录方式?
加个表好了
- 有了多种登录方式,登录代码改如何写?
看完参考链接中的文章,感觉之前代码都写的太挫了。此处省略吐槽,直接说原作者的方法
准备工作
- 首先需要实现Middleware,各种web开发语言环境下都可以实现,此处不做讨论
- 其次需要Authenticator interface来统一登录接口
逻辑
对每一种登录方式,写一个Authenticator接口实现
interface Authenticator{
function auth(){}
}
class ApiAuthenticator exntends Authenticator{
function auth(){
....
}
}
class ApiAuthenticator exntends Authenticator{
function auth(){
....
}
}
class ApiAuthenticator exntends Authenticator{
{
....
}
}
Middleware中循环调用
class Middleware{
public function __invoke($request, $response, $next){
foreach($auths as $auth){
$result = $auth->auth();
if($result !== false){
// 认证成功
....
break;
}
}
$response = $next($request, $response);
return $response;
}
}
参考链接
https://www.liaoxuefeng.com/article/1029274073038464
https://www.liaoxuefeng.com/article/1078848528483840
https://www.liaoxuefeng.com/article/1079209877054048