-
Notifications
You must be signed in to change notification settings - Fork 0
/
id.go
54 lines (44 loc) · 1.51 KB
/
id.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package user
import (
"golang.org/x/net/context"
"github.com/weaveworks/common/errors"
)
type contextKey int
const (
// Keys used in contexts to find the org or user ID
orgIDContextKey contextKey = 0
userIDContextKey contextKey = 1
)
// Errors that we return
const (
ErrNoOrgID = errors.Error("no org id")
ErrDifferentOrgIDPresent = errors.Error("different org ID already present")
ErrTooManyOrgIDs = errors.Error("multiple org IDs present")
ErrNoUserID = errors.Error("no user id")
ErrDifferentUserIDPresent = errors.Error("different user ID already present")
ErrTooManyUserIDs = errors.Error("multiple user IDs present")
)
// ExtractOrgID gets the org ID from the context.
func ExtractOrgID(ctx context.Context) (string, error) {
orgID, ok := ctx.Value(orgIDContextKey).(string)
if !ok {
return "", ErrNoOrgID
}
return orgID, nil
}
// InjectOrgID returns a derived context containing the org ID.
func InjectOrgID(ctx context.Context, orgID string) context.Context {
return context.WithValue(ctx, interface{}(orgIDContextKey), orgID)
}
// ExtractUserID gets the user ID from the context.
func ExtractUserID(ctx context.Context) (string, error) {
userID, ok := ctx.Value(userIDContextKey).(string)
if !ok {
return "", ErrNoUserID
}
return userID, nil
}
// InjectUserID returns a derived context containing the user ID.
func InjectUserID(ctx context.Context, userID string) context.Context {
return context.WithValue(ctx, interface{}(userIDContextKey), userID)
}