From beedd6781e4bf0a2b9b001b5b7b204d5caa6b94b Mon Sep 17 00:00:00 2001 From: Maxim Lebedev Date: Fri, 25 Feb 2022 20:34:20 +0500 Subject: [PATCH] :necktie: Updated token use case logic --- internal/token/delivery/http/token_http.go | 2 +- .../token/delivery/http/token_http_test.go | 14 ++- internal/token/usecase/token_ucase.go | 104 ++++++++---------- internal/user/delivery/http/user_http.go | 24 ++-- main.go | 7 +- 5 files changed, 77 insertions(+), 74 deletions(-) diff --git a/internal/token/delivery/http/token_http.go b/internal/token/delivery/http/token_http.go index c4d8f42..fdf347f 100644 --- a/internal/token/delivery/http/token_http.go +++ b/internal/token/delivery/http/token_http.go @@ -175,7 +175,7 @@ func (h *RequestHandler) handleIntrospect(ctx *http.RequestCtx) { return } - tkn, err := h.tokens.Verify(ctx, req.Token) + tkn, _, err := h.tokens.Verify(ctx, req.Token) if err != nil || tkn == nil { // WARN(toby3d): If the token is not valid, the endpoint still // MUST return a 200 Response. diff --git a/internal/token/delivery/http/token_http_test.go b/internal/token/delivery/http/token_http_test.go index 5ba7eb5..5d9c51f 100644 --- a/internal/token/delivery/http/token_http_test.go +++ b/internal/token/delivery/http/token_http_test.go @@ -12,6 +12,8 @@ import ( "source.toby3d.me/website/indieauth/internal/common" "source.toby3d.me/website/indieauth/internal/domain" + "source.toby3d.me/website/indieauth/internal/profile" + profilerepo "source.toby3d.me/website/indieauth/internal/profile/repository/memory" "source.toby3d.me/website/indieauth/internal/session" sessionrepo "source.toby3d.me/website/indieauth/internal/session/repository/memory" "source.toby3d.me/website/indieauth/internal/testing/httptest" @@ -27,6 +29,7 @@ import ( type Dependencies struct { client *http.Client config *domain.Config + profiles profile.Repository sessions session.Repository store *sync.Map tickets ticket.Repository @@ -135,19 +138,26 @@ func TestRevocation(t *testing.T) { func NewDependencies(tb testing.TB) Dependencies { tb.Helper() + store := new(sync.Map) client := new(http.Client) config := domain.TestConfig(tb) - store := new(sync.Map) token := domain.TestToken(tb) + profiles := profilerepo.NewMemoryProfileRepository(store) sessions := sessionrepo.NewMemorySessionRepository(store, config) tickets := ticketrepo.NewMemoryTicketRepository(store, config) tokens := tokenrepo.NewMemoryTokenRepository(store) ticketService := ticketucase.NewTicketUseCase(tickets, client, config) - tokenService := tokenucase.NewTokenUseCase(tokens, sessions, config) + tokenService := tokenucase.NewTokenUseCase(tokenucase.Config{ + Config: config, + Profiles: profiles, + Sessions: sessions, + Tokens: tokens, + }) return Dependencies{ client: client, config: config, + profiles: profiles, sessions: sessions, store: store, tickets: tickets, diff --git a/internal/token/usecase/token_ucase.go b/internal/token/usecase/token_ucase.go index d7d1519..8a02baf 100644 --- a/internal/token/usecase/token_ucase.go +++ b/internal/token/usecase/token_ucase.go @@ -9,32 +9,41 @@ import ( "github.com/lestrrat-go/jwx/jwt" "source.toby3d.me/website/indieauth/internal/domain" + "source.toby3d.me/website/indieauth/internal/profile" "source.toby3d.me/website/indieauth/internal/session" "source.toby3d.me/website/indieauth/internal/token" ) -type tokenUseCase struct { - sessions session.Repository - tokens token.Repository - config *domain.Config -} +type ( + Config struct { + Config *domain.Config + Profiles profile.Repository + Sessions session.Repository + Tokens token.Repository + } -func NewTokenUseCase(tokens token.Repository, sessions session.Repository, config *domain.Config) token.UseCase { - jwt.RegisterCustomField("email", new(domain.Email)) - jwt.RegisterCustomField("photo", new(domain.URL)) + tokenUseCase struct { + config *domain.Config + profiles profile.Repository + sessions session.Repository + tokens token.Repository + } +) + +func NewTokenUseCase(config Config) token.UseCase { jwt.RegisterCustomField("scope", make(domain.Scopes, 0)) - jwt.RegisterCustomField("url", new(domain.URL)) return &tokenUseCase{ - config: config, - sessions: sessions, - tokens: tokens, + config: config.Config, + profiles: config.Profiles, + sessions: config.Sessions, + tokens: config.Tokens, } } -func (useCase *tokenUseCase) Exchange(ctx context.Context, opts token.ExchangeOptions) (*domain.Token, *domain.Profile, +func (uc *tokenUseCase) Exchange(ctx context.Context, opts token.ExchangeOptions) (*domain.Token, *domain.Profile, error) { - session, err := useCase.sessions.GetAndDelete(ctx, opts.Code) + session, err := uc.sessions.GetAndDelete(ctx, opts.Code) if err != nil { return nil, nil, fmt.Errorf("cannot get session from store: %w", err) } @@ -66,14 +75,13 @@ func (useCase *tokenUseCase) Exchange(ctx context.Context, opts token.ExchangeOp } tkn, err := domain.NewToken(domain.NewTokenOptions{ - Expiration: useCase.config.JWT.Expiry, + Expiration: uc.config.JWT.Expiry, Issuer: session.ClientID, Subject: session.Me, Scope: session.Scope, - Secret: []byte(useCase.config.JWT.Secret), - Profile: session.Profile, - Algorithm: useCase.config.JWT.Algorithm, - NonceLength: useCase.config.JWT.NonceLength, + Secret: []byte(uc.config.JWT.Secret), + Algorithm: uc.config.JWT.Algorithm, + NonceLength: uc.config.JWT.NonceLength, }) if err != nil { return nil, nil, fmt.Errorf("cannot generate a new access token: %w", err) @@ -82,24 +90,24 @@ func (useCase *tokenUseCase) Exchange(ctx context.Context, opts token.ExchangeOp return tkn, session.Profile, nil } -func (useCase *tokenUseCase) Verify(ctx context.Context, accessToken string) (*domain.Token, error) { - find, err := useCase.tokens.Get(ctx, accessToken) +func (uc *tokenUseCase) Verify(ctx context.Context, accessToken string) (*domain.Token, *domain.Profile, error) { + find, err := uc.tokens.Get(ctx, accessToken) if err != nil && !errors.Is(err, token.ErrNotExist) { - return nil, fmt.Errorf("cannot check token in store: %w", err) + return nil, nil, fmt.Errorf("cannot check token in store: %w", err) } if find != nil { - return nil, token.ErrRevoke + return nil, nil, token.ErrRevoke } - tkn, err := jwt.ParseString(accessToken, jwt.WithVerify(jwa.SignatureAlgorithm(useCase.config.JWT.Algorithm), - []byte(useCase.config.JWT.Secret))) + tkn, err := jwt.ParseString(accessToken, jwt.WithVerify(jwa.SignatureAlgorithm(uc.config.JWT.Algorithm), + []byte(uc.config.JWT.Secret))) if err != nil { - return nil, fmt.Errorf("cannot parse JWT token: %w", err) + return nil, nil, fmt.Errorf("cannot parse JWT token: %w", err) } if err = jwt.Validate(tkn); err != nil { - return nil, fmt.Errorf("cannot validate JWT token: %w", err) + return nil, nil, fmt.Errorf("cannot validate JWT token: %w", err) } result := &domain.Token{ @@ -107,7 +115,6 @@ func (useCase *tokenUseCase) Verify(ctx context.Context, accessToken string) (*d Expiry: tkn.Expiration(), ClientID: nil, Me: nil, - Profile: nil, Scope: nil, AccessToken: accessToken, RefreshToken: "", // TODO(toby3d) @@ -120,49 +127,28 @@ func (useCase *tokenUseCase) Verify(ctx context.Context, accessToken string) (*d } if !result.Scope.Has(domain.ScopeProfile) { - return result, nil + return result, nil, nil } - result.Profile = domain.NewProfile() - - if name, ok := tkn.Get("name"); ok { - if n, ok := name.(string); ok { - result.Profile.Name = append(result.Profile.Name, n) - } + profile, err := uc.profiles.Get(ctx, result.Me) + if err != nil { + return result, nil, nil } - if url, ok := tkn.Get("url"); ok { - if u, ok := url.(*domain.URL); ok { - result.Profile.URL = append(result.Profile.URL, u) - } + if !result.Scope.Has(domain.ScopeEmail) && len(profile.Email) > 0 { + profile.Email = nil } - if photo, ok := tkn.Get("photo"); ok { - if p, ok := photo.(*domain.URL); ok { - result.Profile.Photo = append(result.Profile.Photo, p) - } - } - - if !result.Scope.Has(domain.ScopeEmail) { - return result, nil - } - - if email, ok := tkn.Get("email"); ok { - if e, ok := email.(*domain.Email); ok { - result.Profile.Email = append(result.Profile.Email, e) - } - } - - return result, nil + return result, profile, nil } -func (useCase *tokenUseCase) Revoke(ctx context.Context, accessToken string) error { - tkn, err := useCase.Verify(ctx, accessToken) +func (uc *tokenUseCase) Revoke(ctx context.Context, accessToken string) error { + tkn, _, err := uc.Verify(ctx, accessToken) if err != nil { return fmt.Errorf("cannot verify token: %w", err) } - if err = useCase.tokens.Create(ctx, tkn); err != nil { + if err = uc.tokens.Create(ctx, tkn); err != nil { return fmt.Errorf("cannot save token in database: %w", err) } diff --git a/internal/user/delivery/http/user_http.go b/internal/user/delivery/http/user_http.go index c8eeca2..0205707 100644 --- a/internal/user/delivery/http/user_http.go +++ b/internal/user/delivery/http/user_http.go @@ -65,8 +65,8 @@ func (h *RequestHandler) handleUserInformation(ctx *http.RequestCtx) { encoder := json.NewEncoder(ctx) - tkn, err := h.tokens.Verify(ctx, strings.TrimPrefix(string(ctx.Request.Header.Peek(http.HeaderAuthorization)), - "Bearer ")) + tkn, userInfo, err := h.tokens.Verify(ctx, strings.TrimPrefix(string(ctx.Request.Header.Peek( + http.HeaderAuthorization)), "Bearer ")) if err != nil || tkn == nil { // WARN(toby3d): If the token is not valid, the endpoint still // MUST return a 200 Response. @@ -88,24 +88,26 @@ func (h *RequestHandler) handleUserInformation(ctx *http.RequestCtx) { } resp := new(UserInformationResponse) - if tkn.Profile == nil { + if userInfo == nil { _ = encoder.Encode(resp) return } - resp.Name = tkn.Profile.GetName() - - if url := tkn.Profile.GetURL(); url != nil { - resp.URL = url.String() + if userInfo.HasName() { + resp.Name = userInfo.GetName() } - if photo := tkn.Profile.GetPhoto(); photo != nil { - resp.Photo = photo.String() + if userInfo.HasURL() { + resp.URL = userInfo.GetURL().String() } - if email := tkn.Profile.GetEmail(); email != nil && tkn.Scope.Has(domain.ScopeEmail) { - resp.Email = email.String() + if userInfo.HasPhoto() { + resp.Photo = userInfo.GetPhoto().String() + } + + if tkn.Scope.Has(domain.ScopeEmail) && userInfo.HasEmail() { + resp.Email = userInfo.GetEmail().String() } _ = encoder.Encode(resp) diff --git a/main.go b/main.go index 47526f7..c3d6ac2 100644 --- a/main.go +++ b/main.go @@ -277,7 +277,12 @@ func NewApp(opts NewAppOptions) *App { matcher: language.NewMatcher(message.DefaultCatalog.Languages()), sessions: sessionucase.NewSessionUseCase(opts.Sessions), tickets: ticketucase.NewTicketUseCase(opts.Tickets, opts.Client, config), - tokens: tokenucase.NewTokenUseCase(opts.Tokens, opts.Sessions, config), + tokens: tokenucase.NewTokenUseCase(tokenucase.Config{ + Config: config, + Profiles: opts.Profiles, + Sessions: opts.Sessions, + Tokens: opts.Tokens, + }), } }