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
Signed by: sam
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 {
return server.APIError{Code: server.ErrInvalidToken}
}
tx, err := s.DB.Begin(ctx)
if err != nil { 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 err != nil {
if errors.Cause(err) == pgx.ErrNoRows { return errors.Wrap(err, "invalidating tokens")
return server.APIError{Code: server.ErrNotFound}
} }
return errors.Wrap(err, "invalidating token") err = tx.Commit(ctx)
if err != nil {
return errors.Wrap(err, "committing transaction")
} }
render.JSON(w, r, deleteTokenResponse{ render.NoContent(w, r)
TokenID: t.TokenID,
Invalidated: t.Invalidated,
Created: t.Created,
})
return nil return nil
} }