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

View File

@ -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 !claims.TokenWrite || claims.APIToken {
return server.APIError{Code: server.ErrInvalidToken}
}
tx, err := s.DB.Begin(ctx)
if err != nil {
return server.APIError{Code: server.ErrBadRequest}
return errors.Wrap(err, "beginning transaction")
}
defer tx.Rollback(ctx)
t, err := s.DB.InvalidateToken(ctx, claims.UserID, tokenID)
err = s.DB.InvalidateAllTokens(ctx, tx, claims.UserID)
if err != nil {
if errors.Cause(err) == pgx.ErrNoRows {
return server.APIError{Code: server.ErrNotFound}
return errors.Wrap(err, "invalidating tokens")
}
return errors.Wrap(err, "invalidating token")
err = tx.Commit(ctx)
if err != nil {
return errors.Wrap(err, "committing transaction")
}
render.JSON(w, r, deleteTokenResponse{
TokenID: t.TokenID,
Invalidated: t.Invalidated,
Created: t.Created,
})
render.NoContent(w, r)
return nil
}