feat(backend): change DELETE /auth/tokens to invalidate *all* tokens

This commit is contained in:
Sam 2023-03-30 16:05:10 +02:00
parent 92243d58ac
commit abc78f3a9a
No known key found for this signature in database
GPG Key ID: B4EF20DDE721CAA1
2 changed files with 16 additions and 22 deletions

View File

@ -104,7 +104,7 @@ func Mount(srv *server.Server, r chi.Router) {
// tokens // tokens
r.With(server.MustAuth).Get("/tokens", server.WrapHandler(s.getTokens)) r.With(server.MustAuth).Get("/tokens", server.WrapHandler(s.getTokens))
r.With(server.MustAuth).Post("/tokens", server.WrapHandler(s.createToken)) 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 // cancel user delete
// uses a special token, so handled in the function itself // uses a special token, so handled in the function itself

View File

@ -7,9 +7,7 @@ import (
"codeberg.org/u1f320/pronouns.cc/backend/db" "codeberg.org/u1f320/pronouns.cc/backend/db"
"codeberg.org/u1f320/pronouns.cc/backend/server" "codeberg.org/u1f320/pronouns.cc/backend/server"
"emperror.dev/errors" "emperror.dev/errors"
"github.com/go-chi/chi/v5"
"github.com/go-chi/render" "github.com/go-chi/render"
"github.com/jackc/pgx/v4"
"github.com/rs/xid" "github.com/rs/xid"
) )
@ -45,35 +43,31 @@ func (s *Server) getTokens(w http.ResponseWriter, r *http.Request) error {
return nil 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 { func (s *Server) deleteToken(w http.ResponseWriter, r *http.Request) error {
ctx := r.Context() ctx := r.Context()
claims, _ := server.ClaimsFromContext(ctx) claims, _ := server.ClaimsFromContext(ctx)
tokenID, err := xid.FromString(chi.URLParam(r, "id")) if !claims.TokenWrite || claims.APIToken {
if err != nil { return server.APIError{Code: server.ErrInvalidToken}
return server.APIError{Code: server.ErrBadRequest}
} }
t, err := s.DB.InvalidateToken(ctx, claims.UserID, tokenID) tx, err := s.DB.Begin(ctx)
if err != nil { if err != nil {
if errors.Cause(err) == pgx.ErrNoRows { return errors.Wrap(err, "beginning transaction")
return server.APIError{Code: server.ErrNotFound} }
} 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{ err = tx.Commit(ctx)
TokenID: t.TokenID, if err != nil {
Invalidated: t.Invalidated, return errors.Wrap(err, "committing transaction")
Created: t.Created, }
})
render.NoContent(w, r)
return nil return nil
} }