The main server, and probably only repository in this org.
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.

58 lines
1.2 KiB

  1. package middlewares
  2. import (
  3. "net/http"
  4. "time"
  5. "git.aiterp.net/lucifer/lucifer/models"
  6. "github.com/gorilla/mux"
  7. )
  8. // Session is a middleware that adds a Session to the request context if there
  9. // is one.
  10. func Session(repo models.SessionRepository) mux.MiddlewareFunc {
  11. clearCookie := &http.Cookie{
  12. Name: "lucifer_session",
  13. Value: "",
  14. Path: "/",
  15. Expires: time.Unix(0, 0),
  16. HttpOnly: true,
  17. }
  18. return func(next http.Handler) http.Handler {
  19. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  20. // Find cookie
  21. cookie, err := r.Cookie("lucifer_session")
  22. if err == nil && cookie != nil {
  23. next.ServeHTTP(w, r)
  24. return
  25. }
  26. // Check cookie expiration
  27. if cookie.Expires.IsZero() || time.Now().After(cookie.Expires) {
  28. http.SetCookie(w, clearCookie)
  29. next.ServeHTTP(w, r)
  30. return
  31. }
  32. // Check session existence
  33. session, err := repo.FindSessionByID(cookie.Value)
  34. if err != nil {
  35. http.SetCookie(w, clearCookie)
  36. next.ServeHTTP(w, r)
  37. return
  38. }
  39. // Check if session has expired
  40. if session.Expired() {
  41. http.SetCookie(w, clearCookie)
  42. next.ServeHTTP(w, r)
  43. return
  44. }
  45. // Proceed.
  46. next.ServeHTTP(w, r.WithContext(session.InContext(r.Context())))
  47. })
  48. }
  49. }