1// Package auth contains helpers for managing identities within the GraphQL API.
2package auth
3
4import (
5 "context"
6
7 "github.com/MichaelMure/git-bug/cache"
8 "github.com/MichaelMure/git-bug/entity"
9)
10
11// identityCtxKey is a unique context key, accessible only in this package.
12var identityCtxKey = &struct{}{}
13
14// CtxWithUser attaches an Identity to a context.
15func CtxWithUser(ctx context.Context, userId entity.Id) context.Context {
16 return context.WithValue(ctx, identityCtxKey, userId)
17}
18
19// UserFromCtx retrieves an IdentityCache from the context.
20// If there is no identity in the context, ErrNotAuthenticated is returned.
21// If an error occurs while resolving the identity (e.g. I/O error), then it will be returned.
22func UserFromCtx(ctx context.Context, r *cache.RepoCache) (*cache.IdentityCache, error) {
23 id, ok := ctx.Value(identityCtxKey).(entity.Id)
24 if !ok {
25 return nil, ErrNotAuthenticated
26 }
27 return r.Identities().Resolve(id)
28}