forked from stellar/go
-
Notifications
You must be signed in to change notification settings - Fork 6
/
auth_handler.go
108 lines (90 loc) · 2.41 KB
/
auth_handler.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
package compliance
import (
"encoding/json"
"net/http"
complianceProtocol "github.com/stellar/go/protocols/compliance"
"github.com/stellar/go/support/errors"
"github.com/stellar/go/support/log"
)
func (h *AuthHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
authRequest := &complianceProtocol.AuthRequest{}
authRequest.Populate(r)
// Validate request
err := authRequest.Validate()
if err != nil {
h.writeJSON(w, ErrorResponse{
Code: "invalid_request",
Message: err.Error(),
}, http.StatusBadRequest)
return
}
authData, err := authRequest.Data()
if err != nil {
h.writeJSON(w, ErrorResponse{
Code: "invalid_data",
Message: err.Error(),
}, http.StatusBadRequest)
return
}
err = authRequest.VerifySignature(authData.Sender)
if err != nil {
h.writeJSON(w, ErrorResponse{
Code: "invalid_signature",
Message: err.Error(),
}, http.StatusBadRequest)
return
}
// Create response
response := &complianceProtocol.AuthResponse{}
// Sanctions check
err = h.Strategy.SanctionsCheck(authData, response)
if err != nil {
h.writeError(w, err)
return
}
// User info
err = h.Strategy.GetUserData(authData, response)
if err != nil {
h.writeError(w, err)
return
}
// If transaction allowed, persist it for future reference
if response.TxStatus == complianceProtocol.AuthStatusOk && response.InfoStatus == complianceProtocol.AuthStatusOk {
err = h.PersistTransaction(authData)
if err != nil {
h.writeError(w, err)
return
}
}
h.writeJSON(w, response, http.StatusOK)
}
/////////////////////////////////////////////////////////////
// Everything below copied from handlers/federation. We should probably move it
// to some `common` package.
// ErrorResponse represents the JSON response sent to a client when the request
// triggered an error.
type ErrorResponse struct {
Code string `json:"code"`
Message string `json:"message"`
}
func (h *AuthHandler) writeJSON(
w http.ResponseWriter,
obj interface{},
status int,
) {
json, err := json.Marshal(obj)
if err != nil {
h.writeError(w, errors.Wrap(err, "response marshal"))
return
}
if status == 0 {
status = http.StatusOK
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
w.Write(json)
}
func (h *AuthHandler) writeError(w http.ResponseWriter, err error) {
log.Error(err)
http.Error(w, "An internal error occurred", http.StatusInternalServerError)
}