/
http.go
515 lines (429 loc) · 13.1 KB
/
http.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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
package auth
import (
"crypto/sha512"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/omecodes/store/common"
pb "github.com/omecodes/store/gen/go/proto"
"net/http"
"net/url"
"strings"
"github.com/gorilla/mux"
"github.com/omecodes/errors"
"github.com/omecodes/libome/logs"
"github.com/omecodes/store/session"
)
func MuxRouter(middleware ...mux.MiddlewareFunc) http.Handler {
r := mux.NewRouter()
r.Name("SaveAuthProvider").Methods(http.MethodPut).Path(common.ApiSaveAuthProviderRoute).Handler(http.HandlerFunc(SaveProvider))
r.Name("GetAuthProvider").Methods(http.MethodGet).Path(common.ApiGetAuthProviderRoute).Handler(http.HandlerFunc(GetProvider))
r.Name("DeleteAuthProvider").Methods(http.MethodDelete).Path(common.ApiDeleteAuthProviderRoute).Handler(http.HandlerFunc(DeleteProvider))
r.Name("ListProviders").Methods(http.MethodGet).Path(common.ApiListAuthProvidersRoute).Handler(http.HandlerFunc(ListProviders))
r.Name("SaveClientApp").Methods(http.MethodPut).Path(common.ApiSaveClientAppRoute).Handler(http.HandlerFunc(SaveClientApp))
r.Name("GetClientApp").Methods(http.MethodPut).Path(common.ApiGetClientAppRoute).Handler(http.HandlerFunc(GetClientApp))
r.Name("ListClientApps").Methods(http.MethodGet).Path(common.ApiListClientAppsRoute).Handler(http.HandlerFunc(ListClientApps))
r.Name("DeleteClientApp").Methods(http.MethodDelete).Path(common.ApiDeleteClientAppRoute).Handler(http.HandlerFunc(DeleteClientApp))
r.Name("InitWebClientSession").Methods(http.MethodPost).Path(common.ApiCreateAppSessionRoute).Handler(http.HandlerFunc(InitClientAppSession))
r.Name("CreateUser").Methods(http.MethodPut).Path(common.ApiCreateUserRoute).Handler(http.HandlerFunc(SaveUser))
r.Name("SearchUser").Methods(http.MethodGet).Path(common.ApiSearchUsersRoute).Handler(http.HandlerFunc(SearchUsers))
var handler http.Handler
handler = r
for _, m := range middleware {
handler = m(handler)
}
return handler
}
func UserSessionHandler(middleware ...mux.MiddlewareFunc) http.Handler {
var handler http.Handler
handler = http.HandlerFunc(CreateUserWebSession)
for _, m := range middleware {
handler = m(handler)
}
return handler
}
func redirectToLocation(w http.ResponseWriter, status int, location string, params url.Values) {
if params != nil {
location += "&" + params.Encode()
}
b := strings.Builder{}
b.WriteString(fmt.Sprintf("<head>\n"))
b.WriteString(fmt.Sprintf("\t<meta http-equiv=\"refresh\" content=\"0; URL=%s\" />\n", location))
b.WriteString(fmt.Sprintf("</head>"))
contentBytes := []byte(b.String())
w.Header().Set(common.HttpHeaderContentType, "text/html")
w.Header().Set("Location", location)
w.WriteHeader(status)
_, _ = w.Write(contentBytes)
}
func SaveProvider(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
user := Get(ctx)
if user == nil || user.Name != "admin" {
w.WriteHeader(http.StatusForbidden)
return
}
var provider *Provider
err := json.NewDecoder(r.Body).Decode(&provider)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
if provider.Config == nil || provider.Name == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
providers := GetProviders(ctx)
if providers == nil {
logs.Error("missing providers manager in context")
w.WriteHeader(http.StatusInternalServerError)
return
}
err = providers.Save(provider)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
}
func GetProvider(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
user := Get(ctx)
if user == nil {
w.WriteHeader(http.StatusForbidden)
return
}
vars := mux.Vars(r)
providers := GetProviders(ctx)
if providers == nil {
logs.Error("missing providers manager in context")
w.WriteHeader(http.StatusInternalServerError)
return
}
providerId := vars[common.ApiRouteVarIdName]
provider, err := providers.Get(providerId)
if err != nil {
logs.Error("failed to get provider", logs.Details("id", providerId), logs.Err(err))
w.WriteHeader(errors.HTTPStatus(err))
return
}
if user.Name != "admin" {
provider.Config = nil
}
err = json.NewEncoder(w).Encode(provider)
if err != nil {
logs.Error("failed to send provider as response", logs.Err(err))
}
}
func DeleteProvider(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
user := Get(ctx)
if user == nil || user.Name != "admin" {
w.WriteHeader(http.StatusForbidden)
return
}
providers := GetProviders(ctx)
if providers == nil {
logs.Error("missing providers manager in context")
w.WriteHeader(http.StatusInternalServerError)
return
}
vars := mux.Vars(r)
providerId := vars[common.ApiRouteVarIdName]
err := providers.Delete(providerId)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
}
func ListProviders(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
user := Get(ctx)
if user == nil {
w.WriteHeader(http.StatusForbidden)
return
}
vars := mux.Vars(r)
providers := GetProviders(ctx)
if providers == nil {
logs.Error("missing providers manager in context")
w.WriteHeader(http.StatusInternalServerError)
return
}
providerId := vars[common.ApiRouteVarIdName]
providerList, err := providers.GetAll(user.Name != "admin")
if err != nil {
logs.Error("failed to get provider", logs.Details("id", providerId), logs.Err(err))
w.WriteHeader(errors.HTTPStatus(err))
return
}
err = json.NewEncoder(w).Encode(providerList)
if err != nil {
logs.Error("failed to send provider as response", logs.Err(err))
}
}
func SaveClientApp(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
user := Get(ctx)
if user == nil || user.Name != "admin" {
w.WriteHeader(http.StatusForbidden)
return
}
var access *pb.ClientApp
err := json.NewDecoder(r.Body).Decode(&access)
if err != nil {
logs.Error("failed to decode request body", logs.Err(err))
return
}
manager := GetCredentialsManager(ctx)
if manager == nil {
logs.Error("missing credentials manager in context")
w.WriteHeader(http.StatusInternalServerError)
return
}
err = manager.SaveClientApp(access)
if err != nil {
logs.Error("failed to save access", logs.Err(err))
w.WriteHeader(errors.HTTPStatus(err))
return
}
}
func GetClientApp(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
user := Get(ctx)
if user == nil || user.Name != "admin" {
w.WriteHeader(http.StatusForbidden)
return
}
var access *pb.ClientApp
err := json.NewDecoder(r.Body).Decode(&access)
if err != nil {
logs.Error("failed to decode request body", logs.Err(err))
return
}
manager := GetCredentialsManager(ctx)
if manager == nil {
logs.Error("missing credentials manager in context")
w.WriteHeader(http.StatusInternalServerError)
return
}
err = manager.SaveClientApp(access)
if err != nil {
logs.Error("failed to save access", logs.Err(err))
w.WriteHeader(errors.HTTPStatus(err))
return
}
}
func ListClientApps(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
user := Get(ctx)
if user == nil || user.Name != "admin" {
w.WriteHeader(http.StatusForbidden)
return
}
manager := GetCredentialsManager(ctx)
if manager == nil {
logs.Error("missing credentials manager in context")
w.WriteHeader(http.StatusInternalServerError)
return
}
accesses, err := manager.GetAllClientApps()
if err != nil {
logs.Error("failed to get access", logs.Err(err))
w.WriteHeader(errors.HTTPStatus(err))
return
}
err = json.NewEncoder(w).Encode(accesses)
if err != nil {
logs.Error("failed to send provider as response", logs.Err(err))
}
}
func DeleteClientApp(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
user := Get(ctx)
if user == nil || user.Name != "admin" {
w.WriteHeader(http.StatusForbidden)
return
}
vars := mux.Vars(r)
accessId := vars[common.ApiRouteVarIdName]
manager := GetCredentialsManager(ctx)
if manager == nil {
logs.Error("missing credentials manager in context")
w.WriteHeader(http.StatusInternalServerError)
return
}
err := manager.DeleteClientApp(accessId)
if err != nil {
logs.Error("could not get access", logs.Err(err))
w.WriteHeader(http.StatusNotFound)
return
}
}
func SaveUser(w http.ResponseWriter, r *http.Request) {
var user *pb.UserCredentials
ctx := r.Context()
requester := Get(ctx)
if requester == nil || requester.Name != "admin" {
w.WriteHeader(http.StatusForbidden)
return
}
err := json.NewDecoder(r.Body).Decode(&user)
if err != nil {
logs.Error("could not decode request data")
w.WriteHeader(http.StatusBadRequest)
return
}
if user.Username == "" || user.Password == "" {
logs.Error("username or password is empty")
w.WriteHeader(http.StatusBadRequest)
return
}
manager := GetCredentialsManager(ctx)
if manager == nil {
logs.Error("missing credentials manager in context")
w.WriteHeader(http.StatusInternalServerError)
return
}
hashedBytes := sha512.Sum512([]byte(user.Password))
user.Password = hex.EncodeToString(hashedBytes[:])
err = manager.SaveUserCredentials(user)
if err != nil {
logs.Error("could not save user", logs.Err(err))
w.WriteHeader(http.StatusInternalServerError)
return
}
}
func SearchUsers(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
requester := Get(ctx)
if requester == nil || requester.Name == "" {
w.WriteHeader(http.StatusForbidden)
return
}
query := r.URL.Query().Get("q")
if query == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
manager := GetCredentialsManager(ctx)
if manager == nil {
logs.Error("missing credentials manager in context")
w.WriteHeader(http.StatusInternalServerError)
return
}
}
func CreateUserWebSession(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
clientApp := App(ctx)
if clientApp == nil {
w.WriteHeader(http.StatusForbidden)
return
}
if clientApp.Type != pb.ClientType_web {
w.WriteHeader(http.StatusUnauthorized)
return
}
manager := GetCredentialsManager(ctx)
if manager == nil {
logs.Error("missing credentials manager in context")
w.WriteHeader(http.StatusInternalServerError)
return
}
continueURL := r.URL.Query().Get(common.ApiParamContinueURL)
if continueURL == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
err := r.ParseForm()
if err != nil {
logs.Error("could not parse form", logs.Err(err))
w.WriteHeader(http.StatusBadRequest)
return
}
username := r.Form.Get(common.ApiParamUsername)
password := r.Form.Get(common.ApiParamPassword)
logs.Info("login", logs.Details("username", username), logs.Details("password", password))
loadedPassword, err := manager.GetUserPassword(username)
if err != nil {
if errors.IsNotFound(err) {
redirectToLocation(w, http.StatusForbidden, continueURL, nil)
} else {
redirectToLocation(w, errors.HTTPStatus(err), continueURL, nil)
}
return
}
hashedBytes := sha512.Sum512([]byte(password))
password = hex.EncodeToString(hashedBytes[:])
if loadedPassword != password {
redirectToLocation(w, http.StatusForbidden, continueURL, nil)
return
}
userSession, err := session.GetWebSession(session.UserSession, r)
if err != nil {
logs.Error("could not initialize client app session", logs.Err(err))
redirectToLocation(w, errors.HTTPStatus(err), continueURL, nil)
return
}
userSession.Put(session.KeyUsername, username)
err = userSession.Save(w)
if err != nil {
logs.Error("could not save client app session", logs.Err(err))
redirectToLocation(w, errors.HTTPStatus(err), continueURL, nil)
return
}
redirectToLocation(w, http.StatusOK, continueURL, nil)
}
func InitClientAppSession(w http.ResponseWriter, r *http.Request) {
var requestData *InitClientAppSessionRequest
err := json.NewDecoder(r.Body).Decode(&requestData)
if err != nil {
logs.Error("could not decode request data", logs.Err(err))
w.WriteHeader(http.StatusBadRequest)
return
}
if requestData.ClientApp == nil {
logs.Error("missing client app data in request")
w.WriteHeader(http.StatusBadRequest)
return
}
manager := GetCredentialsManager(r.Context())
if manager == nil {
logs.Error("missing credentials manager in context")
w.WriteHeader(http.StatusInternalServerError)
return
}
clientApp, err := manager.GetClientApp(requestData.ClientApp.Key)
if err != nil {
logs.Error("could not load access", logs.Details("", requestData.ClientApp.Key), logs.Err(err))
w.WriteHeader(errors.HTTPStatus(err))
return
}
if clientApp.Secret != requestData.ClientApp.Secret {
logs.Error("client app authentication failed", logs.Err(err))
w.WriteHeader(http.StatusForbidden)
return
}
caSession, err := session.GetWebSession(session.ClientAppSession, r)
if err != nil {
logs.Error("could not initialize client app session", logs.Err(err))
w.WriteHeader(http.StatusInternalServerError)
return
}
if clientApp.Info != nil {
encodedInfo, err := json.Marshal(clientApp.Info)
if err != nil {
logs.Error("could not encode client app info", logs.Err(err))
w.WriteHeader(http.StatusInternalServerError)
return
}
caSession.Put(session.KeyAccessInfo, string(encodedInfo))
}
caSession.Put(session.KeyAccessType, clientApp.Type.String())
caSession.Put(session.KeyAccessKey, clientApp.Key)
err = caSession.Save(w)
if err != nil {
logs.Error("could not save client app session", logs.Err(err))
w.WriteHeader(errors.HTTPStatus(err))
return
}
}