IT评测·应用市场-qidao123.com

标题: 用go设计开发一个自己的轻量级登录库/框架吧(业务篇) [打印本页]

作者: 科技颠覆者    时间: 2023-5-13 11:52
标题: 用go设计开发一个自己的轻量级登录库/框架吧(业务篇)
用go设计开发一个自己的轻量级登录库/框架吧(业务篇)

本篇会讲讲框架的登录业务的实现。实现三种登录模式:
源码:weloe/token-go: a light login library (github.com)
存储结构

首先从我们要考虑是底层该怎么存储登录信息来去达成这三种登录模式
我们不能使用无状态token模式,要有状态,在后端存储会话信息才能达成想要实现的一些逻辑,因此,存储会话信息是必要的。
对于每个请求,我们会存储一个token-loginId的k-v结构。
对于整个会话,我们会存储一个loginId-session的k-v结构。
基于这个存储结构我们就可以方便的实现这三种模式。
Session结构体
session包括了多个tokenValue,这就是我们用来实现同一用户多次登录多token,或者同一用户多次登录共享一个token的关键点
  1. type TokenSign struct {
  2.    Value  string
  3.    Device string
  4. }
  5. type Session struct {
  6.    Id            string
  7.    TokenSignList *list.List
  8. }
复制代码
总之,我们实现的业务将基于这两种k-v结构
功能实现

源码:https://github.com/weloe/token-go/blob/f58ba4d93f0f012972bf6a35b9127229b5c328fe/enforcer.go#L167
我们再来梳理一些功能和配置的对应关系
同一用户只能登录一次:IsConcurrent == false
同一用户多次登录多token: IsConcurrent == true && IsShare == false这时候配置MaxLoginCount才生效
同一用户多次登录共享一个token: IsConcurrent == true && IsShare == true
接着我们再讲讲登录的具体流程:
我们大致将它分为几个阶段:
生成token

https://github.com/weloe/token-go/blob/f58ba4d93f0f012972bf6a35b9127229b5c328fe/enforcer_internal_api.go#L12
生成token的时候,我们要判断他是否是可多次登录,也就是isConcurrent是否为false。
如果可多次登录并且共享token即IsConcurrent == true && IsShare == true,就判断能否复用之前的token
这里我们还允许用户自定义token。
loginModel *model.Login是为了支持自定义这几个参数
  1. type model.Login struct {
  2.         Device          string
  3.         IsLastingCookie bool
  4.         Timeout         int64
  5.         Token           string
  6.         IsWriteHeader   bool
  7. }
复制代码
  1. // createLoginToken create by config.TokenConfig and model.Login
  2. func (e *Enforcer) createLoginToken(id string, loginModel *model.Login) (string, error) {
  3.         tokenConfig := e.config
  4.         var tokenValue string
  5.         var err error
  6.         // if isConcurrent is false,
  7.         if !tokenConfig.IsConcurrent {
  8.                 err = e.Replaced(id, loginModel.Device)
  9.                 if err != nil {
  10.                         return "", err
  11.                 }
  12.         }
  13.         // if loginModel set token, return directly
  14.         if loginModel.Token != "" {
  15.                 return loginModel.Token, nil
  16.         }
  17.         // if share token
  18.         if tokenConfig.IsConcurrent && tokenConfig.IsShare {
  19.                 // reuse the previous token.
  20.                 if v := e.GetSession(id); v != nil {
  21.                         tokenValue = v.GetLastTokenByDevice(loginModel.Device)
  22.                         if tokenValue != "" {
  23.                                 return tokenValue, nil
  24.                         }
  25.                 }
  26.         }
  27.         // create new token
  28.         tokenValue, err = e.generateFunc.Exec(tokenConfig.TokenStyle)
  29.         if err != nil {
  30.                 return "", err
  31.         }
  32.         return tokenValue, nil
  33. }
复制代码
生成session

