This commit is contained in:
lbenedar
2026-03-20 18:07:41 +03:00
parent efb58d7c15
commit 891b63f259
5 changed files with 88 additions and 1 deletions

View File

@@ -1,12 +1,16 @@
package main
import (
"errors"
"fmt"
"net"
"net/http"
"strings"
"sync"
"time"
"gitea.local.lab/Lbenedar/greenlight/internal/data"
"gitea.local.lab/Lbenedar/greenlight/internal/validator"
"golang.org/x/time/rate"
)
@@ -75,3 +79,47 @@ func (app *application) rateLimit(next http.Handler) http.Handler {
next.ServeHTTP(w, r)
})
}
func (app *application) authenticate(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Vary", "Authorization")
authorizationHeader := r.Header.Get("Authorization")
if authorizationHeader == "" {
r = app.contextSetUser(r, data.AnonymousUser)
next.ServeHTTP(w, r)
return
}
headerParts := strings.Split(authorizationHeader, " ")
if len(headerParts) != 2 || headerParts[0] != "Bearer" {
app.invalidCredentialsResponse(w, r)
return
}
token := headerParts[1]
v := validator.New()
if data.ValidateTokenPlaintext(v, token); !v.Valid() {
app.invalidCredentialsResponse(w, r)
return
}
user, err := app.models.Users.GetForToken(data.ScopeAuthentication, token)
if err != nil {
switch {
case errors.Is(err, data.ErrRecordNotFound):
app.invalidAuthenticationTokenResponse(w, r)
default:
app.serverErrorResponse(w, r, err)
}
return
}
r = app.contextSetUser(r, user)
next.ServeHTTP(w, r)
})
}