sess.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package sec
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "git.clearsky.net.au/cody/gex.git/sec/jwt"
  6. "git.clearsky.net.au/cody/gex.git/srv"
  7. "time"
  8. )
  9. type Sess struct {
  10. req *srv.Req
  11. res srv.Res
  12. User_id int
  13. User_name string
  14. Roles []string
  15. Expires time.Time
  16. Props map[string]any
  17. }
  18. var TokenName string = "GexToken"
  19. var Expires time.Time = time.Now().Add(24 * time.Hour)
  20. var Secret string = "secret"
  21. func (sess *Sess) setDefaults() {
  22. sess.User_id = 0
  23. sess.User_name = "Guest"
  24. sess.Roles = []string{"Guest", "Everyone"}
  25. sess.Expires = Expires
  26. }
  27. func (sess *Sess) Construct(req *srv.Req, res srv.Res) {
  28. sess.req = req
  29. sess.res = res
  30. sess.Props = make(map[string]any)
  31. sess.setDefaults()
  32. // check cookie is valid (not expired too)
  33. cookie, err := req.Cookie(TokenName)
  34. if err != nil {
  35. //fmt.Println("cookie error")
  36. return
  37. }
  38. // decode jwt to json bytes
  39. jsonByt, err := jwt.Decode(cookie, Secret)
  40. if err != nil {
  41. fmt.Println("jwt decode error")
  42. return
  43. }
  44. // decode json bytes to session
  45. err = json.Unmarshal(jsonByt, &sess)
  46. if err != nil {
  47. fmt.Println("jwt to session error")
  48. return
  49. }
  50. // if session token has expired, return default session
  51. if time.Now().After(sess.Expires) {
  52. fmt.Println("session expired")
  53. sess.setDefaults()
  54. }
  55. sess.Expires = Expires
  56. }
  57. func (sess *Sess) Token() (string, error) {
  58. jsonStr, err := json.Marshal(sess)
  59. if err != nil {
  60. return "", err
  61. }
  62. // encode the json to jwt and set the cookie
  63. token, err := jwt.Encode(jsonStr, Secret)
  64. if err != nil {
  65. return "", err
  66. }
  67. return token, nil
  68. }
  69. func (sess *Sess) HasRole(roleName string) bool {
  70. for _, role := range sess.Roles {
  71. if role == roleName {
  72. return true
  73. }
  74. }
  75. return false
  76. }
  77. // Saves token to cookie
  78. func (sess *Sess) Save() {
  79. // get existing session or create new one
  80. // get the session token
  81. token, err := sess.Token()
  82. if err != nil {
  83. sess.res.Send(err.Error())
  84. return
  85. }
  86. // set the token cookie
  87. sess.res.Cookie(TokenName, token)
  88. }