/
router.go
207 lines (180 loc) · 5.06 KB
/
router.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
package api
import (
"encoding/json"
"fmt"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"github.com/application-research/edge-ur/core"
logging "github.com/ipfs/go-log/v2"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"golang.org/x/xerrors"
)
var (
OsSignal chan os.Signal
log = logging.Logger("router")
)
type HttpError struct {
Code int `json:"code,omitempty"`
Reason string `json:"reason"`
Details string `json:"details"`
}
func (he HttpError) Error() string {
if he.Details == "" {
return he.Reason
}
return he.Reason + ": " + he.Details
}
type HttpErrorResponse struct {
Error HttpError `json:"error"`
}
type AuthResponse struct {
Result struct {
Validated bool `json:"validated"`
Details string `json:"details"`
} `json:"result"`
}
// RouterConfig configures the API node
func InitializeEchoRouterConfig(ln *core.LightNode) {
// Echo instance
// Echo instance
e := echo.New()
e.File("/", "templates/index.html")
// Middleware
e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
AllowOrigins: []string{"*"},
}))
e.Pre(middleware.RemoveTrailingSlash())
e.HTTPErrorHandler = ErrorHandler
defaultOpenRoute := e.Group("")
ConfigureGatewayRouter(defaultOpenRoute, ln) // access to light node
ConfigureStatsRouter(defaultOpenRoute, ln)
ConfigureHealthCheckRouter(defaultOpenRoute, ln)
ConfigureNodeInfoRouter(defaultOpenRoute, ln)
apiGroup := e.Group("/api/v1")
apiGroup.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
authorizationString := c.Request().Header.Get("Authorization")
authParts := strings.Split(authorizationString, " ")
if len(authParts) != 2 {
return c.JSON(http.StatusInternalServerError, HttpErrorResponse{
Error: HttpError{
Code: http.StatusInternalServerError,
Reason: http.StatusText(http.StatusInternalServerError),
Details: "Invalid Authorization Header",
},
})
}
response, err := http.Post(
"https://estuary-auth-api.onrender.com/check-api-key",
"application/json",
strings.NewReader(fmt.Sprintf(`{"token": "%s"}`, authParts[1])),
)
if err != nil {
log.Errorf("handler error: %s", err)
return c.JSON(http.StatusInternalServerError, HttpErrorResponse{
Error: HttpError{
Code: http.StatusInternalServerError,
Reason: http.StatusText(http.StatusInternalServerError),
Details: err.Error(),
},
})
}
authResp, err := GetAuthResponse(response)
if err != nil {
log.Errorf("handler error: %s", err)
return c.JSON(http.StatusInternalServerError, HttpErrorResponse{
Error: HttpError{
Code: http.StatusInternalServerError,
Reason: http.StatusText(http.StatusInternalServerError),
Details: err.Error(),
},
})
}
if authResp.Result.Validated == false {
return c.JSON(http.StatusUnauthorized, HttpErrorResponse{
Error: HttpError{
Code: http.StatusUnauthorized,
Reason: http.StatusText(http.StatusUnauthorized),
Details: authResp.Result.Details,
},
})
}
if authResp.Result.Validated == true {
return next(c)
}
return next(c)
}
})
ConfigureRetrieveRouter(apiGroup, ln)
ConfigurePinningRouter(apiGroup, ln)
ConfigureStatusCheckRouter(apiGroup, ln)
// Start server
addrPort := fmt.Sprintf("0.0.0.0:%d", ln.Config.Node.Port)
e.Logger.Fatal(e.Start(addrPort)) // configuration
}
func GetAuthResponse(resp *http.Response) (AuthResponse, error) {
jsonBody := AuthResponse{}
err := json.NewDecoder(resp.Body).Decode(&jsonBody)
if err != nil {
log.Error("empty json body")
return AuthResponse{
Result: struct {
Validated bool `json:"validated"`
Details string `json:"details"`
}{
Validated: false,
Details: "empty json body",
},
}, nil
}
return jsonBody, nil
}
func ErrorHandler(err error, c echo.Context) {
var httpRespErr *HttpError
if xerrors.As(err, &httpRespErr) {
log.Errorf("handler error: %s", err)
if err := c.JSON(httpRespErr.Code, HttpErrorResponse{Error: *httpRespErr}); err != nil {
log.Errorf("handler error: %s", err)
return
}
return
}
var echoErr *echo.HTTPError
if xerrors.As(err, &echoErr) {
if err := c.JSON(echoErr.Code, HttpErrorResponse{
Error: HttpError{
Code: echoErr.Code,
Reason: http.StatusText(echoErr.Code),
Details: echoErr.Message.(string),
},
}); err != nil {
log.Errorf("handler error: %s", err)
return
}
return
}
log.Errorf("handler error: %s", err)
if err := c.JSON(http.StatusInternalServerError, HttpErrorResponse{
Error: HttpError{
Code: http.StatusInternalServerError,
Reason: http.StatusText(http.StatusInternalServerError),
Details: err.Error(),
},
}); err != nil {
log.Errorf("handler error: %s", err)
return
}
}
// LoopForever on signal processing
func LoopForever() {
fmt.Printf("Entering infinite loop\n")
signal.Notify(OsSignal, syscall.SIGINT, syscall.SIGTERM, syscall.SIGUSR1)
_ = <-OsSignal
fmt.Printf("Exiting infinite loop received OsSignal\n")
}