session.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. Language string `json:"language"`
  18. PocketRequestToken string `json:"pocket_request_token"`
  19. }
  20. func (s SessionData) String() string {
  21. return fmt.Sprintf(`CSRF="%s", "OAuth2State="%s", FlashMessage="%s", FlashErrorMessage="%s", Lang="%s"`,
  22. s.CSRF, s.OAuth2State, s.FlashMessage, s.FlashErrorMessage, s.Language)
  23. }
  24. // Value converts the session data to JSON.
  25. func (s SessionData) Value() (driver.Value, error) {
  26. j, err := json.Marshal(s)
  27. return j, err
  28. }
  29. // Scan converts raw JSON data.
  30. func (s *SessionData) Scan(src interface{}) error {
  31. source, ok := src.([]byte)
  32. if !ok {
  33. return errors.New("session: unable to assert type of src")
  34. }
  35. err := json.Unmarshal(source, s)
  36. if err != nil {
  37. return fmt.Errorf("session: %v", err)
  38. }
  39. return err
  40. }
  41. // Session represents a session in the system.
  42. type Session struct {
  43. ID string
  44. Data *SessionData
  45. }
  46. func (s *Session) String() string {
  47. return fmt.Sprintf(`ID="%s", Data={%v}`, s.ID, s.Data)
  48. }