github.com/covergates/covergates@v0.2.2-0.20201009050117-42ef8a19fb95/modules/session/session.go (about) 1 package session 2 3 import ( 4 "encoding/gob" 5 6 "github.com/covergates/covergates/core" 7 "github.com/gin-contrib/sessions" 8 "github.com/gin-gonic/gin" 9 ) 10 11 func init() { 12 gob.Register(&core.User{}) 13 } 14 15 // Session stores records for Gin 16 type Session struct { 17 } 18 19 const ( 20 keyUser = "user" 21 keyBinding = "bindUser" 22 ) 23 24 // CreateUser in session record 25 func (s *Session) CreateUser(c *gin.Context, user *core.User) error { 26 session := sessions.Default(c) 27 session.Set(keyUser, user) 28 return session.Save() 29 } 30 31 // GetUser from session 32 func (s *Session) GetUser(c *gin.Context) *core.User { 33 session := sessions.Default(c) 34 data := session.Get(keyUser) 35 user, ok := data.(*core.User) 36 if !ok { 37 return &core.User{} 38 } 39 return user 40 } 41 42 // Clear all session records 43 func (s *Session) Clear(c *gin.Context) error { 44 session := sessions.Default(c) 45 session.Clear() 46 return session.Save() 47 } 48 49 // StartBindUser remarks a user is going to bind new SCM account in session 50 func (s *Session) StartBindUser(c *gin.Context) error { 51 session := sessions.Default(c) 52 session.Set(keyBinding, true) 53 return session.Save() 54 } 55 56 // EndBindUser remarks server finishes bind new SCM account in session 57 func (s *Session) EndBindUser(c *gin.Context) error { 58 session := sessions.Default(c) 59 session.Delete(keyBinding) 60 return session.Save() 61 } 62 63 // ShouldBindUser tells if the new SCM login should be with a user 64 func (s *Session) ShouldBindUser(c *gin.Context) bool { 65 session := sessions.Default(c) 66 shouldBind, ok := session.Get(keyBinding).(bool) 67 if !ok || !shouldBind { 68 return false 69 } 70 return true 71 }