session.go 1.4 KB

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