-
Notifications
You must be signed in to change notification settings - Fork 12
/
apiKeyChecker.service.go
168 lines (147 loc) · 4.52 KB
/
apiKeyChecker.service.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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
package security
import (
"context"
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/openline-ai/openline-customer-os/packages/server/customer-os-common-module/tracing"
postgresEntity "github.com/openline-ai/openline-customer-os/packages/server/customer-os-postgres-repository/entity"
postgresRepository "github.com/openline-ai/openline-customer-os/packages/server/customer-os-postgres-repository/repository"
"github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/log"
"github.com/pkg/errors"
"google.golang.org/grpc/metadata"
)
type App string
const (
CUSTOMER_OS_API App = "customer-os-api"
CUSTOMER_OS_WEBHOOKS App = "customer-os-webhooks"
FILE_STORE_API App = "file-store-api"
SETTINGS_API App = "settings-api"
VALIDATION_API App = "validation-api"
AI_API App = "ai-api"
PLATFORM_ADMIN_API App = "platform-admin-api"
)
const ApiKeyHeader = "X-Openline-API-KEY"
const TenantApiKeyHeader = "X-CUSTOMER-OS-API-KEY"
func ApiKeyCheckerHTTP(tenantApiKeyRepo postgresRepository.TenantWebhookApiKeyRepository, appKeyRepo postgresRepository.AppKeyRepository, app App, opts ...CommonServiceOption) func(c *gin.Context) {
// Apply the options to configure the middleware
config := &Options{}
for _, opt := range opts {
opt(config)
}
return func(c *gin.Context) {
span, ctx := opentracing.StartSpanFromContext(c.Request.Context(), "ApiKeyCheckerHTTP")
spanFinished := false
defer func() {
if !spanFinished {
span.Finish()
}
}()
span.LogFields(log.String("app", string(app)))
kh := c.GetHeader(ApiKeyHeader)
tenantKh := c.GetHeader(TenantApiKeyHeader)
if kh != "" {
// Check if the API key matches the cached value
if config.cache != nil && config.cache.CheckApiKey(string(app), kh) {
// Valid API key found in cache
span.LogFields(log.Bool("cached", true))
if !spanFinished {
spanFinished = true
span.Finish()
}
c.Next()
return
}
span.LogFields(log.Bool("cached", false))
keyResult := appKeyRepo.FindByKey(ctx, string(app), kh)
if keyResult.Error != nil {
c.JSON(http.StatusUnauthorized, gin.H{
"errors": []gin.H{{"message": fmt.Sprintf("Error while checking api key: %s", keyResult.Error.Error())}},
})
c.Abort()
return
}
appKey := keyResult.Result.(*postgresEntity.AppKey)
if appKey == nil {
c.JSON(http.StatusUnauthorized, gin.H{
"errors": []gin.H{{"message": "Invalid api key"}},
})
c.Abort()
return
}
// If the API key is valid after database check, cache it
if config.cache != nil && keyResult.Result != nil {
config.cache.SetApiKey(string(app), kh)
}
if !spanFinished {
spanFinished = true
span.Finish()
}
c.Next()
} else if tenantKh != "" {
// Check if the API key matches the cached value
if config.cache != nil && config.cache.CheckTenantApiKey(tenantKh) {
// Valid API key found in cache
span.LogFields(log.Bool("cached", true))
if !spanFinished {
spanFinished = true
span.Finish()
}
c.Next()
return
}
span.LogFields(log.Bool("cached", false))
keyResult := tenantApiKeyRepo.GetTenantWithApiKey(tenantKh)
if keyResult.Error != nil {
c.JSON(http.StatusUnauthorized, gin.H{
"errors": []gin.H{{"message”": "Invalid api key"}},
})
c.Abort()
return
}
apiKey := keyResult.Result.(*postgresEntity.TenantWebhookApiKey)
if apiKey == nil {
c.JSON(http.StatusUnauthorized, gin.H{
"errors": []gin.H{{"message": "Invalid api key"}},
})
c.Abort()
return
}
if config.cache != nil && keyResult.Result != nil {
config.cache.SetTenantApiKey(tenantKh, apiKey.TenantName)
}
c.Set(KEY_TENANT_NAME, apiKey.TenantName)
c.Set(KEY_USER_ROLES, []string{"USER"})
if !spanFinished {
spanFinished = true
span.Finish()
}
c.Next()
} else {
// illegal request, terminate the current process
c.JSON(http.StatusUnauthorized, gin.H{
"errors": []gin.H{{"message": "Api key is required"}},
})
tracing.TraceErr(span, errors.New("Api key is required"))
c.Abort()
return
}
}
}
func ApiKeyCheckerGRPC(ctx context.Context, appKeyRepo postgresRepository.AppKeyRepository, app App) bool {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return false
}
kh := md.Get(ApiKeyHeader)
if len(kh) == 1 {
keyResult := appKeyRepo.FindByKey(ctx, string(app), kh[0])
if keyResult.Error != nil {
return false
}
appKey := keyResult.Result.(*postgresEntity.AppKey)
return appKey != nil
}
return false
}