pejhancctv/services/authentication.go

64 lines
1.2 KiB
Go

package services
import (
"app/utils"
"net/http"
"time"
"github.com/labstack/echo/v4"
)
func LoginByEmail(c echo.Context) error {
var info struct {
Email string `json:"email"`
Password string `json:"password"`
}
if err := c.Bind(&info); err != nil {
return err
}
if info.Email == "" || info.Password == "" {
return c.String(http.StatusUnauthorized, "pls check username and password")
}
user, err := utils.GetUserByEmail(info.Email)
if err != nil {
return err
}
checkpw, err := utils.Match(info.Password, info.Email)
if err != nil {
return err
}
if !checkpw {
return c.String(http.StatusUnauthorized, "pls check username and password")
} else {
err = utils.CheckToken(c)
if err == echo.ErrUnauthorized {
utils.GenerateToken(c, *user)
}
return c.JSON(http.StatusOK, map[string]string{
"message": "Login successful",
})
}
}
func Logout(c echo.Context) error {
coockie := new(http.Cookie)
coockie.Name = "authorization"
coockie.Value = ""
// coockie.HttpOnly = true
// coockie.Secure = true
coockie.Expires = time.Now().Add(time.Hour * 24)
c.SetCookie(coockie)
return c.JSON(http.StatusOK, map[string]string{
"message": "Logout successful",
})
}