ch16.3
This commit is contained in:
@@ -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)
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user