-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
gql.go
72 lines (58 loc) · 1.91 KB
/
gql.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
package auth
import (
"context"
"github.com/pkg/errors"
"github.com/smartcontractkit/chainlink/v2/core/logger"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
clsessions "github.com/smartcontractkit/chainlink/v2/core/sessions"
)
type sessionUserKey struct{}
type GQLSession struct {
SessionID string
User *clsessions.User
}
// AuthenticateGQL middleware checks the session cookie for a user and sets it
// on the request context if it exists. It is the responsibility of each resolver
// to validate whether it requires an authenticated user.
//
// We currently only support GQL authentication by session cookie.
func AuthenticateGQL(authenticator Authenticator, lggr logger.Logger) gin.HandlerFunc {
return func(c *gin.Context) {
session := sessions.Default(c)
sessionID, ok := session.Get(SessionIDKey).(string)
if !ok {
return
}
user, err := authenticator.AuthorizedUserWithSession(sessionID)
if err != nil {
if errors.Is(err, clsessions.ErrUserSessionExpired) {
lggr.Warnw("Failed to authenticate session", "err", err)
} else {
lggr.Errorw("Failed call to AuthorizedUserWithSession, unable to get user", "err", err)
}
return
}
ctx := SetGQLAuthenticatedSession(c.Request.Context(), user, sessionID)
c.Request = c.Request.WithContext(ctx)
}
}
// SetGQLAuthenticatedSession sets the authenticated session in the context
//
// There shouldn't be a need to do this outside of testing
func SetGQLAuthenticatedSession(ctx context.Context, user clsessions.User, sessionID string) context.Context {
return context.WithValue(
ctx,
sessionUserKey{},
&GQLSession{sessionID, &user},
)
}
// GetGQLAuthenticatedSession extracts the authentication session from a context.
func GetGQLAuthenticatedSession(ctx context.Context) (*GQLSession, bool) {
obj := ctx.Value(sessionUserKey{})
if obj == nil {
return nil, false
}
session, ok := obj.(*GQLSession)
return session, ok
}