-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
enable jwt generate/validate/extract support with github.com/golang-j…
…wt/jwt/v5 (#24) * init empty jwt interface * added utility method to generate/validate/extract jwt token * added test code for jwt generate/validate/extract claims
- Loading branch information
1 parent
a26d6df
commit e054f7e
Showing
4 changed files
with
277 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
package auth | ||
|
||
import ( | ||
"context" | ||
"reflect" | ||
|
||
"github.com/golang-jwt/jwt/v5" | ||
"github.com/irdaislakhuafa/go-sdk/codes" | ||
"github.com/irdaislakhuafa/go-sdk/errors" | ||
) | ||
|
||
type JWTInterface[C jwt.Claims] interface { | ||
Generate(ctx context.Context) (string, error) | ||
Validate(ctx context.Context, tokenString string) (*jwt.Token, error) | ||
ExtractClaims(ctx context.Context, jwtToken *jwt.Token) (C, error) | ||
WithSigningMethod(signingMethod jwt.SigningMethod) JWTInterface[C] | ||
} | ||
|
||
type jwtimpl[C jwt.Claims] struct { | ||
secretKey []byte | ||
claims C | ||
signingMethod jwt.SigningMethod | ||
} | ||
|
||
func InitJWT[C jwt.Claims](secretKey []byte, claims C) JWTInterface[C] { | ||
j := jwtimpl[C]{ | ||
secretKey: secretKey, | ||
claims: claims, | ||
signingMethod: jwt.SigningMethodHS256, | ||
} | ||
return &j | ||
} | ||
|
||
func (j *jwtimpl[C]) Generate(ctx context.Context) (string, error) { | ||
jwtToken := jwt.NewWithClaims(j.signingMethod, j.claims) | ||
jwtString, err := jwtToken.SignedString(j.secretKey) | ||
if err != nil { | ||
return "", errors.NewWithCode(codes.CodeJWTSignedStringError, "cannot signed string, %v", err.Error()) | ||
} | ||
|
||
return jwtString, nil | ||
} | ||
|
||
func (j *jwtimpl[C]) Validate(ctx context.Context, tokenString string) (*jwt.Token, error) { | ||
kind := reflect.TypeOf(j.claims).Kind() | ||
|
||
switch kind { | ||
case reflect.Pointer: | ||
keyFunc := func(jwtToken *jwt.Token) (any, error) { | ||
if _, isOk := jwtToken.Method.(*jwt.SigningMethodHMAC); !isOk { | ||
return nil, errors.NewWithCode(codes.CodeJWTInvalidMethod, "invalid token method algoritm") | ||
} | ||
return j.secretKey, nil | ||
} | ||
|
||
jwtToken, err := jwt.ParseWithClaims(tokenString, j.claims, keyFunc) | ||
if err != nil { | ||
return nil, errors.NewWithCode(codes.CodeJWTParseWithClaimsError, "cannot parse token with claims, %v", err) | ||
} | ||
|
||
return jwtToken, nil | ||
default: | ||
return nil, errors.NewWithCode(codes.CodeJWTInvalidClaimsType, "claims type must be a pointer but got %v", kind.String()) | ||
} | ||
} | ||
|
||
func (j *jwtimpl[C]) ExtractClaims(ctx context.Context, jwtToken *jwt.Token) (C, error) { | ||
claims, isOk := jwtToken.Claims.(C) | ||
if !isOk { | ||
return j.claims, errors.NewWithCode(codes.CodeJWTInvalidClaimsType, "claims type is not equals") | ||
} | ||
|
||
return claims, nil | ||
} | ||
|
||
func (j *jwtimpl[C]) WithSigningMethod(signingMethod jwt.SigningMethod) JWTInterface[C] { | ||
j.signingMethod = signingMethod | ||
return j | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,184 @@ | ||
package auth | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"strings" | ||
"testing" | ||
"time" | ||
|
||
"github.com/golang-jwt/jwt/v5" | ||
"github.com/google/uuid" | ||
"github.com/irdaislakhuafa/go-sdk/codes" | ||
"github.com/irdaislakhuafa/go-sdk/errors" | ||
"github.com/irdaislakhuafa/go-sdk/files" | ||
) | ||
|
||
func Test_JWT(t *testing.T) { | ||
type Mode int | ||
|
||
const ( | ||
MODE_GENERATE = Mode(iota + 1) | ||
MODE_VALIDATE | ||
MODE_EXTRACT | ||
) | ||
|
||
type claims struct { | ||
UserID string | ||
jwt.RegisteredClaims | ||
} | ||
|
||
type params struct { | ||
claims claims | ||
tokenString string | ||
secretKey string | ||
} | ||
|
||
type want struct { | ||
fn func(token string) error | ||
} | ||
|
||
type wantErr struct { | ||
code codes.Code | ||
} | ||
|
||
type test struct { | ||
ctx context.Context | ||
name string | ||
beforeFunc func(ctx context.Context, j JWTInterface[*claims], p *params) | ||
mode Mode | ||
params params | ||
want want | ||
isWantErr bool | ||
wantErr wantErr | ||
} | ||
|
||
tests := []test{ | ||
{ | ||
ctx: context.Background(), | ||
name: "generate jwt token string", | ||
mode: MODE_GENERATE, | ||
params: params{ | ||
claims: claims{ | ||
uuid.NewString(), | ||
jwt.RegisteredClaims{ | ||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * 24)), | ||
}, | ||
}, | ||
secretKey: "secret", | ||
}, | ||
isWantErr: false, | ||
want: want{ | ||
fn: func(token string) error { | ||
if len(strings.Split(token, ".")) == 3 { | ||
return nil | ||
} | ||
return errors.NewWithCode(codes.CodeJWT, "generated jwt token not valid") | ||
}, | ||
}, | ||
wantErr: wantErr{}, | ||
}, | ||
{ | ||
ctx: context.Background(), | ||
name: "validate jwt token string", | ||
beforeFunc: func(ctx context.Context, j JWTInterface[*claims], p *params) { | ||
s, _ := j.Generate(ctx) | ||
p.tokenString = s | ||
}, | ||
mode: MODE_VALIDATE, | ||
params: params{ | ||
secretKey: "secret", | ||
}, | ||
isWantErr: false, | ||
want: want{ | ||
fn: func(token string) error { | ||
return nil | ||
}, | ||
}, | ||
wantErr: wantErr{}, | ||
}, | ||
{ | ||
ctx: context.Background(), | ||
name: "extract claims jwt token string", | ||
beforeFunc: func(ctx context.Context, j JWTInterface[*claims], p *params) { | ||
s, _ := j.Generate(ctx) | ||
p.tokenString = s | ||
}, | ||
mode: MODE_EXTRACT, | ||
params: params{ | ||
secretKey: "secret", | ||
}, | ||
isWantErr: false, | ||
want: want{ | ||
fn: func(token string) error { | ||
return nil | ||
}, | ||
}, | ||
wantErr: wantErr{}, | ||
}, | ||
} | ||
|
||
f := files.GetCurrentMethodName() | ||
for _, tt := range tests { | ||
t.Run(fmt.Sprintf("%v:%v", f, tt.name), func(t *testing.T) { | ||
jwtFunc := InitJWT([]byte(tt.params.secretKey), &tt.params.claims) | ||
|
||
if tt.beforeFunc != nil { | ||
tt.beforeFunc(tt.ctx, jwtFunc, &tt.params) | ||
} | ||
|
||
switch tt.mode { | ||
case MODE_GENERATE: | ||
s, err := jwtFunc.Generate(tt.ctx) | ||
if tt.isWantErr { | ||
if err != nil { | ||
if code := errors.GetCode(err); code != tt.wantErr.code { | ||
t.Fatalf("want err code is %#v but got err code %#v", tt.wantErr.code, code) | ||
} | ||
} else { | ||
t.Fatalf("want err is %#v but got err %#v", tt.isWantErr, err) | ||
} | ||
} | ||
|
||
if err := tt.want.fn(s); err != nil { | ||
t.Fatalf(err.Error()) | ||
} | ||
|
||
t.Logf("generated token: %#v", s) | ||
|
||
case MODE_VALIDATE: | ||
_, err := jwtFunc.Validate(tt.ctx, tt.params.tokenString) | ||
if tt.isWantErr { | ||
if err != nil { | ||
if code := errors.GetCode(err); code != tt.wantErr.code { | ||
t.Fatalf("want err code is %#v but got err code %#v", tt.wantErr.code, code) | ||
} | ||
} else { | ||
t.Fatalf("want err is %#v but got err %#v", tt.isWantErr, err) | ||
} | ||
} | ||
case MODE_EXTRACT: | ||
jt, err := jwtFunc.Validate(tt.ctx, tt.params.tokenString) | ||
if err != nil { | ||
if code := errors.GetCode(err); code != tt.wantErr.code { | ||
t.Fatalf("want err code is %#v but got err code %#v", tt.wantErr.code, code) | ||
} | ||
} | ||
|
||
c, err := jwtFunc.ExtractClaims(tt.ctx, jt) | ||
if tt.isWantErr { | ||
if err != nil { | ||
if code := errors.GetCode(err); code != tt.wantErr.code { | ||
t.Fatalf("want err code is %#v but got err code %#v", tt.wantErr.code, code) | ||
} | ||
} else { | ||
t.Fatalf("want err is %#v but got err %#v", tt.isWantErr, err) | ||
} | ||
} | ||
|
||
t.Logf("claims: %#v", *c) | ||
} | ||
}) | ||
fmt.Println("") | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters