1package plc
2
3import (
4 "context"
5 "crypto/rand"
6 "encoding/hex"
7
8 "github.com/whyrusleeping/go-did"
9 "gorm.io/gorm"
10)
11
12type FakeDidMapping struct {
13 gorm.Model
14 Handle string
15 Did string `gorm:"index"`
16 Service string
17 KeyType string
18 PubKeyMbase string
19}
20
21type FakeDid struct {
22 db *gorm.DB
23}
24
25func NewFakeDid(db *gorm.DB) *FakeDid {
26 db.AutoMigrate(&FakeDidMapping{})
27 return &FakeDid{db}
28}
29
30func (fd *FakeDid) GetDocument(ctx context.Context, udid string) (*did.Document, error) {
31 var rec FakeDidMapping
32 if err := fd.db.First(&rec, "did = ?", udid).Error; err != nil {
33 return nil, err
34 }
35
36 d, err := did.ParseDID(rec.Did)
37 if err != nil {
38 panic(err)
39 }
40
41 return &did.Document{
42 Context: []string{},
43
44 ID: d,
45
46 AlsoKnownAs: []string{"https://" + rec.Handle},
47
48 //Authentication []interface{} `json:"authentication"`
49
50 VerificationMethod: []did.VerificationMethod{
51 did.VerificationMethod{
52 ID: "#signingKey",
53 Type: rec.KeyType,
54 PublicKeyMultibase: &rec.PubKeyMbase,
55 Controller: rec.Did,
56 },
57 },
58
59 Service: []did.Service{
60 did.Service{
61 //ID: "",
62 Type: "pds",
63 ServiceEndpoint: "http://" + rec.Service,
64 },
65 },
66 }, nil
67}
68
69func (fd *FakeDid) FlushCacheFor(did string) {
70 return
71}
72
73func (fd *FakeDid) CreateDID(ctx context.Context, sigkey *did.PrivKey, recovery string, handle string, service string) (string, error) {
74 buf := make([]byte, 8)
75 rand.Read(buf)
76 d := "did:plc:" + hex.EncodeToString(buf)
77
78 if err := fd.db.Create(&FakeDidMapping{
79 Handle: handle,
80 Did: d,
81 Service: service,
82 PubKeyMbase: sigkey.Public().MultibaseString(),
83 KeyType: sigkey.KeyType(),
84 }).Error; err != nil {
85 return "", err
86 }
87
88 return d, nil
89}
90
91func (fd *FakeDid) UpdateUserHandle(ctx context.Context, did string, nhandle string) error {
92 if err := fd.db.Model(FakeDidMapping{}).Where("did = ?", did).UpdateColumn("handle", nhandle).Error; err != nil {
93 return err
94 }
95
96 return nil
97}