-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathjson.cpp
More file actions
106 lines (84 loc) · 2.27 KB
/
Copy pathjson.cpp
File metadata and controls
106 lines (84 loc) · 2.27 KB
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
#include "http/json.h"
#include <cstring>
#include "settings/settings.h"
namespace {
void sendCorsHeaders(WebServer& server) {
server.sendHeader("Access-Control-Allow-Origin", "*");
server.sendHeader("Access-Control-Allow-Headers", "Authorization");
server.sendHeader(
"Access-Control-Allow-Methods",
"GET, POST, OPTIONS"
);
}
void sendWithCors(WebServer& server, int code, const char* type, const char* body) {
sendCorsHeaders(server);
server.send(code, type, body);
}
bool bearerTokenMatches(const String& header, const char* expected) {
constexpr const char* kPrefix = "Bearer ";
constexpr size_t kPrefixLen = 7;
if (header.length() < kPrefixLen) {
return false;
}
for (size_t i = 0; i < kPrefixLen; i++) {
if (header[i] != kPrefix[i]) {
return false;
}
}
const char* presented = header.c_str() + kPrefixLen;
return strcmp(presented, expected) == 0;
}
} // namespace
void httpSendJson(WebServer& server, int code, const char* body) {
sendWithCors(server, code, "application/json", body);
}
void httpSendHtml(WebServer& server, int code, const char* body) {
sendCorsHeaders(server);
// send() copies into Arduino String and fails on the large panel.
server.send_P(code, "text/html; charset=utf-8", body);
}
void httpSendCorsPreflight(WebServer& server) {
sendCorsHeaders(server);
server.send(204);
}
bool httpRequireApiAuth(WebServer& server) {
if (!settingsAccessTokenSet()) {
return true;
}
if (!server.hasHeader("Authorization") ||
!bearerTokenMatches(
server.header("Authorization"),
settingsAccessToken()
)) {
httpSendJson(
server,
401,
"{\"ok\":false,\"error\":\"unauthorized\"}"
);
return false;
}
return true;
}
bool httpRequireWifiConfigured(WebServer& server) {
if (settingsWifiConfigured()) {
return true;
}
httpSendJson(
server,
503,
"{\"ok\":false,\"error\":\"wifi not configured\"}"
);
return false;
}
void httpWithApiAuth(WebServer& server, void (*handler)(WebServer&)) {
if (!httpRequireApiAuth(server)) {
return;
}
handler(server);
}
void httpWithWifiAndApiAuth(WebServer& server, void (*handler)(WebServer&)) {
if (!httpRequireWifiConfigured(server)) {
return;
}
httpWithApiAuth(server, handler);
}