account.go
·
54 строки
·
1.5 KB
| 1 | package handlers |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "strings" |
| 7 | |
| 8 | "polar/internal/user" |
| 9 | "polar/internal/web/middleware" |
| 10 | |
| 11 | "github.com/gofiber/fiber/v2" |
| 12 | ) |
| 13 | |
| 14 | func (h *Handler) deleteAccount(ctx context.Context, account *user.User) error { |
| 15 | if account == nil { |
| 16 | return user.ErrUserNotFound |
| 17 | } |
| 18 | if err := h.repoSvc.DeleteAllByOwner(ctx, account); err != nil { |
| 19 | return err |
| 20 | } |
| 21 | return h.userSvc.Delete(ctx, account.ID) |
| 22 | } |
| 23 | |
| 24 | func (h *Handler) DeleteAccountSubmit(c *fiber.Ctx) error { |
| 25 | current := middleware.CurrentUser(c) |
| 26 | if current == nil { |
| 27 | return c.Redirect("/login", fiber.StatusSeeOther) |
| 28 | } |
| 29 | |
| 30 | confirm := strings.TrimSpace(c.FormValue("confirm_username")) |
| 31 | password := c.FormValue("password") |
| 32 | if !strings.EqualFold(confirm, current.Username) { |
| 33 | h.setFlashT(c, "settings.delete_mismatch") |
| 34 | return c.Redirect("/settings#danger", fiber.StatusSeeOther) |
| 35 | } |
| 36 | if _, err := h.userSvc.Authenticate(c.UserContext(), current.Username, password); err != nil { |
| 37 | h.setFlashT(c, "auth.invalid_creds") |
| 38 | return c.Redirect("/settings#danger", fiber.StatusSeeOther) |
| 39 | } |
| 40 | |
| 41 | if err := h.deleteAccount(c.UserContext(), current); err != nil { |
| 42 | h.logger.Error("delete account failed", "user_id", current.ID, "err", err) |
| 43 | if errors.Is(err, user.ErrLastAdmin) { |
| 44 | h.setFlashT(c, "settings.delete_last_admin") |
| 45 | } else { |
| 46 | h.setFlashT(c, "flash.account_delete_failed") |
| 47 | } |
| 48 | return c.Redirect("/settings#danger", fiber.StatusSeeOther) |
| 49 | } |
| 50 | |
| 51 | c.ClearCookie(middleware.SessionCookieName) |
| 52 | h.setFlashT(c, "flash.account_deleted") |
| 53 | return c.Redirect("/", fiber.StatusSeeOther) |
| 54 | } |
| 55 |