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

26
cmd/api/context.go Normal file
View File

@@ -0,0 +1,26 @@
package main
import (
"context"
"net/http"
"gitea.local.lab/Lbenedar/greenlight/internal/data"
)
type contextKey string
const userContextKey = contextKey("user")
func (app *application) contextSetUser(r *http.Request, user *data.User) *http.Request {
ctx := context.WithValue(r.Context(), userContextKey, user)
return r.WithContext(ctx)
}
func (app *application) contextGetUser(r *http.Request) *data.User {
user, ok := r.Context().Value(userContextKey).(*data.User)
if !ok {
panic("missing user value in request context")
}
return user
}

View File

@@ -61,3 +61,10 @@ func (app *application) invalidCredentialsResponse(w http.ResponseWriter, r *htt
message := "invalid authentication credentials"
app.errorResponse(w, r, http.StatusUnauthorized, message)
}
func (app *application) invalidAuthenticationTokenResponse(w http.ResponseWriter, r *http.Request) {
w.Header().Set("WWW-Authenticate", "Bearer")
message := "invalid or missing authentication token"
app.errorResponse(w, r, http.StatusUnauthorized, message)
}

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)
})
}

View File

@@ -25,5 +25,5 @@ func (app *application) routes() http.Handler {
router.HandlerFunc(http.MethodPost, "/v1/tokens/authentication", app.createAuthenticationTokenHandler)
return app.recoverPanic(app.rateLimit(router))
return app.recoverPanic(app.rateLimit(app.authenticate(router)))
}

View File

@@ -15,6 +15,8 @@ var (
ErrDuplicateEmail = errors.New("duplicate email")
)
var AnonymousUser = &User{}
type User struct {
ID int64 `json:"id"`
CreatedAt time.Time `json:"created_at"`
@@ -25,6 +27,10 @@ type User struct {
Version int `json:"-"`
}
func (u *User) IsAnonymous() bool {
return u == AnonymousUser
}
type password struct {
plaintext *string
hash []byte