From abc78f3a9a73e6f605139ce6d8c2136a233cd545 Mon Sep 17 00:00:00 2001 From: Sam Date: Thu, 30 Mar 2023 16:05:10 +0200 Subject: [PATCH] feat(backend): change DELETE /auth/tokens to invalidate *all* tokens --- backend/routes/auth/routes.go | 2 +- backend/routes/auth/tokens.go | 36 +++++++++++++++-------------------- 2 files changed, 16 insertions(+), 22 deletions(-) diff --git a/backend/routes/auth/routes.go b/backend/routes/auth/routes.go index 923f57a..1283472 100644 --- a/backend/routes/auth/routes.go +++ b/backend/routes/auth/routes.go @@ -104,7 +104,7 @@ func Mount(srv *server.Server, r chi.Router) { // tokens r.With(server.MustAuth).Get("/tokens", server.WrapHandler(s.getTokens)) r.With(server.MustAuth).Post("/tokens", server.WrapHandler(s.createToken)) - r.With(server.MustAuth).Delete("/tokens/{id}", server.WrapHandler(s.deleteToken)) + r.With(server.MustAuth).Delete("/tokens", server.WrapHandler(s.deleteToken)) // cancel user delete // uses a special token, so handled in the function itself diff --git a/backend/routes/auth/tokens.go b/backend/routes/auth/tokens.go index d490e34..4705abc 100644 --- a/backend/routes/auth/tokens.go +++ b/backend/routes/auth/tokens.go @@ -7,9 +7,7 @@ import ( "codeberg.org/u1f320/pronouns.cc/backend/db" "codeberg.org/u1f320/pronouns.cc/backend/server" "emperror.dev/errors" - "github.com/go-chi/chi/v5" "github.com/go-chi/render" - "github.com/jackc/pgx/v4" "github.com/rs/xid" ) @@ -45,35 +43,31 @@ func (s *Server) getTokens(w http.ResponseWriter, r *http.Request) error { return nil } -type deleteTokenResponse struct { - TokenID xid.ID `json:"id"` - Invalidated bool `json:"invalidated"` - Created time.Time `json:"time"` -} - func (s *Server) deleteToken(w http.ResponseWriter, r *http.Request) error { ctx := r.Context() claims, _ := server.ClaimsFromContext(ctx) - tokenID, err := xid.FromString(chi.URLParam(r, "id")) - if err != nil { - return server.APIError{Code: server.ErrBadRequest} + if !claims.TokenWrite || claims.APIToken { + return server.APIError{Code: server.ErrInvalidToken} } - t, err := s.DB.InvalidateToken(ctx, claims.UserID, tokenID) + tx, err := s.DB.Begin(ctx) if err != nil { - if errors.Cause(err) == pgx.ErrNoRows { - return server.APIError{Code: server.ErrNotFound} - } + return errors.Wrap(err, "beginning transaction") + } + defer tx.Rollback(ctx) - return errors.Wrap(err, "invalidating token") + err = s.DB.InvalidateAllTokens(ctx, tx, claims.UserID) + if err != nil { + return errors.Wrap(err, "invalidating tokens") } - render.JSON(w, r, deleteTokenResponse{ - TokenID: t.TokenID, - Invalidated: t.Invalidated, - Created: t.Created, - }) + err = tx.Commit(ctx) + if err != nil { + return errors.Wrap(err, "committing transaction") + } + + render.NoContent(w, r) return nil }