github.com/infraboard/keyauth@v0.8.1/apps/session/session_ext.go (about) 1 package session 2 3 import ( 4 "github.com/go-playground/validator/v10" 5 "github.com/infraboard/mcube/exception" 6 "github.com/mssola/user_agent" 7 "github.com/rs/xid" 8 9 "github.com/infraboard/keyauth/apps/token" 10 ) 11 12 // use a single instance of Validate, it caches struct info 13 var ( 14 validate = validator.New() 15 ) 16 17 // NewSession todo 18 func NewSession(tk *token.Token) (*Session, error) { 19 if err := tk.IsAvailable(); err != nil { 20 return nil, exception.NewPermissionDeny("token is not available, %s", err) 21 } 22 23 sess := &Session{ 24 Id: xid.New().String(), 25 Domain: tk.Domain, 26 Account: tk.Account, 27 UserType: tk.UserType, 28 ApplicationId: tk.ApplicationId, 29 ApplicationName: tk.ApplicationName, 30 GrantType: tk.GrantType, 31 AccessToken: tk.AccessToken, 32 LoginAt: tk.CreateAt, 33 LoginIp: tk.GetRemoteIP(), 34 UserAgent: &UserAgent{}, 35 IpInfo: &IPInfo{}, 36 } 37 sess.ParseUserAgent(tk.GetUserAgent()) 38 39 return sess, nil 40 } 41 42 // NewDefaultSession todo 43 func NewDefaultSession() *Session { 44 return &Session{ 45 UserAgent: &UserAgent{}, 46 IpInfo: &IPInfo{}, 47 } 48 } 49 50 // ParseUserAgent todo 51 func (s *Session) ParseUserAgent(userAgent string) { 52 if userAgent == "" { 53 return 54 } 55 56 ua := user_agent.New(userAgent) 57 s.UserAgent = &UserAgent{ 58 Os: ua.OS(), 59 Platform: ua.Platform(), 60 } 61 s.UserAgent.EngineName, s.UserAgent.EngineVersion = ua.Engine() 62 s.UserAgent.BrowserName, s.UserAgent.BrowserVersion = ua.Browser() 63 } 64 65 // NewSessionSet 实例化 66 func NewSessionSet() *Set { 67 return &Set{ 68 Items: []*Session{}, 69 } 70 } 71 72 // Add 添加应用 73 func (s *Set) Add(item *Session) { 74 s.Items = append(s.Items, item) 75 } 76 77 // Length 长度 78 func (s *Set) Length() int { 79 return len(s.Items) 80 } 81 82 // IsEmpty 长度 83 func (s *Set) IsEmpty() bool { 84 return len(s.Items) == 0 85 }