-
Notifications
You must be signed in to change notification settings - Fork 29
/
context.go
68 lines (55 loc) · 2.04 KB
/
context.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Copyright 2017 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package auth
import (
"context"
)
type contextKey int
const (
userCredentialsKey contextKey = iota
requiredDomainKey
dischargeIDKey
usernameKey
)
type userCredentials struct {
username, password string
}
// ContextWithUserCredentials returns a context with the given user
// credentials attached. These will then be checked when performing
// authorizations.
func ContextWithUserCredentials(ctx context.Context, username, password string) context.Context {
return context.WithValue(ctx, userCredentialsKey, userCredentials{username, password})
}
func userCredentialsFromContext(ctx context.Context) (username, password string, ok bool) {
uc, ok := ctx.Value(userCredentialsKey).(userCredentials)
return uc.username, uc.password, ok
}
// ContextWithRequiredDomain returns a context associated
// with the given domain, such that declared identities
// will only be allowed if they have that domain.
func ContextWithRequiredDomain(ctx context.Context, domain string) context.Context {
return context.WithValue(ctx, requiredDomainKey, domain)
}
func requiredDomainFromContext(ctx context.Context) string {
requiredDomain, _ := ctx.Value(usernameKey).(string)
return requiredDomain
}
// ContextWithDischargeID returns a context with the given discharge ID
// stored.
func ContextWithDischargeID(ctx context.Context, dischargeID string) context.Context {
return context.WithValue(ctx, dischargeIDKey, dischargeID)
}
func dischargeIDFromContext(ctx context.Context) string {
dischargeID, _ := ctx.Value(dischargeIDKey).(string)
return dischargeID
}
// ContextWithUsername returns a context with the given username stored.
// Any user attached to the context will be considered authenticated by
// IdentityFromContext.
func ContextWithUsername(ctx context.Context, username string) context.Context {
return context.WithValue(ctx, usernameKey, username)
}
func usernameFromContext(ctx context.Context) string {
username, _ := ctx.Value(usernameKey).(string)
return username
}