Basic JWT is now working #12

Merged
jtom38 merged 12 commits from features/jwt/maybe into main 2024-03-29 14:51:01 -07:00
2 changed files with 44 additions and 6 deletions
Showing only changes of commit 565e6112a8 - Show all commits

View File

@ -1,6 +1,7 @@
package v1 package v1
import ( import (
"errors"
"go-cook/api/models" "go-cook/api/models"
"go-cook/api/repositories" "go-cook/api/repositories"
"net/http" "net/http"
@ -10,6 +11,12 @@ import (
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
) )
const (
ErrJwtMissing = "auth token is missing"
ErrJwtClaimsMissing = "claims missing on token"
ErrJwtExpired = "auth token has expired"
)
type JwtToken struct { type JwtToken struct {
Exp time.Time `json:"exp"` Exp time.Time `json:"exp"`
Authorized bool `json:"authorized"` Authorized bool `json:"authorized"`
@ -97,3 +104,25 @@ func (h *Handler) AuthLogin(c echo.Context) error {
func (h *Handler) RefreshJwtToken(c echo.Context) error { func (h *Handler) RefreshJwtToken(c echo.Context) error {
return nil 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 ( import (
"fmt" "fmt"
"go-cook/api/models"
"net/http" "net/http"
"github.com/labstack/echo/v4" "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 { 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)
} }