You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51 lines
944 B

  1. package Auth
  2. import (
  3. "errors"
  4. "net/http"
  5. "time"
  6. )
  7. var (
  8. Sessions = map[string]Session{}
  9. )
  10. type Session struct {
  11. Username string
  12. Expiry time.Time
  13. }
  14. func (s Session) IsExpired() bool {
  15. return s.Expiry.Before(time.Now())
  16. }
  17. func CheckCookie(r *http.Request) (Session, error) {
  18. var (
  19. c *http.Cookie
  20. sessionToken string
  21. userSession Session
  22. exists bool
  23. err error
  24. )
  25. c, err = r.Cookie("session_token")
  26. if err != nil {
  27. return userSession, err
  28. }
  29. sessionToken = c.Value
  30. // We then get the session from our session map
  31. userSession, exists = Sessions[sessionToken]
  32. if !exists {
  33. return userSession, errors.New("Cookie not found")
  34. }
  35. // If the session is present, but has expired, we can delete the session, and return
  36. // an unauthorized status
  37. if userSession.IsExpired() {
  38. delete(Sessions, sessionToken)
  39. return userSession, errors.New("Cookie expired")
  40. }
  41. return userSession, nil
  42. }