graphqlidentity.go

 1// Package graphqlidentity contains helpers for managing identities within the GraphQL API.
 2package graphqlidentity
 3
 4import (
 5	"context"
 6
 7	"github.com/MichaelMure/git-bug/cache"
 8	"github.com/MichaelMure/git-bug/entity"
 9	"github.com/MichaelMure/git-bug/identity"
10	"github.com/MichaelMure/git-bug/repository"
11)
12
13// identityCtxKey is a unique context key, accessible only in this package.
14var identityCtxKey = &struct{}{}
15
16// AttachToContext attaches an Identity to a context.
17func AttachToContext(ctx context.Context, u *identity.Identity) context.Context {
18	return context.WithValue(ctx, identityCtxKey, u.Id())
19}
20
21// ForContext retrieves an IdentityCache from the context.
22// If there is no identity in the context, ErrNotAuthenticated is returned.
23// If an error occurs while resolving the identity (e.g. I/O error), then it will be returned.
24func ForContext(ctx context.Context, r *cache.RepoCache) (*cache.IdentityCache, error) {
25	id, ok := ctx.Value(identityCtxKey).(entity.Id)
26	if !ok {
27		return nil, ErrNotAuthenticated
28	}
29	return r.ResolveIdentity(id)
30}
31
32// ForContextUncached retrieves an Identity from the context.
33// If there is no identity in the context, ErrNotAuthenticated is returned.
34// If an error occurs while resolving the identity (e.g. I/O error), then it will be returned.
35func ForContextUncached(ctx context.Context, repo repository.Repo) (*identity.Identity, error) {
36	id, ok := ctx.Value(identityCtxKey).(entity.Id)
37	if !ok {
38		return nil, ErrNotAuthenticated
39	}
40	return identity.ReadLocal(repo, id)
41}