github.com/kyleu/dbaudit@v0.0.2-0.20240321155047-ff2f2c940496/app/lib/auth/msfix/session.go (about) 1 // Package msfix - Content managed by Project Forge, see [projectforge.md] for details. 2 package msfix 3 4 import ( 5 "encoding/json" 6 "time" 7 8 "github.com/markbates/goth" 9 "github.com/pkg/errors" 10 ) 11 12 type Session struct { 13 AuthURL string 14 AccessToken string 15 ExpiresAt time.Time 16 } 17 18 func (s Session) GetAuthURL() (string, error) { 19 if s.AuthURL == "" { 20 return "", errors.New(goth.NoAuthUrlErrorMessage) 21 } 22 23 return s.AuthURL, nil 24 } 25 26 func (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) { 27 p, ok := provider.(*Provider) 28 if !ok { 29 return "", errors.Errorf("invalid provider of type [%T]", provider) 30 } 31 token, err := p.config.Exchange(goth.ContextForClient(p.Client()), params.Get("code")) 32 if err != nil { 33 return "", err 34 } 35 36 if !token.Valid() { 37 return "", errors.New("invalid token received from provider") 38 } 39 40 s.AccessToken = token.AccessToken 41 s.ExpiresAt = token.Expiry 42 43 return token.AccessToken, err 44 } 45 46 func (s Session) Marshal() string { 47 b, _ := json.Marshal(s) //nolint:errchkjson // no chance of error 48 return string(b) 49 } 50 51 func (s Session) String() string { 52 return s.Marshal() 53 }