-
Notifications
You must be signed in to change notification settings - Fork 402
/
auth.go
73 lines (54 loc) · 1.69 KB
/
auth.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
// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
package console
import (
"context"
"encoding/base64"
"github.com/zeebo/errs"
"storj.io/storj/satellite/console/consoleauth"
)
//TODO: change to JWT or Macaroon based auth
// Signer creates signature for provided data
type Signer interface {
Sign(data []byte) ([]byte, error)
}
// signToken signs token with given signer
func signToken(token *consoleauth.Token, signer Signer) error {
encoded := base64.URLEncoding.EncodeToString(token.Payload)
signature, err := signer.Sign([]byte(encoded))
if err != nil {
return err
}
token.Signature = signature
return nil
}
// key is a context value key type
type key int
// authKey is context key for Authorization
const authKey key = 0
// ErrUnauthorized is error class for authorization related errors
var ErrUnauthorized = errs.Class("unauthorized error")
// Authorization contains auth info of authorized User
type Authorization struct {
User User
Claims consoleauth.Claims
}
// WithAuth creates new context with Authorization
func WithAuth(ctx context.Context, auth Authorization) context.Context {
return context.WithValue(ctx, authKey, auth)
}
// WithAuthFailure creates new context with authorization failure
func WithAuthFailure(ctx context.Context, err error) context.Context {
return context.WithValue(ctx, authKey, err)
}
// GetAuth gets Authorization from context
func GetAuth(ctx context.Context) (Authorization, error) {
value := ctx.Value(authKey)
if auth, ok := value.(Authorization); ok {
return auth, nil
}
if _, ok := value.(error); ok {
return Authorization{}, errs.New(internalErrMsg)
}
return Authorization{}, errs.New(unauthorizedErrMsg)
}