Implementing Middleware for adding query params and groupID to context

Signed-off-by: Ethan Wellenreiter <ewellenreiter@gmail.com>
This commit is contained in:
Ethan Wellenreiter 2025-06-23 13:09:06 -04:00
parent 18330e745f
commit b687b43b35

View File

@ -7,7 +7,8 @@ import (
"net/http"
"strconv"
auth_storage "git.ewellenr.ca/receipt_indexer/backend/internal/storage/auth"
// auth_storage "git.ewellenr.ca/receipt_indexer/backend/internal/storage/auth"
l_context "git.ewellenr.ca/receipt_indexer/backend/internal/context"
"github.com/go-chi/chi/v5"
)
@ -27,7 +28,7 @@ func (app *application) AuthSessionMiddleware(next http.Handler) http.Handler {
return
}
valid, userID, err := app.auth.Sessions.CheckSession(r.Context(), token) // should have a different function for this
valid, userID, err := app.store.Sessions.CheckSession(r.Context(), token) // should have a different function for this
if !valid {
app.unauthorizedErrorResponse(w, r, fmt.Errorf("Invalid session token"))
return
@ -131,7 +132,7 @@ func (app *application) RateLimiterMiddleware(next http.Handler) http.Handler {
})
}
func (app *application) receiptsContextMiddleware(next http.Handler) http.Handler {
func (app *application) receiptContextMiddleware(next http.Handler) http.Handler {
// add the receipt id to the context? or the receipt class to the context
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@ -163,7 +164,7 @@ func (app *application) receiptsContextMiddleware(next http.Handler) http.Handle
}
func (app *application) checkRolePrecedence(ctx context.Context, user *auth_storage.User, roleName string) (bool, error) {
role, err := app.auth.Roles.GetByName(ctx, roleName)
role, err := app.store.Roles.GetByName(ctx, roleName)
if err != nil {
return false, err
}
@ -195,3 +196,36 @@ func (app *application) checkReceiptOwnership(requiredRole string, next http.Han
next.ServeHTTP(w, r)
})
}
func (app *application) addGroupToContextMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
urlGroupID, err := strconv.ParseInt(chi.URLParam(r, "groupID"), 10, 64)
if err != nil {
app.badRequestResponse(w, r, fmt.Errorf("Invalid url group ID - Not an integer"))
return
}
ctx := r.Context()
group, err := app.getGroup(ctx, urlGroupID)
if err != nil {
app.unauthorizedErrorResponse(w, r, err)
return
}
ctx = context.WithValue(ctx, groupCtx, group)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func (app *application) addQueryParamsToContextMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// need to select the user from the token validation stuff
ctx := r.Context()
ctx = context.WithValue(ctx, l_context.QueryParamsCtx, r.URL.Query())
// make sure to add user and role into the context here
next.ServeHTTP(w, r.WithContext(ctx))
})
}