@@ 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]