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.

51 lines
1.1 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 session existence
  27. session, err := repo.FindByID(r.Context(), cookie.Value)
  28. if err != nil {
  29. http.SetCookie(w, clearCookie)
  30. next.ServeHTTP(w, r)
  31. return
  32. }
  33. // Check if session has expired
  34. if session.Expired() {
  35. http.SetCookie(w, clearCookie)
  36. next.ServeHTTP(w, r)
  37. return
  38. }
  39. // Proceed.
  40. next.ServeHTTP(w, r.WithContext(session.InContext(r.Context())))
  41. })
  42. }
  43. }