From 3b8756a853663bcd46a3e1066792936648b166ee Mon Sep 17 00:00:00 2001 From: Peter Sanchez Date: Sun, 23 Jul 2023 07:25:38 -0600 Subject: [PATCH] Adding ErrInvalidToken to make it easier to process auth errors in external applications --- logic.go | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/logic.go b/logic.go index ac2c156..19203de 100644 --- a/logic.go +++ b/logic.go @@ -4,6 +4,7 @@ import ( "context" "crypto/sha512" "encoding/hex" + "errors" "fmt" "log" @@ -12,10 +13,16 @@ import ( "hg.code.netlandish.com/~netlandish/gobwebs/database" ) +// ErrInvalidToken general error for invalid tokens. You can use this to +// customize behavior when an error is returned in your middleware checks. +var ErrInvalidToken = errors.New("invalid or expired OAuth 2.0 bearer token") + +// OAuth2 will check the provided token and verify it's validity, returning a +// TokenUser once all checks pass. func OAuth2(ctx context.Context, token string, fetch gobwebs.UserFetch) (*TokenUser, error) { bt := DecodeBearerToken(ctx, token) if bt == nil { - return nil, fmt.Errorf("Invalid or expired OAuth 2.0 bearer token") + return nil, ErrInvalidToken } user, err := fetch.FromDB(ctx, uint(bt.UserID), true) if err != nil { @@ -35,11 +42,11 @@ func OAuth2(ctx context.Context, token string, fetch gobwebs.UserFetch) (*TokenU return nil, err } if len(grants) == 0 { - return nil, fmt.Errorf("Invalid or expired OAuth 2.0 bearer token") + return nil, ErrInvalidToken } else if len(grants) > 1 { // Should never happen log.Printf("Token hash %s has more than one grant record", hashStr) - return nil, fmt.Errorf("Error with provided OAuth 2.0 bearer token") + return nil, fmt.Errorf("Error with provided OAuth 2.0 bearer token: %w", ErrInvalidToken) } grant := grants[0] -- 2.45.2