Initial commit

This commit is contained in:
kandrusyak
2023-06-23 02:18:00 +03:00
commit 688ae61bc6
12 changed files with 297 additions and 0 deletions

48
handler/auth.go Normal file
View File

@@ -0,0 +1,48 @@
package handler
import (
"astra-api-gateway/model"
"crypto/sha256"
"fmt"
"github.com/golang-jwt/jwt/v5"
"github.com/labstack/echo/v4"
"net/http"
"strconv"
"time"
)
func (h *Handler) Login(c echo.Context) (err error) {
// Bind
u := new(model.User)
if err = c.Bind(u); err != nil {
return
}
u.Password = fmt.Sprintf("%x", sha256.Sum256([]byte(u.Password)))
var t = h.DB.Where("user_name = ? AND password = ?", u.UserName, u.Password).First(&u)
if t.RowsAffected == 0 {
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(Key))
if err != nil {
return
}
c.SetCookie(&http.Cookie{
Name: "accessToken",
Value: _token,
HttpOnly: true,
Path: "/",
})
return c.JSON(http.StatusOK, u)
}

11
handler/handler.go Normal file
View File

@@ -0,0 +1,11 @@
package handler
import "gorm.io/gorm"
type Handler struct {
DB *gorm.DB
}
const (
Key = "secret"
)

14
handler/health.go Normal file
View File

@@ -0,0 +1,14 @@
package handler
import (
"github.com/labstack/echo/v4"
"net/http"
)
func (h *Handler) Health(c echo.Context) error {
type Resp struct {
Status string `json:"status"`
}
return c.JSON(http.StatusOK, Resp{Status: "OK"})
}