auth.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package middleware
  2. import (
  3. "net/http"
  4. "strconv"
  5. "github.com/go-chi/chi"
  6. sessionstore "github.com/porter-dev/porter/internal/auth"
  7. )
  8. type Auth struct {
  9. store *sessionstore.PGStore
  10. cookieName string
  11. }
  12. func NewAuth(
  13. store *sessionstore.PGStore,
  14. cookieName string,
  15. ) *Auth {
  16. return &Auth{store, cookieName}
  17. }
  18. // BasicAuthenticate just checks that a user is logged in
  19. func (auth *Auth) BasicAuthenticate(next http.Handler) http.Handler {
  20. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  21. if auth.isLoggedIn(r) {
  22. next.ServeHTTP(w, r)
  23. } else {
  24. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  25. return
  26. }
  27. return
  28. })
  29. }
  30. // DoesUserIDMatch checks the id URL parameter and verifies that it matches
  31. // the one stored in the session
  32. func (auth *Auth) DoesUserIDMatch(next http.Handler) http.Handler {
  33. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  34. id, err := strconv.ParseUint(chi.URLParam(r, "id"), 0, 64)
  35. if err == nil && auth.doesSessionMatchID(r, uint(id)) {
  36. next.ServeHTTP(w, r)
  37. } else {
  38. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  39. return
  40. }
  41. return
  42. })
  43. }
  44. // Helpers
  45. func (auth *Auth) doesSessionMatchID(r *http.Request, id uint) bool {
  46. session, _ := auth.store.Get(r, auth.cookieName)
  47. if sessID, ok := session.Values["user_id"].(uint); !ok || sessID != id {
  48. return false
  49. }
  50. return true
  51. }
  52. func (auth *Auth) isLoggedIn(r *http.Request) bool {
  53. session, _ := auth.store.Get(r, auth.cookieName)
  54. if auth, ok := session.Values["authenticated"].(bool); !auth || !ok {
  55. return false
  56. }
  57. return true
  58. }