2
0

auth.go 715 B

12345678910111213141516171819202122232425262728293031323334353637
  1. package middleware
  2. import (
  3. "net/http"
  4. "github.com/gorilla/sessions"
  5. )
  6. var (
  7. key = []byte("secret") // change to os.Getenv("SESSION_KEY")
  8. store = sessions.NewCookieStore(key)
  9. )
  10. // ContentTypeJSON sets the content type for requests to application/json
  11. func authenticate(next http.Handler) http.Handler {
  12. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  13. if isLoggedIn(r) {
  14. next.ServeHTTP(w, r)
  15. } else {
  16. http.Error(w, http.StatusText(403), 403)
  17. return
  18. }
  19. return
  20. })
  21. }
  22. // Helpers
  23. func isLoggedIn(r *http.Request) bool {
  24. session, _ := store.Get(r, "session-id")
  25. if auth, ok := session.Values["authenticated"].(bool); !auth || !ok {
  26. return false
  27. }
  28. return true
  29. }