2023-03-08 01:32:18 -08:00
|
|
|
package user
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
2023-12-29 19:27:08 -08:00
|
|
|
"codeberg.org/pronounscc/pronouns.cc/backend/log"
|
2023-06-03 07:18:47 -07:00
|
|
|
"codeberg.org/pronounscc/pronouns.cc/backend/server"
|
2023-03-08 01:32:18 -08:00
|
|
|
"emperror.dev/errors"
|
|
|
|
"github.com/go-chi/render"
|
2023-12-29 19:27:08 -08:00
|
|
|
"github.com/jackc/pgx/v5"
|
2023-03-08 01:32:18 -08:00
|
|
|
)
|
|
|
|
|
|
|
|
func (s *Server) deleteUser(w http.ResponseWriter, r *http.Request) error {
|
|
|
|
ctx := r.Context()
|
|
|
|
claims, _ := server.ClaimsFromContext(ctx)
|
|
|
|
|
2023-03-30 07:58:35 -07:00
|
|
|
if claims.APIToken {
|
|
|
|
return server.APIError{Code: server.ErrMissingPermissions, Details: "This endpoint cannot be used by API tokens"}
|
2023-03-08 01:32:18 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
tx, err := s.DB.Begin(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "creating transaction")
|
|
|
|
}
|
2023-12-29 19:27:08 -08:00
|
|
|
defer func() {
|
|
|
|
err := tx.Rollback(ctx)
|
|
|
|
if err != nil && !errors.Is(err, pgx.ErrTxClosed) {
|
|
|
|
log.Error("rolling back transaction:", err)
|
|
|
|
}
|
|
|
|
}()
|
2023-03-08 01:32:18 -08:00
|
|
|
|
|
|
|
err = s.DB.DeleteUser(ctx, tx, claims.UserID, true, "")
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "setting user as deleted")
|
|
|
|
}
|
|
|
|
|
|
|
|
err = s.DB.InvalidateAllTokens(ctx, tx, claims.UserID)
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "invalidating tokens")
|
|
|
|
}
|
|
|
|
|
|
|
|
err = tx.Commit(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "committing transaction")
|
|
|
|
}
|
|
|
|
|
2023-03-30 07:05:40 -07:00
|
|
|
render.NoContent(w, r)
|
2023-03-08 01:32:18 -08:00
|
|
|
return nil
|
|
|
|
}
|