Initial commit
This commit is contained in:
48
handler/auth.go
Normal file
48
handler/auth.go
Normal 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
11
handler/handler.go
Normal 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
14
handler/health.go
Normal 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"})
|
||||
}
|
||||
Reference in New Issue
Block a user