49 lines
946 B
Go
49 lines
946 B
Go
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)
|
|
}
|