session.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright 2017 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package model
  5. import (
  6. "database/sql/driver"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. )
  11. // SessionData represents the data attached to the session.
  12. type SessionData struct {
  13. CSRF string `json:"csrf"`
  14. OAuth2State string `json:"oauth2_state"`
  15. FlashMessage string `json:"flash_message"`
  16. FlashErrorMessage string `json:"flash_error_message"`
  17. }
  18. func (s SessionData) String() string {
  19. return fmt.Sprintf(`CSRF="%s", "OAuth2State="%s", FlashMessage="%s", "FlashErrorMessage="%s"`,
  20. s.CSRF, s.OAuth2State, s.FlashMessage, s.FlashErrorMessage)
  21. }
  22. // Value converts the session data to JSON.
  23. func (s SessionData) Value() (driver.Value, error) {
  24. j, err := json.Marshal(s)
  25. return j, err
  26. }
  27. // Scan converts raw JSON data.
  28. func (s *SessionData) Scan(src interface{}) error {
  29. source, ok := src.([]byte)
  30. if !ok {
  31. return errors.New("session: unable to assert type of src")
  32. }
  33. err := json.Unmarshal(source, s)
  34. if err != nil {
  35. return fmt.Errorf("session: %v", err)
  36. }
  37. return err
  38. }
  39. // Session represents a session in the system.
  40. type Session struct {
  41. ID string
  42. Data *SessionData
  43. }
  44. func (s *Session) String() string {
  45. return fmt.Sprintf(`ID="%s", Data="%v"`, s.ID, s.Data)
  46. }