UpdateOwnAccountRouteHandler

mail@pastecode.io avatar
unknown
golang
2 months ago
2.1 kB
11
Indexable
Never
func (h *UserHandler) updateUsersOwnAccount(c *fiber.Ctx) error {

        customContext, cancel := context.WithCancel(c.Context())
        defer cancel()

        user := c.Locals("user").(*common.User)
        studentId := c.Locals("studentId").(string)

        u := &common.UserUpdate{}

        if err := c.BodyParser(u); err != nil {
                return c.Status(fiber.StatusBadRequest).JSON(&fiber.Map{
                        "status":  "fail",
                        "message": err.Error(),
                })
        }

        if u.Username != "" {
                user.Username = u.Username
        }

        if u.Password != "" {

                hash, err := tools.HashPassword(u.Password)
                if err != nil {
                        return c.Status(500).JSON(fiber.Map{"status": "error", "message": "Couldn't hash password", "data": err})
                }

                user.Password = hash
        }

        err := h.userService.UpdateUser(customContext, int(user.ID), user)

        if err != nil {
                return c.Status(fiber.StatusInternalServerError).JSON(&fiber.Map{
                        "status":  "fail",
                        "message": err.Error(),
                })
        }

        c.Cookie(&fiber.Cookie{
                Name:     "jwt",
                Value:    "loggedOut",
                Path:     "/",
                Expires:  time.Now().Add(time.Second * 10),
                Secure:   false,
                HTTPOnly: true,
        })

        err = h.commonService.MarkTaskDone(customContext, studentId, 5)

        if err != nil {
                return c.Status(fiber.StatusInternalServerError).JSON(&fiber.Map{
                        "status":  "Virhe pisteiden asettamisessa",
                        "message": err.Error(),
                })
        }

        return c.Status(fiber.StatusOK).JSON(&fiber.Map{
                "status":  "success",
                "message": "Käyttäjätilin tiedot päivitetty onnistuneesti. Kirjaudu sisään uudelleen.",
        })
}
Leave a Comment