-
Notifications
You must be signed in to change notification settings - Fork 23
/
currentuser_middleware.go
143 lines (119 loc) · 4.3 KB
/
currentuser_middleware.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
//
// Copyright 2024 The Chainloop Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package usercontext
import (
"context"
"errors"
"fmt"
"time"
"github.com/go-kratos/kratos/v2/log"
"github.com/golang-jwt/jwt/v4"
"github.com/chainloop-dev/chainloop/app/controlplane/internal/biz"
"github.com/chainloop-dev/chainloop/app/controlplane/internal/jwt/user"
"github.com/go-kratos/kratos/v2/middleware"
jwtMiddleware "github.com/go-kratos/kratos/v2/middleware/auth/jwt"
)
// Utils to get and set information from context
type User struct {
Email, ID string
CreatedAt *time.Time
}
type Org struct {
ID, Name string
CreatedAt *time.Time
}
func WithCurrentUser(ctx context.Context, user *User) context.Context {
return context.WithValue(ctx, currentUserCtxKey{}, user)
}
// RequestID tries to retrieve requestID from the given context.
// If it doesn't exist, an empty string is returned.
func CurrentUser(ctx context.Context) *User {
res := ctx.Value(currentUserCtxKey{})
if res == nil {
return nil
}
return res.(*User)
}
func WithCurrentOrg(ctx context.Context, org *Org) context.Context {
return context.WithValue(ctx, currentOrgCtxKey{}, org)
}
// RequestID tries to retrieve requestID from the given context.
// If it doesn't exist, an empty string is returned.
func CurrentOrg(ctx context.Context) *Org {
res := ctx.Value(currentOrgCtxKey{})
if res == nil {
return nil
}
return res.(*Org)
}
type currentUserCtxKey struct{}
type currentOrgCtxKey struct{}
// Middleware that injects the current user + organization to the context
func WithCurrentUserAndOrgMiddleware(userUseCase biz.UserOrgFinder, logger *log.Helper) middleware.Middleware {
return func(handler middleware.Handler) middleware.Handler {
return func(ctx context.Context, req interface{}) (interface{}, error) {
rawClaims, ok := jwtMiddleware.FromContext(ctx)
// If not found means that there is no currentUser set in the context
if !ok {
logger.Warn("couldn't extract org/user, JWT parser middleware not running before this one?")
return nil, errors.New("can't extract JWT info from the context")
}
genericClaims, ok := rawClaims.(jwt.MapClaims)
if !ok {
return nil, errors.New("error mapping the claims")
}
// Check wether the token is for a user or an API-token and handle accordingly
// We've received a token for a user
if genericClaims.VerifyAudience(user.Audience, true) {
userID, ok := genericClaims["user_id"].(string)
if !ok || userID == "" {
return nil, errors.New("error mapping the user claims")
}
var err error
ctx, err = setCurrentOrgAndUser(ctx, userUseCase, userID, logger)
if err != nil {
return nil, fmt.Errorf("error setting current org and user: %w", err)
}
logger.Infow("msg", "[authN] processed credentials", "id", userID, "type", "user")
}
return handler(ctx, req)
}
}
}
// Find organization and user in DB
func setCurrentOrgAndUser(ctx context.Context, userUC biz.UserOrgFinder, userID string, logger *log.Helper) (context.Context, error) {
u, err := userUC.FindByID(ctx, userID)
if err != nil {
return nil, err
}
if u == nil {
logger.Warnf("user with id %s not found", userID)
return nil, errors.New("user not found")
}
// We load the current organization
membership, err := userUC.CurrentMembership(ctx, userID)
if err != nil {
return nil, err
}
if membership == nil {
logger.Warnf("user with id %s has no current organization", userID)
return nil, errors.New("org not found")
}
ctx = WithCurrentOrg(ctx, &Org{Name: membership.Org.Name, ID: membership.Org.ID, CreatedAt: membership.CreatedAt})
ctx = WithCurrentUser(ctx, &User{Email: u.Email, ID: u.ID, CreatedAt: u.CreatedAt})
// Set the authorization subject that will be used to check the policies
ctx = WithAuthzSubject(ctx, string(membership.Role))
return ctx, nil
}