This repository has been archived by the owner on Aug 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
auth.go
70 lines (55 loc) · 1.6 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
package auth
import (
"context"
"time"
"github.com/romshark/dgraph_graphql_go/store"
"github.com/romshark/dgraph_graphql_go/store/errors"
)
// CtxKey represents a context.Context value key type
type CtxKey int
// CtxSession defines the context.Context session value key
const CtxSession CtxKey = 1
// GQLShieldClientRole represents a GraphQL shield client role identifier
type GQLShieldClientRole int
const (
_ GQLShieldClientRole = iota
// GQLShieldClientGuest represents a guest API user
GQLShieldClientGuest
// GQLShieldClientDebug represents the debug API user
GQLShieldClientDebug
// GQLShieldClientRegular represents the regular API user
GQLShieldClientRegular
)
// RequestSession represents a client session
type RequestSession struct {
IsDebug bool
UserID store.ID
Creation time.Time
ShieldClientRole GQLShieldClientRole
}
// Requirement defines the authorization requirement implementation interface
type Requirement interface {
check(session *RequestSession) string
}
// Authorize authorizes the client session taken from the provided context
// against the provided requirements
func Authorize(
ctx context.Context,
requirements ...Requirement,
) error {
// Extract the session
session, isSession := ctx.Value(CtxSession).(*RequestSession)
// Pass debug clients without further authorization
if isSession && session.IsDebug {
return nil
}
// Check all requirements
for _, rule := range requirements {
if errMsg := rule.check(session); len(errMsg) > 0 {
// Unauthorized
return errors.New(errors.ErrUnauthorized, errMsg)
}
}
// Authorized
return nil
}