This repository has been archived by the owner on Mar 29, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathjap.go
81 lines (70 loc) · 1.94 KB
/
jap.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
69
70
71
72
73
74
75
76
77
78
79
80
81
package jap
import (
"crypto/rsa"
"errors"
"net/http"
"golang.org/x/net/context"
"golang.org/x/net/trace"
"golang.org/x/oauth2/jws"
)
const (
clientIDKey int = iota
)
var (
errPermissionDenied = errors.New("Permission denied")
)
// CIDFromContext returns the client ID bound to the context, if any.
func CIDFromContext(ctx context.Context) (cid string, ok bool) {
cid, ok = ctx.Value(clientIDKey).(string)
return
}
// NewCIDContext returns a copy of the parent context and associates it with a
// client id.
func NewCIDContext(ctx context.Context, cid string) context.Context {
return context.WithValue(ctx, clientIDKey, cid)
}
func writeError(ctx context.Context, w http.ResponseWriter, msg string, status int) {
tr, ok := trace.FromContext(ctx)
if ok {
tr.LazyPrintf(msg)
tr.SetError()
}
http.Error(w, msg, status)
}
// PermissionChecker is a function that's used for checking if the email
// associated with a given token has permission to perform some action.
type PermissionChecker func(tok string) (bool, error)
func signJWT(
ctx context.Context,
claims jws.ClaimSet,
key *rsa.PrivateKey,
permCheck PermissionChecker) (tok string, err error) {
// Assert that we actually get a key. We don't want bugs that result in nil
// keys to go unnoticed; we want them to break everything. This would probably
// happen in the crypto functions anyways, but I want it to be testable.
if key == nil {
panic("got nil RSA private key; something is very, very wrong.")
}
tr, ok := trace.FromContext(ctx)
header := jws.Header{
Algorithm: "RS256",
}
if ok {
tr.LazyPrintf("Signing JWT…")
}
tok, err = jws.Encode(&header, &claims, key)
if err != nil {
return tok, err
}
if ok {
tr.LazyPrintf("Done signing JWT.")
}
if permCheck != nil {
tr.LazyPrintf("Checking permissions…")
// TODO(ssw): Retry if there's an error?
if ok, err := permCheck(tok); !ok || err != nil {
return tok, errPermissionDenied
}
}
return tok, nil
}