https://github.com/weloe/token-go/blob/f58ba4d93f0f012972bf6a35b9127229b5c328fe/enforcer.go#L183
先判断是否已经存在session,如果不存在需要先创建,避免空指针
  1.         // add tokenSign
  2.         if session = e.GetSession(id); session == nil {
  3.                 session = model.NewSession(e.spliceSessionKey(id), "account-session", id)
  4.         }
  5.         session.AddTokenSign(&model.TokenSign{
  6.                 Value:  tokenValue,
  7.                 Device: loginModel.Device,
  8.         })
复制代码
存储

https://github.com/weloe/token-go/blob/f58ba4d93f0f012972bf6a35b9127229b5c328fe/enforcer.go#L192
在存储的时候,需要拼接key防止与其他的key重复
  1.         // reset session
  2.         err = e.SetSession(id, session, loginModel.Timeout)
  3.         if err != nil {
  4.                 return "", err
  5.         }
  6.         // set token-id
  7.         err = e.adapter.SetStr(e.spliceTokenKey(tokenValue), id, loginModel.Timeout)
  8.         if err != nil {
  9.                 return "", err
  10.         }
复制代码
返回token

https://github.com/weloe/token-go/blob/f58ba4d93f0f012972bf6a35b9127229b5c328fe/enforcer_internal_api.go#L51
这个操作对应我们配置的TokenConfig的IsReadCookie、IsWriteHeader和CookieConfig
  1. // responseToken set token to cookie or header
  2. func (e *Enforcer) responseToken(tokenValue string, loginModel *model.Login, ctx ctx.Context) error {
  3.    if ctx == nil {
  4.       return nil
  5.    }
  6.    tokenConfig := e.config
  7.    // set token to cookie
  8.    if tokenConfig.IsReadCookie {
  9.       cookieTimeout := tokenConfig.Timeout
  10.       if loginModel.IsLastingCookie {
  11.          cookieTimeout = -1
  12.       }
  13.       // add cookie use tokenConfig.CookieConfig
  14.       ctx.Response().AddCookie(tokenConfig.TokenName,
  15.          tokenValue,
  16.          tokenConfig.CookieConfig.Path,
  17.          tokenConfig.CookieConfig.Domain,
  18.          cookieTimeout)
  19.    }
  20.    // set token to header
  21.    if loginModel.IsWriteHeader {
  22.       ctx.Response().SetHeader(tokenConfig.TokenName, tokenValue)
  23.    }
  24.    return nil
  25. }
复制代码
调用watcher和logger

https://github.com/weloe/token-go/blob/f58ba4d93f0f012972bf6a35b9127229b5c328fe/enforcer.go#L210
在事件发生后回调,提供扩展点
  1.         // called watcher
  2.         m := &model.Login{
  3.                 Device:          loginModel.Device,
  4.                 IsLastingCookie: loginModel.IsLastingCookie,
  5.                 Timeout:         loginModel.Timeout,
  6.                 JwtData:         loginModel.JwtData,
  7.                 Token:           tokenValue,
  8.                 IsWriteHeader:   loginModel.IsWriteHeader,
  9.         }
  10.         // called logger
  11.         e.logger.Login(e.loginType, id, tokenValue, m)
  12.         if e.watcher != nil {
  13.                 e.watcher.Login(e.loginType, id, tokenValue, m)
  14.         }
复制代码
检测登录人数

