The jwt token is now checked to see if it expires and will return an error

This commit is contained in:
James Tombleson 2024-03-29 14:49:57 -07:00
parent faf0bec069
commit 565e6112a8
2 changed files with 44 additions and 6 deletions

View File

@ -1,6 +1,7 @@
package v1
import (
"errors"
"go-cook/api/models"
"go-cook/api/repositories"
"net/http"
@ -10,6 +11,12 @@ import (
"github.com/labstack/echo/v4"
)
const (
ErrJwtMissing = "auth token is missing"
ErrJwtClaimsMissing = "claims missing on token"
ErrJwtExpired = "auth token has expired"
)
type JwtToken struct {
Exp time.Time `json:"exp"`
Authorized bool `json:"authorized"`
@ -45,8 +52,8 @@ func (h *Handler) AuthRegister(c echo.Context) error {
if err.Error() != repositories.ErrUserNotFound {
return c.JSON(http.StatusInternalServerError, models.ErrorResponse{
HttpCode: http.StatusInternalServerError,
Message: err.Error(),
})
Message: err.Error(),
})
}
}
@ -55,7 +62,7 @@ func (h *Handler) AuthRegister(c echo.Context) error {
if err != nil {
return c.JSON(http.StatusInternalServerError, models.ErrorResponse{
HttpCode: http.StatusInternalServerError,
Message: err.Error(),
Message: err.Error(),
})
}
@ -63,7 +70,7 @@ func (h *Handler) AuthRegister(c echo.Context) error {
if err != nil {
return c.JSON(http.StatusInternalServerError, models.ErrorResponse{
HttpCode: http.StatusInternalServerError,
Message: err.Error(),
Message: err.Error(),
})
}
@ -73,7 +80,7 @@ func (h *Handler) AuthRegister(c echo.Context) error {
func (h *Handler) AuthLogin(c echo.Context) error {
username := c.QueryParam("username")
password := c.QueryParam("password")
// check if the user exists
err := h.UserService.DoesUserExist(username)
if err != nil {
@ -97,3 +104,25 @@ func (h *Handler) AuthLogin(c echo.Context) error {
func (h *Handler) RefreshJwtToken(c echo.Context) error {
return nil
}
func (h *Handler) getJwtToken(c echo.Context) (JwtToken, error) {
// Make sure that the request came with a jwtToken
token, ok := c.Get("user").(*jwt.Token)
if !ok {
return JwtToken{}, errors.New(ErrJwtMissing)
}
// Generate the claims from the token
claims, ok := token.Claims.(*JwtToken)
if !ok {
return JwtToken{}, errors.New(ErrJwtClaimsMissing)
}
// Check to see if the token has expired
hasExpired := claims.Exp.Compare(time.Now())
if hasExpired == -1 {
return JwtToken{}, errors.New(ErrJwtExpired)
}
return *claims, nil
}

View File

@ -2,6 +2,7 @@ package v1
import (
"fmt"
"go-cook/api/models"
"net/http"
"github.com/labstack/echo/v4"
@ -49,5 +50,13 @@ func (h *Handler) HelloBody(c echo.Context) error {
}
func (h *Handler) ProtectedRoute(c echo.Context) error {
return c.JSON(http.StatusOK, "You have a good bearer token!")
token, err := h.getJwtToken(c)
if err != nil {
return c.JSON(http.StatusForbidden, models.ErrorResponse{
HttpCode: http.StatusForbidden,
Message: err.Error(),
})
}
return c.JSON(http.StatusOK, token)
}