Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(middleware): move middlewares to middleware file #12

Merged
merged 1 commit into from
Oct 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 44 additions & 1 deletion api/router/middleware.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
package router

import "net/http"
import (
"net/http"
"os"

"github.com/joho/godotenv"
"github.com/vit0rr/short-spot/pkg/log"
)

// SetResponseTypeToJSON is a middleware sets the response type to JSON
func SetResponseTypeToJSON(next http.Handler) http.Handler {
Expand All @@ -9,3 +15,40 @@ func SetResponseTypeToJSON(next http.Handler) http.Handler {
next.ServeHTTP(w, r)
})
}

// AuthMiddleware is a middleware that checks if the request has a valid auth token
func AuthMiddleware(next http.Handler) http.Handler {
godotenv.Load()

return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
next.ServeHTTP(w, r)
return
}

token := r.Header.Get("Authorization")
if token != os.Getenv("AUTH_TOKEN") {
log.Error(r.Context(), "Unauthorized. Please provide a valid auth token")
http.Error(w, "Unauthorized. Please provide a valid auth token", http.StatusUnauthorized)
return
}

next.ServeHTTP(w, r)
})
}

// CorsMiddleware is a middleware that sets the CORS headers
func CorsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With")

if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}

next.ServeHTTP(w, r)
})
}
50 changes: 5 additions & 45 deletions api/router/router.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,10 @@
package router

import (
"net/http"
"os"

"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/joho/godotenv"
urlshort "github.com/vit0rr/short-spot/api/internal/url-short"
"github.com/vit0rr/short-spot/pkg/deps"
"github.com/vit0rr/short-spot/pkg/log"
"github.com/vit0rr/short-spot/pkg/telemetry"
"go.mongodb.org/mongo-driver/mongo"
)
Expand All @@ -24,12 +19,12 @@ func (router *Router) BuildRoutes() *chi.Mux {
r.Use(middleware.Recoverer)
r.Use(middleware.RealIP)
r.Use(middleware.StripSlashes)
r.Use(SetResponseTypeToJSON)
r.Use(telemetry.TelemetryMiddleware)

// Custom middleware
r.Use(corsMiddleware)
r.Use(authMiddleware)
// Custom middlewares
r.Use(telemetry.TelemetryMiddleware)
r.Use(SetResponseTypeToJSON)
r.Use(CorsMiddleware)
r.Use(AuthMiddleware)

r.Route("/", func(r chi.Router) {
r.Get("/{id}", telemetry.HandleFuncLogger(router.urlshort.Redirect))
Expand All @@ -48,38 +43,3 @@ func New(deps *deps.Deps, db mongo.Database) *Router {
urlshort: urlshort.NewHTTP(deps, &db),
}
}

func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With")

if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}

next.ServeHTTP(w, r)
})
}

func authMiddleware(next http.Handler) http.Handler {
godotenv.Load()

return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
next.ServeHTTP(w, r)
return
}

token := r.Header.Get("Authorization")
if token != os.Getenv("AUTH_TOKEN") {
log.Error(r.Context(), "Unauthorized. Please provide a valid auth token")
http.Error(w, "Unauthorized. Please provide a valid auth token", http.StatusUnauthorized)
return
}

next.ServeHTTP(w, r)
})
}
Loading