| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 
 | package token
 import (
 "errors"
 "github.com/dgrijalva/jwt-go"
 "github.com/labstack/echo/v4"
 "github.com/memochou1993/prophecy/app/model"
 "github.com/memochou1993/prophecy/app/request"
 "github.com/memochou1993/prophecy/database"
 "gorm.io/gorm"
 "net/http"
 "os"
 "time"
 )
 
 
 type Claims struct {
 UserID uint
 jwt.StandardClaims
 }
 
 
 type Credentials struct {
 Email    string `json:"email" validate:"required,email"`
 Password string `json:"password" validate:"required"`
 }
 
 func Login(c echo.Context) error {
 
 credentials := new(Credentials)
 
 
 if err := c.Bind(credentials); err != nil {
 return echo.ErrInternalServerError
 }
 
 
 if err := c.Validate(credentials); err != nil {
 return c.JSON(http.StatusUnprocessableEntity, err.Error())
 }
 
 
 user := model.User{}
 
 
 result := database.DB().Where(&model.User{Email: credentials.Email}).First(&user)
 
 
 if errors.Is(result.Error, gorm.ErrRecordNotFound) {
 return echo.ErrUnauthorized
 }
 
 
 if user.Password != credentials.Password {
 return echo.ErrUnauthorized
 }
 
 
 claims := &Claims{
 user.ID,
 jwt.StandardClaims{
 ExpiresAt: time.Now().Add(time.Hour * 72).Unix(),
 },
 }
 
 
 token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(os.Getenv("APP_KEY")))
 
 if err != nil {
 return echo.ErrInternalServerError
 }
 
 return c.JSON(http.StatusOK, map[string]string{
 "token": token,
 })
 }
 
 |