https://github.com/weloe/token-go/blob/f58ba4d93f0f012972bf6a35b9127229b5c328fe/enforcer.go#L227
要注意的是检测登录人数需要配置IsConcurrent == true && IsShare == false,也就是:同一用户多次登录多token模式,提供一个特殊值-1,如果为-1就认为不对登录数量进行限制,不然就开始强制退出,就是删除一部分的token
  1.         // if login success check it
  2.         if tokenConfig.IsConcurrent && !tokenConfig.IsShare {
  3.                 // check if the number of sessions for this account exceeds the maximum limit.
  4.                 if tokenConfig.MaxLoginCount != -1 {
  5.                         if session = e.GetSession(id); session != nil {
  6.                                 // logout account until loginCount == maxLoginCount if loginCount > maxLoginCount
  7.                                 for element, i := session.TokenSignList.Front(), 0; element != nil && i < session.TokenSignList.Len()-int(tokenConfig.MaxLoginCount); element, i = element.Next(), i+1 {
  8.                                         tokenSign := element.Value.(*model.TokenSign)
  9.                                         // delete tokenSign
  10.                                         session.RemoveTokenSign(tokenSign.Value)
  11.                                         // delete token-id
  12.                                         err = e.adapter.Delete(e.spliceTokenKey(tokenSign.Value))
  13.                                         if err != nil {
  14.                                                 return "", err
  15.                                         }
  16.                                 }
  17.                                 // check TokenSignList length, if length == 0, delete this session
  18.                                 if session != nil && session.TokenSignList.Len() == 0 {
  19.                                         err = e.deleteSession(id)
  20.                                         if err != nil {
  21.                                                 return "", err
  22.                                         }
  23.                                 }
  24.                         }
  25.                 }
复制代码
测试

同一用户只能登录一次

https://github.com/weloe/token-go/blob/f58ba4d93f0f012972bf6a35b9127229b5c328fe/enforcer_test.go#L295
  1. IsConcurrent = false
  2. IsShare = false
复制代码
  1. func TestEnforcerNotConcurrentNotShareLogin(t *testing.T) {
  2.         err, enforcer, ctx := NewTestNotConcurrentEnforcer(t)
  3.         if err != nil {
  4.                 t.Errorf("InitWithConfig() failed: %v", err)
  5.         }
  6.         loginModel := model.DefaultLoginModel()
  7.         for i := 0; i < 4; i++ {
  8.                 _, err = enforcer.LoginByModel("id", loginModel, ctx)
  9.                 if err != nil {
  10.                         t.Errorf("Login() failed: %v", err)
  11.                 }
  12.         }
  13.         session := enforcer.GetSession("id")
  14.         if session.TokenSignList.Len() != 1 {
  15.                 t.Errorf("Login() failed: unexpected session.TokenSignList length = %v", session.TokenSignList.Len())
  16.         }
  17. }
复制代码
同一用户多次登录共享一个token

https://github.com/weloe/token-go/blob/f58ba4d93f0f012972bf6a35b9127229b5c328fe/enforcer_test.go#L335
  1. IsConcurrent = true
  2. IsShare = false
复制代码
  1. func TestEnforcer_ConcurrentNotShareMultiLogin(t *testing.T) {
  2.         err, enforcer, ctx := NewTestConcurrentEnforcer(t)
  3.         if err != nil {
  4.                 t.Errorf("InitWithConfig() failed: %v", err)
  5.         }
  6.         loginModel := model.DefaultLoginModel()
  7.         for i := 0; i < 14; i++ {
  8.                 _, err = enforcer.LoginByModel("id", loginModel, ctx)
  9.                 if err != nil {
  10.                         t.Errorf("Login() failed: %v", err)
  11.                 }
  12.         }
  13.         session := enforcer.GetSession("id")
  14.         if session.TokenSignList.Len() != 12 {
  15.                 t.Errorf("Login() failed: unexpected session.TokenSignList length = %v", session.TokenSignList.Len())
  16.         }
  17. }
复制代码
同一用户多次登录多token

https://github.com/weloe/token-go/blob/f58ba4d93f0f012972bf6a35b9127229b5c328fe/enforcer_test.go#LL316C17-L316C17
  1. IsConcurrent = true
  2. IsShare = true
复制代码
  1. func TestEnforcer_ConcurrentShare(t *testing.T) {
  2.         err, enforcer, ctx := NewTestEnforcer(t)
  3.         if err != nil {
  4.                 t.Errorf("InitWithConfig() failed: %v", err)
  5.         }
  6.         loginModel := model.DefaultLoginModel()
  7.         for i := 0; i < 5; i++ {
  8.                 _, err = enforcer.LoginByModel("id", loginModel, ctx)
  9.                 if err != nil {
  10.                         t.Errorf("Login() failed: %v", err)
  11.                 }
  12.         }
  13.         session := enforcer.GetSession("id")
  14.         if session.TokenSignList.Len() != 1 {
  15.                 t.Errorf("Login() failed: unexpected session.TokenSignList length = %v", session.TokenSignList.Len())
  16.         }
  17. }
复制代码
至此,我们就实现了三种登录模式,

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/) Powered by Discuz! X3.4