From 4275a3acad502a099252317ccf418b5e4861ffc2 Mon Sep 17 00:00:00 2001 From: konrad Date: Tue, 23 Jan 2018 15:25:41 +0100 Subject: [PATCH] Added method to delete a user --- models/user_delete.go | 20 +++++++++++++++ routes/api/v1/user_delete.go | 47 ++++++++++++++++++++++++++++++++++++ routes/routes.go | 1 + 3 files changed, 68 insertions(+) create mode 100644 models/user_delete.go create mode 100644 routes/api/v1/user_delete.go diff --git a/models/user_delete.go b/models/user_delete.go new file mode 100644 index 0000000..8eb357d --- /dev/null +++ b/models/user_delete.go @@ -0,0 +1,20 @@ +package models + +import "fmt" + +// DeleteUserByID deletes a user by its ID +func DeleteUserByID(id int64) error { + // Check if the id is 0 + if id == 0 { + return fmt.Errorf("ID cannot be 0") + } + + // Delete the user + _, err := x.Id(id).Delete(&User{}) + + if err != nil { + return err + } + + return err +} diff --git a/routes/api/v1/user_delete.go b/routes/api/v1/user_delete.go new file mode 100644 index 0000000..c184222 --- /dev/null +++ b/routes/api/v1/user_delete.go @@ -0,0 +1,47 @@ +package v1 + +import ( + "git.mowie.cc/konrad/Library/models" + "github.com/labstack/echo" + "net/http" + "strconv" +) + +// UserDelete is the handler to delete a user +func UserDelete(c echo.Context) error { + + id := c.Param("id") + + // Make int + userID, err := strconv.ParseInt(id, 10, 64) + + if err != nil { + return c.JSON(http.StatusBadRequest, models.Message{"User ID is invalid."}) + } + + // Check if the user exists + _, exists, err := models.GetUserByID(userID) + + if err != nil { + return c.JSON(http.StatusInternalServerError, models.Message{"Could not get user."}) + } + + if !exists { + return c.JSON(http.StatusNotFound, models.Message{"The user does not exist."}) + } + + // Delete it + err = models.DeleteUserByID(userID) + + if err != nil { + return c.JSON(http.StatusInternalServerError, models.Message{"Could not delete user."}) + } + + // Log the action + err = models.LogAction("Deleted a user", userID, c) + if err != nil { + return c.JSON(http.StatusInternalServerError, models.Message{"Could not log."}) + } + + return c.JSON(http.StatusOK, models.Message{"success"}) +} diff --git a/routes/routes.go b/routes/routes.go index b8c466f..e7d8a04 100644 --- a/routes/routes.go +++ b/routes/routes.go @@ -112,6 +112,7 @@ func RegisterRoutes(e *echo.Echo) { a.PUT("/users", apiv1.UserAddOrUpdate) a.POST("/users/:id", apiv1.UserAddOrUpdate) a.GET("/users/:id", apiv1.UserShow) + a.DELETE("/users/:id", apiv1.UserDelete) // Manage Users