auth.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package middleware
  2. import (
  3. "net/http"
  4. "github.com/gorilla/sessions"
  5. "github.com/labstack/echo/v4"
  6. )
  7. const (
  8. SessionName = "goflare"
  9. UserIDKey = "user_id"
  10. )
  11. func RequireAuth(store sessions.Store) echo.MiddlewareFunc {
  12. return func(next echo.HandlerFunc) echo.HandlerFunc {
  13. return func(c echo.Context) error {
  14. sess, err := GetSession(c, store)
  15. if err != nil {
  16. return c.JSON(http.StatusInternalServerError, map[string]string{"error": "session error"})
  17. }
  18. userID, ok := sess.Values[UserIDKey]
  19. if !ok || userID == nil {
  20. return c.JSON(http.StatusUnauthorized, map[string]string{"error": "not authenticated"})
  21. }
  22. c.Set(UserIDKey, userID)
  23. return next(c)
  24. }
  25. }
  26. }
  27. func GetSession(c echo.Context, store sessions.Store) (*sessions.Session, error) {
  28. sess, err := store.Get(c.Request(), SessionName)
  29. if err != nil {
  30. // Cookie can't be decoded (e.g. secret changed). gorilla/sessions
  31. // still returns a new empty session. Clear its values and the
  32. // IsNew flag is already true, so callers proceed as if no session
  33. // existed. The stale cookie gets overwritten on the next Save().
  34. for k := range sess.Values {
  35. delete(sess.Values, k)
  36. }
  37. return sess, nil
  38. }
  39. return sess, nil
  40. }