-
Notifications
You must be signed in to change notification settings - Fork 28
/
operations.go
230 lines (179 loc) · 5.74 KB
/
operations.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
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package operation
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"path"
"time"
"github.com/google/uuid"
"github.com/gorilla/mux"
"github.com/hyperledger/aries-framework-go/pkg/doc/verifiable"
log "github.com/sirupsen/logrus"
"github.com/trustbloc/edge-core/pkg/storage"
"github.com/trustbloc/edge-service/pkg/internal/common/support"
)
const (
credential = "credential"
createCredentialEndpoint = "/credential"
createProfileEndpoint = "/profile"
credentialContext = "https://www.w3.org/2018/credentials/v1"
profilePathVariable = "profileID"
getProfileEndpoint = "/profile/{" + profilePathVariable
// ID is the identifier for the verifiable credential
ID = "https://example.com/credentials/1872"
// TODO create the profile and get the prefix of the ID from the profile issue-47
)
var errProfileNotFound = errors.New("specified profile ID does not exist")
// Handler http handler for each controller API endpoint
type Handler interface {
Path() string
Method() string
Handle() http.HandlerFunc
}
// New returns CreateCredential instance
func New(provider storage.Provider) (*Operation, error) {
store, err := provider.OpenStore(credential)
if err != nil {
return nil, err
}
profileStore := NewProfile(store)
svc := &Operation{
profileStore: profileStore,
}
svc.registerHandler()
return svc, nil
}
// Operation defines handlers for Edge service
type Operation struct {
handlers []Handler
profileStore *Profile
}
func (c *Operation) createCredentialHandler(rw http.ResponseWriter, req *http.Request) {
data := CreateCrendential{}
err := json.NewDecoder(req.Body).Decode(&data)
if err != nil {
c.writeErrorResponse(rw, http.StatusBadRequest, "Failed to write response for invalid request received")
return
}
validCredential, err := createCredential(&data)
if err != nil {
c.writeErrorResponse(rw, http.StatusBadRequest, "Failed to write response for create credential failure")
return
}
rw.WriteHeader(http.StatusCreated)
c.writeResponse(rw, validCredential)
}
func (c *Operation) createProfileHandler(rw http.ResponseWriter, req *http.Request) {
data := ProfileRequest{}
err := json.NewDecoder(req.Body).Decode(&data)
if err != nil {
c.writeErrorResponse(rw, http.StatusBadRequest, "Failed to write response for invalid request received")
return
}
profileResponse, err := c.createProfile(&data)
if err != nil {
c.writeErrorResponse(rw, http.StatusBadRequest, err.Error())
return
}
rw.WriteHeader(http.StatusCreated)
c.writeResponse(rw, profileResponse)
}
func (c *Operation) getProfileHandler(rw http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
profileID := vars[profilePathVariable]
profileResponseJSON, err := c.profileStore.GetProfile(profileID)
if err != nil {
if err == errProfileNotFound {
c.writeErrorResponse(rw, http.StatusNotFound, "Failed to find the profile")
return
}
c.writeErrorResponse(rw, http.StatusBadRequest, err.Error())
return
}
c.writeResponse(rw, profileResponseJSON)
}
func createCredential(data *CreateCrendential) (*verifiable.Credential, error) {
credential := &verifiable.Credential{}
issueDate := time.Now().UTC()
credential.Context = []string{credentialContext}
credential.Subject = data.Subject
credential.Types = data.Type
credential.Issuer = data.Issuer
credential.Issued = &issueDate
// TODO to be replaced by getting profile ID issue-47
credential.ID = ID
cred, err := json.Marshal(credential)
if err != nil {
return nil, fmt.Errorf("create credential marshalling failed: %s", err.Error())
}
validatedCred, _, err := verifiable.NewCredential(cred)
if err != nil {
return nil, fmt.Errorf("failed to create new credential: %s", err.Error())
}
return validatedCred, nil
}
func (c *Operation) createProfile(pr *ProfileRequest) (*ProfileResponse, error) {
if pr.DID == "" {
return nil, fmt.Errorf("missing DID information")
}
if pr.URI == "" {
return nil, fmt.Errorf("missing URI information")
}
u, err := parseAndGetURI(pr.URI)
if err != nil {
return nil, err
}
issueDate := time.Now().UTC()
profileResponse := &ProfileResponse{
ID: uuid.New().String(),
URI: u,
IssueDate: &issueDate,
DID: pr.DID,
}
err = c.profileStore.SaveProfile(profileResponse)
if err != nil {
return nil, err
}
return profileResponse, nil
}
func parseAndGetURI(uri string) (string, error) {
u, err := url.Parse(uri)
if err != nil {
return "", fmt.Errorf("failed to parse the uri: %s", err.Error())
}
u.Path = path.Join(u.Path, uuid.New().String())
return u.String(), nil
}
// writeResponse writes interface value to response
func (c *Operation) writeResponse(rw io.Writer, v interface{}) {
err := json.NewEncoder(rw).Encode(v)
if err != nil {
log.Errorf("Unable to send error response, %s", err)
}
}
func (c *Operation) writeErrorResponse(rw http.ResponseWriter, status int, msg string) {
rw.WriteHeader(status)
if _, err := rw.Write([]byte(msg)); err != nil {
log.Errorf("Unable to send error message, %s", err)
}
}
// registerHandler register handlers to be exposed from this service as REST API endpoints
func (c *Operation) registerHandler() {
// Add more protocol endpoints here to expose them as controller API endpoints
c.handlers = []Handler{
support.NewHTTPHandler(createCredentialEndpoint, http.MethodPost, c.createCredentialHandler),
support.NewHTTPHandler(createProfileEndpoint, http.MethodPost, c.createProfileHandler),
support.NewHTTPHandler(getProfileEndpoint, http.MethodGet, c.getProfileHandler),
}
}
// GetRESTHandlers get all controller API handler available for this service
func (c *Operation) GetRESTHandlers() []Handler {
return c.handlers
}