2024-05-12 10:45:16 -07:00
|
|
|
package handlers
|
|
|
|
|
|
|
|
import (
|
2024-05-18 22:38:12 -07:00
|
|
|
"errors"
|
2024-05-12 10:45:16 -07:00
|
|
|
"net/http"
|
2024-05-18 22:38:12 -07:00
|
|
|
"time"
|
2024-05-12 10:45:16 -07:00
|
|
|
|
2024-05-18 22:38:12 -07:00
|
|
|
"git.jamestombleson.com/jtom38/newsbot-portal/internal/domain"
|
|
|
|
"github.com/golang-jwt/jwt/v4"
|
2024-05-12 10:45:16 -07:00
|
|
|
"github.com/labstack/echo/v4"
|
|
|
|
)
|
|
|
|
|
2024-05-18 22:38:12 -07:00
|
|
|
func SetCookie(c echo.Context, key, value, path string) {
|
2024-05-12 10:45:16 -07:00
|
|
|
cookie := new(http.Cookie)
|
|
|
|
cookie.Name = key
|
|
|
|
cookie.Value = value
|
2024-05-18 22:38:12 -07:00
|
|
|
if path != "" {
|
|
|
|
cookie.Path = path
|
|
|
|
}
|
2024-05-12 10:45:16 -07:00
|
|
|
c.SetCookie(cookie)
|
|
|
|
}
|
2024-05-18 22:38:12 -07:00
|
|
|
|
|
|
|
type jwtToken struct {
|
|
|
|
Exp time.Time `json:"exp"`
|
|
|
|
Iss string `json:"iss"`
|
|
|
|
Authorized bool `json:"authorized"`
|
|
|
|
UserName string `json:"username"`
|
|
|
|
Scopes []string `json:"scopes"`
|
|
|
|
jwt.RegisteredClaims
|
|
|
|
}
|
|
|
|
|
|
|
|
func ValidateJwt(ctx echo.Context, sharedSecret, issuer string) (jwtToken, error) {
|
|
|
|
cookie, err := ctx.Cookie(domain.CookieToken)
|
|
|
|
if err != nil {
|
|
|
|
return jwtToken{}, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if cookie.Value == "" {
|
|
|
|
return jwtToken{}, errors.New("JWT Bearer Token is missing")
|
|
|
|
}
|
|
|
|
|
|
|
|
token, err := jwt.ParseWithClaims(cookie.Value, &jwtToken{}, func(token *jwt.Token) (interface{}, error) {
|
|
|
|
return []byte(sharedSecret), nil
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return jwtToken{}, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if !token.Valid {
|
|
|
|
return jwtToken{}, errors.New("invalid jwt token")
|
|
|
|
}
|
|
|
|
|
|
|
|
claims := token.Claims.(*jwtToken)
|
|
|
|
if !claims.Exp.After(time.Now()) {
|
|
|
|
return jwtToken{}, errors.New("the jwt token has expired")
|
|
|
|
}
|
|
|
|
//if claims.Iss != issuer {
|
|
|
|
// return jwtToken{}, errors.New("the issuer was invalid")
|
|
|
|
//}
|
|
|
|
|
|
|
|
return *claims, nil
|
|
|
|
}
|