115 lines
2.2 KiB
Go
115 lines
2.2 KiB
Go
package handler
|
|
|
|
import (
|
|
"astra-users/model"
|
|
"astra-users/pkg/utils"
|
|
"crypto/sha256"
|
|
"fmt"
|
|
"github.com/labstack/echo/v4"
|
|
"net/http"
|
|
)
|
|
|
|
func (h *Handler) GetCurrentUser(c echo.Context) error {
|
|
userId := c.Request().Header.Get("UserId")
|
|
|
|
if userId == "" {
|
|
return c.NoContent(http.StatusBadRequest)
|
|
}
|
|
|
|
u := new(model.User)
|
|
|
|
tx := h.DB.First(&u, userId)
|
|
|
|
if tx.RowsAffected == 0 {
|
|
return c.NoContent(http.StatusNotFound)
|
|
}
|
|
|
|
u.Password = ""
|
|
|
|
return c.JSON(http.StatusOK, &u)
|
|
}
|
|
|
|
func (h *Handler) GetUsers(c echo.Context) error {
|
|
var users []model.User
|
|
|
|
query := c.Request().URL.Query()
|
|
limit, offset := utils.GetPaginationParams(query)
|
|
sortCol, isDesc, filterCol, filterVal := utils.GetFilterParams(query)
|
|
|
|
tx := h.DB.Limit(limit).Offset(offset)
|
|
|
|
utils.ApplyIdFilter(c, tx)
|
|
utils.ApplySort(tx, sortCol, isDesc)
|
|
utils.ApplyFilters(tx, filterCol, filterVal)
|
|
|
|
tx = tx.Find(&users)
|
|
|
|
if tx.RowsAffected == 1 {
|
|
return c.JSON(http.StatusOK, users[0])
|
|
}
|
|
|
|
return c.JSON(http.StatusOK, users)
|
|
}
|
|
|
|
func (h *Handler) UpdateUser(c echo.Context) (err error) {
|
|
var user = new(model.User)
|
|
var apiUser = new(model.APIUser)
|
|
tx := h.DB
|
|
|
|
id := c.Param("id")
|
|
tx = tx.Find(&user, id)
|
|
|
|
if tx.RowsAffected == 0 {
|
|
return c.NoContent(http.StatusNotFound)
|
|
}
|
|
|
|
if err = c.Bind(apiUser); err != nil {
|
|
return c.NoContent(http.StatusBadRequest)
|
|
}
|
|
|
|
user.FirstName = apiUser.FirstName
|
|
user.LastName = apiUser.LastName
|
|
|
|
tx = h.DB.Save(&user)
|
|
|
|
if tx.RowsAffected == 0 {
|
|
return c.NoContent(http.StatusBadGateway)
|
|
}
|
|
|
|
user.Password = ""
|
|
|
|
return c.JSON(http.StatusOK, &user)
|
|
}
|
|
|
|
func (h *Handler) DeleteUser(c echo.Context) (err error) {
|
|
id := c.Param("id")
|
|
|
|
tx := h.DB.Delete(&model.User{}, id)
|
|
|
|
if tx.RowsAffected == 0 {
|
|
return c.NoContent(http.StatusBadGateway)
|
|
}
|
|
|
|
return c.NoContent(http.StatusOK)
|
|
}
|
|
|
|
func (h *Handler) CreateUser(c echo.Context) (err error) {
|
|
var user = new(model.User)
|
|
|
|
if err = c.Bind(user); err != nil {
|
|
return c.NoContent(http.StatusBadRequest)
|
|
}
|
|
|
|
user.Password = fmt.Sprintf("%x", sha256.Sum256([]byte(user.Password)))
|
|
|
|
tx := h.DB.Omit("ID", "CreatedAt", "UpdatedAt", "DeletedAt").Create(user)
|
|
|
|
if tx.RowsAffected == 0 {
|
|
return c.NoContent(http.StatusBadGateway)
|
|
}
|
|
|
|
user.Password = ""
|
|
|
|
return c.JSON(http.StatusCreated, user)
|
|
}
|