/
archivedbmodule.go
57 lines (48 loc) · 1.59 KB
/
archivedbmodule.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
package keycloakb
import (
"context"
"encoding/json"
"github.com/cloudtrust/common-service/database/sqltypes"
"github.com/cloudtrust/common-service/log"
"github.com/cloudtrust/common-service/security"
"github.com/cloudtrust/keycloak-bridge/internal/dto"
)
const (
storeUserArchiveStmt = `
INSERT users (realm_name, user_id, timestamp, details)
VALUES (?, ?, UTC_TIMESTAMP, ?)
`
)
// ArchiveDBModule interface
type ArchiveDBModule interface {
StoreUserDetails(ctx context.Context, realm string, user dto.ArchiveUserRepresentation) error
}
type archiveDBModule struct {
db sqltypes.CloudtrustDB
cipher security.EncrypterDecrypter
logger log.Logger
}
// NewArchiveDBModule returns an archive DB module.
func NewArchiveDBModule(db sqltypes.CloudtrustDB, cipher security.EncrypterDecrypter, logger log.Logger) ArchiveDBModule {
return &archiveDBModule{
db: db,
cipher: cipher,
logger: logger,
}
}
func (a *archiveDBModule) StoreUserDetails(ctx context.Context, realm string, user dto.ArchiveUserRepresentation) error {
details, err := json.Marshal(user)
if err != nil {
a.logger.Warn(ctx, "msg", "Can't marshal user to json", "error", err.Error(), "realmID", realm, "userID", user.ID)
return err
}
// encrypt the JSON containing the details on the user
encryptedData, err := a.cipher.Encrypt(details, []byte(*user.ID))
if err != nil {
a.logger.Warn(ctx, "msg", "Can't encrypt the user archive", "error", err.Error(), "realmID", realm, "userID", user.ID)
return err
}
// update value in DB
_, err = a.db.Exec(storeUserArchiveStmt, realm, user.ID, encryptedData)
return err
}