-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathidentity.go
358 lines (313 loc) · 10.1 KB
/
identity.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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
/*
Copyright 2024 Blnk Finance 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 blnk
import (
"context"
"encoding/json"
"fmt"
"reflect"
"strings"
"github.com/jerry-enebeli/blnk/internal/notification"
"github.com/jerry-enebeli/blnk/internal/tokenization"
"github.com/jerry-enebeli/blnk/model"
)
// postIdentityActions performs actions after an identity has been created.
// It sends the newly created identity to the search index queue and sends a webhook notification.
func (l *Blnk) postIdentityActions(_ context.Context, identity *model.Identity) {
go func() {
err := l.queue.queueIndexData(identity.IdentityID, "identities", identity)
if err != nil {
notification.NotifyError(err)
}
err = SendWebhook(NewWebhook{
Event: "identity.created",
Payload: identity,
})
if err != nil {
notification.NotifyError(err)
}
}()
}
// CreateIdentity creates a new identity in the database.
//
// Parameters:
// - identity model.Identity: The Identity model to be created.
//
// Returns:
// - model.Identity: The created Identity model.
// - error: An error if the identity could not be created.
func (l *Blnk) CreateIdentity(identity model.Identity) (model.Identity, error) {
identity, err := l.datasource.CreateIdentity(identity)
if err != nil {
return model.Identity{}, err
}
l.postIdentityActions(context.Background(), &identity)
return identity, nil
}
// GetIdentity retrieves an identity by its ID.
//
// Parameters:
// - id string: The ID of the identity to retrieve.
//
// Returns:
// - *model.Identity: A pointer to the Identity model if found.
// - error: An error if the identity could not be retrieved.
func (l *Blnk) GetIdentity(id string) (*model.Identity, error) {
return l.datasource.GetIdentityByID(id)
}
// GetAllIdentities retrieves all identities from the database.
//
// Returns:
// - []model.Identity: A slice of Identity models.
// - error: An error if the identities could not be retrieved.
func (l *Blnk) GetAllIdentities() ([]model.Identity, error) {
return l.datasource.GetAllIdentities()
}
// UpdateIdentity updates an existing identity in the database.
//
// Parameters:
// - identity *model.Identity: A pointer to the Identity model to be updated.
//
// Returns:
// - error: An error if the identity could not be updated.
func (l *Blnk) UpdateIdentity(identity *model.Identity) error {
return l.datasource.UpdateIdentity(identity)
}
// DeleteIdentity deletes an identity by its ID.
//
// Parameters:
// - id string: The ID of the identity to delete.
//
// Returns:
// - error: An error if the identity could not be deleted.
func (l *Blnk) DeleteIdentity(id string) error {
return l.datasource.DeleteIdentity(id)
}
// TokenizeIdentityField tokenizes a specific field in an identity.
//
// Parameters:
// - identityID string: The ID of the identity.
// - fieldName string: The name of the field to tokenize.
//
// Returns:
// - error: An error if the field could not be tokenized.
func (l *Blnk) TokenizeIdentityField(identityID, fieldName string) error {
// Convert field name to struct field format for reflection
structFieldName := convertToStructFieldName(fieldName)
// Check if field is tokenizable
validField := false
for _, field := range tokenization.TokenizableFields {
if field == structFieldName {
validField = true
break
}
}
if !validField {
return fmt.Errorf("field %s is not tokenizable", fieldName)
}
// Get the identity
identity, err := l.GetIdentity(identityID)
if err != nil {
return err
}
// Check if field is already tokenized using the original field name
// as IsFieldTokenized will handle the conversion internally
if identity.IsFieldTokenized(fieldName) {
return fmt.Errorf("field %s is already tokenized", fieldName)
}
// Get the field value using reflection with struct field name
val := reflect.ValueOf(identity).Elem()
fieldVal := val.FieldByName(structFieldName)
if !fieldVal.IsValid() || !fieldVal.CanSet() {
return fmt.Errorf("field %s not found or cannot be set", fieldName)
}
// Get the string value
strVal := fieldVal.String()
// Tokenize the value
token, err := l.tokenizer.TokenizeWithMode(strVal, tokenization.FormatPreservingMode)
if err != nil {
return err
}
// Set the tokenized value
fieldVal.SetString(token)
// Mark the field as tokenized using the original field name
// as MarkFieldAsTokenized will handle the conversion internally
identity.MarkFieldAsTokenized(fieldName)
// Update the identity
return l.UpdateIdentity(identity)
}
// DetokenizeIdentityField detokenizes a specific field in an identity.
//
// Parameters:
// - identityID string: The ID of the identity.
// - fieldName string: The name of the field to detokenize.
//
// Returns:
// - string: The detokenized field value.
// - error: An error if the field could not be detokenized.
func (l *Blnk) DetokenizeIdentityField(identityID, fieldName string) (string, error) {
// Get the identity
identity, err := l.GetIdentity(identityID)
if err != nil {
return "", err
}
// Try both original and capitalized field name
structFieldName := convertToStructFieldName(fieldName)
// Check if field is tokenized
if !identity.IsFieldTokenized(fieldName) && !identity.IsFieldTokenized(structFieldName) {
// Debug info
if identity.MetaData != nil {
metaStr, _ := json.Marshal(identity.MetaData)
return "", fmt.Errorf("field %s is not tokenized. Metadata: %s", fieldName, metaStr)
}
return "", fmt.Errorf("field %s is not tokenized", fieldName)
}
// Get the field value using reflection - try both field name versions
val := reflect.ValueOf(identity).Elem()
fieldVal := val.FieldByName(structFieldName)
if !fieldVal.IsValid() {
fieldVal = val.FieldByName(fieldName)
if !fieldVal.IsValid() {
return "", fmt.Errorf("field %s not found", fieldName)
}
}
// Get the tokenized value
tokenVal := fieldVal.String()
// Detokenize the value
originalValue, err := l.tokenizer.Detokenize(tokenVal)
if err != nil {
return "", err
}
return originalValue, nil
}
// TokenizeIdentity tokenizes all specified fields in an identity.
//
// Parameters:
// - identityID string: The ID of the identity.
// - fields []string: The names of the fields to tokenize.
//
// Returns:
// - error: An error if any field could not be tokenized.
func (l *Blnk) TokenizeIdentity(identityID string, fields []string) error {
for _, field := range fields {
err := l.TokenizeIdentityField(identityID, field)
if err != nil {
return err
}
}
return nil
}
// DetokenizeIdentity detokenizes and returns all tokenized fields in an identity.
//
// Parameters:
// - identityID string: The ID of the identity.
//
// Returns:
// - map[string]string: A map of field names to their detokenized values.
// - error: An error if any field could not be detokenized.
func (l *Blnk) DetokenizeIdentity(identityID string) (map[string]string, error) {
// Get the identity
identity, err := l.GetIdentity(identityID)
if err != nil {
return nil, err
}
result := make(map[string]string)
// Check each tokenized field in metadata
if identity.MetaData != nil {
tokenizedFields, ok := identity.MetaData["tokenized_fields"].(map[string]bool)
if ok {
for fieldName, isTokenized := range tokenizedFields {
if isTokenized {
originalValue, err := l.DetokenizeIdentityField(identityID, fieldName)
if err != nil {
return nil, err
}
result[fieldName] = originalValue
}
}
}
}
return result, nil
}
// TokenizeAllPII tokenizes all eligible PII fields in an identity.
//
// Parameters:
// - identityID string: The ID of the identity.
//
// Returns:
// - error: An error if any field could not be tokenized.
func (l *Blnk) TokenizeAllPII(identityID string) error {
for _, field := range tokenization.TokenizableFields {
// Ignore errors for fields that might already be tokenized
_ = l.TokenizeIdentityField(identityID, field)
}
return nil
}
// GetDetokenizedIdentity returns a copy of the identity with all fields detokenized.
// Note: This does not modify the stored identity.
//
// Parameters:
// - identityID string: The ID of the identity.
//
// Returns:
// - *model.Identity: A pointer to the detokenized Identity model.
// - error: An error if the identity could not be detokenized.
func (l *Blnk) GetDetokenizedIdentity(identityID string) (*model.Identity, error) {
// Get the identity
identity, err := l.GetIdentity(identityID)
if err != nil {
return nil, err
}
// Create a copy
detokenizedIdentity := *identity
// Detokenize all tokenized fields
if identity.MetaData != nil {
tokenizedFields, ok := identity.MetaData["tokenized_fields"].(map[string]bool)
if ok {
for field, isTokenized := range tokenizedFields {
if isTokenized {
originalValue, err := l.DetokenizeIdentityField(identityID, field)
if err != nil {
return nil, err
}
// Set the original value in the copy
val := reflect.ValueOf(&detokenizedIdentity).Elem()
fieldVal := val.FieldByName(field)
if fieldVal.IsValid() && fieldVal.CanSet() {
fieldVal.SetString(originalValue)
}
}
}
}
}
// Create a clean copy of metadata without tokenized_fields
if detokenizedIdentity.MetaData != nil {
newMetaData := make(map[string]interface{})
for k, v := range detokenizedIdentity.MetaData {
if k != "tokenized_fields" {
newMetaData[k] = v
}
}
detokenizedIdentity.MetaData = newMetaData
}
return &detokenizedIdentity, nil
}
// convertToStructFieldName ensures consistent field name format by returning
// the Go struct field name (typically capitalized) for the given input
func convertToStructFieldName(fieldName string) string {
// For simple cases, just capitalize the first letter
if len(fieldName) > 0 {
return strings.ToUpper(fieldName[0:1]) + fieldName[1:]
}
return fieldName
}