portal/account/jwt.go

172 lines
4.0 KiB
Go
Raw Normal View History

package account
import (
"crypto/ed25519"
2024-02-14 03:17:34 +00:00
"errors"
"fmt"
2024-03-17 12:15:27 +00:00
"net/http"
2024-02-14 03:17:34 +00:00
"strconv"
"time"
2024-02-18 01:07:43 +00:00
2024-03-18 21:02:16 +00:00
"github.com/samber/lo"
2024-03-17 13:09:29 +00:00
"go.sia.tech/jape"
"git.lumeweb.com/LumeWeb/portal/api/router"
apiRegistry "git.lumeweb.com/LumeWeb/portal/api/registry"
2024-02-18 01:07:43 +00:00
"github.com/golang-jwt/jwt/v5"
)
const AUTH_COOKIE_NAME = "auth_token"
2024-02-14 01:58:17 +00:00
type JWTPurpose string
2024-02-18 01:11:43 +00:00
type VerifyTokenFunc func(claim *jwt.RegisteredClaims) error
2024-02-14 03:17:34 +00:00
var (
2024-02-18 01:11:43 +00:00
nopVerifyFunc VerifyTokenFunc = func(claim *jwt.RegisteredClaims) error {
2024-02-14 03:17:34 +00:00
return nil
}
ErrJWTUnexpectedClaimsType = errors.New("unexpected claims type")
ErrJWTUnexpectedIssuer = errors.New("unexpected issuer")
ErrJWTInvalid = errors.New("invalid JWT")
)
2024-02-14 01:58:17 +00:00
const (
JWTPurposeLogin JWTPurpose = "login"
2024-02-14 03:17:34 +00:00
JWTPurpose2FA JWTPurpose = "2fa"
2024-03-13 22:44:09 +00:00
JWTPurposeNone JWTPurpose = ""
2024-02-14 01:58:17 +00:00
)
2024-02-14 03:31:44 +00:00
func JWTGenerateToken(domain string, privateKey ed25519.PrivateKey, userID uint, purpose JWTPurpose) (string, error) {
return JWTGenerateTokenWithDuration(domain, privateKey, userID, time.Hour*24, purpose)
}
2024-02-14 01:58:17 +00:00
2024-02-14 03:31:44 +00:00
func JWTGenerateTokenWithDuration(domain string, privateKey ed25519.PrivateKey, userID uint, duration time.Duration, purpose JWTPurpose) (string, error) {
2024-02-14 03:17:34 +00:00
// Define the claims
2024-02-14 03:17:34 +00:00
claims := jwt.RegisteredClaims{
Issuer: domain,
Subject: strconv.Itoa(int(userID)),
ExpiresAt: jwt.NewNumericDate(time.Now().Add(duration)),
IssuedAt: jwt.NewNumericDate(time.Now()),
Audience: []string{string(purpose)},
}
// Create the token
token := jwt.NewWithClaims(jwt.SigningMethodEdDSA, claims)
// Sign the token with the Ed25519 private key
tokenString, err := token.SignedString(privateKey)
if err != nil {
return "", err
}
return tokenString, nil
}
2024-02-14 03:17:34 +00:00
2024-02-14 03:31:44 +00:00
func JWTVerifyToken(token string, domain string, privateKey ed25519.PrivateKey, verifyFunc VerifyTokenFunc) (*jwt.RegisteredClaims, error) {
2024-02-18 01:07:43 +00:00
validatedToken, err := jwt.ParseWithClaims(token, &jwt.RegisteredClaims{}, func(token *jwt.Token) (interface{}, error) {
2024-02-14 03:17:34 +00:00
if _, ok := token.Method.(*jwt.SigningMethodEd25519); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
publicKey := privateKey.Public()
return publicKey, nil
})
if err != nil {
return nil, err
}
if verifyFunc == nil {
verifyFunc = nopVerifyFunc
}
2024-02-18 01:07:43 +00:00
claim, ok := validatedToken.Claims.(*jwt.RegisteredClaims)
2024-02-14 03:17:34 +00:00
if !ok {
return nil, fmt.Errorf("%w: %s", ErrJWTUnexpectedClaimsType, validatedToken.Claims)
}
if domain != claim.Issuer {
return nil, fmt.Errorf("%w: %s", ErrJWTUnexpectedIssuer, claim.Issuer)
}
2024-02-18 01:11:43 +00:00
err = verifyFunc(claim)
2024-02-14 03:17:34 +00:00
2024-02-18 01:16:19 +00:00
return claim, err
2024-02-14 03:17:34 +00:00
}
2024-03-17 12:15:27 +00:00
2024-03-17 13:18:01 +00:00
func SetAuthCookie(jc jape.Context, jwt string, apiName string) {
for name, api := range apiRegistry.GetAllAPIs() {
routeableApi, ok := api.(router.RoutableAPI)
if !ok {
continue
}
if len(apiName) > 0 && apiName != name {
continue
}
2024-03-17 13:09:29 +00:00
http.SetCookie(jc.ResponseWriter, &http.Cookie{
Name: routeableApi.AuthTokenName(),
Value: jwt,
Expires: time.Now().Add(24 * time.Hour),
Secure: true,
HttpOnly: true,
Path: "/",
Domain: routeableApi.Domain(),
})
}
2024-03-17 12:15:27 +00:00
}
2024-03-17 13:27:57 +00:00
2024-03-18 21:02:16 +00:00
func EchoAuthCookie(jc jape.Context, apiName string) {
for name, api := range apiRegistry.GetAllAPIs() {
routeableApi, ok := api.(router.RoutableAPI)
if !ok {
continue
}
if len(apiName) > 0 && apiName != name {
continue
}
cookies := lo.Filter(jc.Request.Cookies(), func(item *http.Cookie, _ int) bool {
return item.Name == routeableApi.AuthTokenName()
})
if len(cookies) == 0 {
continue
}
http.SetCookie(jc.ResponseWriter, cookies[0])
}
}
2024-03-17 13:27:57 +00:00
func ClearAuthCookie(jc jape.Context, apiName string) {
for name, api := range apiRegistry.GetAllAPIs() {
routeableApi, ok := api.(router.RoutableAPI)
if !ok {
continue
}
if len(apiName) > 0 && apiName != name {
continue
}
http.SetCookie(jc.ResponseWriter, &http.Cookie{
Name: routeableApi.AuthTokenName(),
Value: "",
Expires: time.Now().Add(-1 * time.Hour),
Secure: true,
2024-03-17 13:27:57 +00:00
HttpOnly: true,
Path: "/",
Domain: routeableApi.Domain(),
})
}
}