112 lines
2.1 KiB
Go
112 lines
2.1 KiB
Go
package users
|
|
|
|
import (
|
|
"astra-api-gateway/config"
|
|
"astra-api-gateway/model"
|
|
"astra-api-gateway/pkg/api"
|
|
"encoding/json"
|
|
"github.com/golang-jwt/jwt/v5"
|
|
"github.com/labstack/echo/v4"
|
|
"net/http"
|
|
"strconv"
|
|
"time"
|
|
)
|
|
|
|
func Login(c echo.Context) (err error) {
|
|
// Bind
|
|
u := new(model.User)
|
|
if err = c.Bind(u); err != nil {
|
|
return
|
|
}
|
|
|
|
data, err := api.PostRequest(config.Env.MSHosts.UsersHost+"/login", u, c.Request().Header)
|
|
|
|
u.Password = ""
|
|
|
|
if err != nil {
|
|
return c.NoContent(http.StatusBadGateway)
|
|
}
|
|
|
|
err = json.Unmarshal(data, &u)
|
|
|
|
if err != nil {
|
|
return c.NoContent(http.StatusUnauthorized)
|
|
}
|
|
|
|
token := jwt.New(jwt.SigningMethodHS256)
|
|
|
|
claims := token.Claims.(jwt.MapClaims)
|
|
claims["id"] = strconv.Itoa(int(u.ID))
|
|
claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
|
|
|
|
var _token, _ = token.SignedString([]byte(config.Env.Server.JWTSecret))
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
c.SetCookie(&http.Cookie{
|
|
Name: "accessToken",
|
|
Value: _token,
|
|
HttpOnly: true,
|
|
Path: "/",
|
|
})
|
|
|
|
return c.JSON(http.StatusOK, u)
|
|
}
|
|
|
|
func GetCurrentUser(c echo.Context) error {
|
|
data, err := api.GetRequest(config.Env.MSHosts.UsersHost+"/me", c.Request().Header)
|
|
|
|
if err != nil {
|
|
return c.NoContent(http.StatusBadGateway)
|
|
}
|
|
|
|
return c.JSONBlob(http.StatusOK, data)
|
|
}
|
|
|
|
func GetUsers(c echo.Context) error {
|
|
id := c.Param("id")
|
|
|
|
data, err := api.GetRequest(
|
|
config.Env.MSHosts.UsersHost+"/"+id,
|
|
c.Request().Header, c.Request().URL.RawQuery)
|
|
|
|
if err != nil {
|
|
return c.NoContent(http.StatusBadGateway)
|
|
}
|
|
|
|
return c.JSONBlob(http.StatusOK, data)
|
|
}
|
|
|
|
func DeleteUser(c echo.Context) error {
|
|
id := c.Param("id")
|
|
|
|
data, err := api.DeleteRequest(
|
|
config.Env.MSHosts.UsersHost+"/"+id,
|
|
c.Request().Header)
|
|
|
|
if err != nil {
|
|
return c.NoContent(http.StatusBadGateway)
|
|
}
|
|
|
|
return c.JSONBlob(http.StatusOK, data)
|
|
}
|
|
|
|
func UpdateUser(c echo.Context) (err error) {
|
|
id := c.Param("id")
|
|
|
|
// Bind
|
|
u := new(model.User)
|
|
if err = c.Bind(u); err != nil {
|
|
return
|
|
}
|
|
|
|
data, err := api.PatchRequest(config.Env.MSHosts.UsersHost+"/"+id, u, c.Request().Header)
|
|
|
|
if err != nil {
|
|
return c.NoContent(http.StatusBadGateway)
|
|
}
|
|
|
|
return c.JSONBlob(http.StatusOK, data)
|
|
}
|