| 2 |
raymond |
1 |
#pragma once
|
|
|
2 |
#include <Arduino.h>
|
|
|
3 |
#include <LittleFS.h>
|
|
|
4 |
|
|
|
5 |
#include <ArduinoJson.h> // https://github.com/bblanchon/ArduinoJson
|
|
|
6 |
#include <MySQL.h> // https://github.com/cotestatnt/Arduino-MySQL
|
|
|
7 |
#include <AsyncFsWebServer.h> // https://github.com/cotestatnt/async-esp-fs-webserver
|
|
|
8 |
#include "mbedtls/md.h"
|
|
|
9 |
|
|
|
10 |
#include "html_flash_files.h"
|
|
|
11 |
extern MySQL sql;
|
|
|
12 |
extern bool queryExecute(DataQuery_t&, const char*, ...);
|
|
|
13 |
|
|
|
14 |
// Webserver class
|
|
|
15 |
AsyncFsWebServer myWebServer(LittleFS, 80, "esp32rfid");
|
|
|
16 |
|
|
|
17 |
int getUserLevel(const String& user, const String& hash) {
|
|
|
18 |
DataQuery_t data;
|
|
|
19 |
if (queryExecute(data, "SELECT password, level FROM users WHERE username = '%s';", user)) {
|
|
|
20 |
sql.printResult(data, Serial);
|
|
|
21 |
if (hash.equals(data.getRowValue(0, "password")))
|
|
|
22 |
return atoi(data.getRowValue(0, "level"));
|
|
|
23 |
}
|
|
|
24 |
return 0;
|
|
|
25 |
}
|
|
|
26 |
|
|
|
27 |
|
|
|
28 |
String getSHA256(const char* payload) {
|
|
|
29 |
String hashed = "";
|
|
|
30 |
byte shaResult[32];
|
|
|
31 |
mbedtls_md_context_t ctx;
|
|
|
32 |
const size_t payloadLength = strlen(payload);
|
|
|
33 |
mbedtls_md_init(&ctx);
|
|
|
34 |
mbedtls_md_setup(&ctx, mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), 0);
|
|
|
35 |
mbedtls_md_starts(&ctx);
|
|
|
36 |
mbedtls_md_update(&ctx, (const unsigned char *) payload, payloadLength);
|
|
|
37 |
mbedtls_md_finish(&ctx, shaResult);
|
|
|
38 |
mbedtls_md_free(&ctx);
|
|
|
39 |
for(int i= 0; i< sizeof(shaResult); i++){
|
|
|
40 |
char str[3];
|
|
|
41 |
sprintf(str, "%02x", (int)shaResult[i]);
|
|
|
42 |
hashed += str;
|
|
|
43 |
}
|
|
|
44 |
return hashed;
|
|
|
45 |
}
|
|
|
46 |
|
|
|
47 |
|
|
|
48 |
void handleGetLogs(AsyncWebServerRequest *request) {
|
|
|
49 |
|
|
|
50 |
String filter;
|
|
|
51 |
if(request->hasArg("filter")) {
|
|
|
52 |
filter = request->arg("firstname");
|
|
|
53 |
}
|
|
|
54 |
|
|
|
55 |
String SQL = "SELECT * FROM logs ";
|
|
|
56 |
if (filter.length()) {
|
|
|
57 |
SQL += filter;
|
|
|
58 |
}
|
|
|
59 |
SQL += " ORDER BY epoch DESC LIMIT 30;";
|
|
|
60 |
Serial.println(SQL);
|
|
|
61 |
delay(100);
|
|
|
62 |
|
|
|
63 |
DataQuery_t data;
|
|
|
64 |
if (queryExecute(data, SQL.c_str())) {
|
|
|
65 |
sql.printResult(data, Serial);
|
|
|
66 |
|
|
|
67 |
JsonDocument doc;
|
|
|
68 |
JsonArray array = doc.to<JsonArray>();;
|
|
|
69 |
for (Record_t &row : data.records) {
|
|
|
70 |
JsonObject user = array.add<JsonObject>();
|
|
|
71 |
user["id"] = row.record[0];
|
|
|
72 |
user["epochTime"] = row.record[1];
|
|
|
73 |
user["username"] = row.record[2];
|
|
|
74 |
user["tagCode"] = row.record[3];
|
|
|
75 |
user["readerID"] = row.record[4];
|
|
|
76 |
}
|
|
|
77 |
String json;
|
|
|
78 |
serializeJsonPretty(doc, json);
|
|
|
79 |
request->send(200, "application/json", json);
|
|
|
80 |
return;
|
|
|
81 |
}
|
|
|
82 |
request->send(500, "text/plain", sql.getLastError());
|
|
|
83 |
}
|
|
|
84 |
|
|
|
85 |
void handleGetUsers(AsyncWebServerRequest *request) {
|
|
|
86 |
DataQuery_t data;
|
|
|
87 |
if (queryExecute(data, "SELECT id, username, name, email, tag_code, level FROM users")) {
|
|
|
88 |
sql.printResult(data, Serial);
|
|
|
89 |
|
|
|
90 |
JsonDocument doc;
|
|
|
91 |
JsonArray array = doc.to<JsonArray>();
|
|
|
92 |
for (Record_t &row : data.records) {
|
|
|
93 |
JsonObject user = array.add<JsonObject>();
|
|
|
94 |
user["id"] = row.record[0];
|
|
|
95 |
user["username"] = row.record[1];
|
|
|
96 |
user["name"] = row.record[2];
|
|
|
97 |
user["email"] = row.record[3];
|
|
|
98 |
user["tagCode"] = row.record[4];
|
|
|
99 |
user["level"] = row.record[5];
|
|
|
100 |
}
|
|
|
101 |
String json;
|
|
|
102 |
serializeJsonPretty(doc, json);
|
|
|
103 |
request->send(200, "application/json", json);
|
|
|
104 |
return;
|
|
|
105 |
}
|
|
|
106 |
request->send(500, "text/plain", sql.getLastError());
|
|
|
107 |
}
|
|
|
108 |
|
|
|
109 |
void handleNewUser(AsyncWebServerRequest *request) {
|
|
|
110 |
String user = request->arg("username");
|
|
|
111 |
String name = request->arg("name");
|
|
|
112 |
String email = request->arg("email");
|
|
|
113 |
String tagCode = request->arg("tagCode");
|
|
|
114 |
String level = request->arg("level");
|
|
|
115 |
String hashedPassword = getSHA256(request->arg("password").c_str());
|
|
|
116 |
|
|
|
117 |
DataQuery_t data;
|
|
|
118 |
if (queryExecute(data, newUpdateUser,
|
|
|
119 |
request->arg("username").c_str(), hashedPassword.c_str(), request->arg("name").c_str(),
|
|
|
120 |
request->arg("email").c_str(), request->arg("tagCode").c_str(), request->arg("level").c_str()))
|
|
|
121 |
{
|
|
|
122 |
request->send(200, "text/plain", "OK");
|
|
|
123 |
return;
|
|
|
124 |
}
|
|
|
125 |
request->send(500, "text/plain", sql.getLastError());
|
|
|
126 |
}
|
|
|
127 |
|
|
|
128 |
void handleRemoveUser(AsyncWebServerRequest *request) {
|
|
|
129 |
DataQuery_t data;
|
|
|
130 |
if (queryExecute(data, "DELETE FROM users WHERE username = '%s';", request->arg("username").c_str())) {
|
|
|
131 |
request->send(200, "text/plain", "OK");
|
|
|
132 |
return;
|
|
|
133 |
}
|
|
|
134 |
request->send(500, "text/plain", sql.getLastError());
|
|
|
135 |
}
|
|
|
136 |
|
|
|
137 |
void handleGetCode(AsyncWebServerRequest *request) {
|
|
|
138 |
uint32_t timeout = millis();
|
|
|
139 |
|
|
|
140 |
while (true) {
|
|
|
141 |
if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial()) {
|
|
|
142 |
uint64_t tagCode = 0;
|
|
|
143 |
|
|
|
144 |
// tagCode is swapped, but it doesn't matter We need only it's a unique number
|
|
|
145 |
for(byte i = 0; i < mfrc522.uid.size; i++) {
|
|
|
146 |
tagCode |= mfrc522.uid.uidByte[i] << (8*i);
|
|
|
147 |
}
|
|
|
148 |
|
|
|
149 |
// With 8 byte TAG code, the result integer could be too large since JavaScript
|
|
|
150 |
// uses 64-bit floating-point numbers (IEEE 754), which have a maximum precision of 2^53 - 1
|
|
|
151 |
String result = "{\"tagCode\": \"";
|
|
|
152 |
result += String(tagCode);
|
|
|
153 |
result += "\"}";
|
|
|
154 |
|
|
|
155 |
Serial.printf("Tag code: 0x%llX", tagCode);
|
|
|
156 |
request->send(200, "application/json", result);
|
|
|
157 |
addLogRecord = true;
|
|
|
158 |
return;
|
|
|
159 |
}
|
|
|
160 |
|
|
|
161 |
if (millis() - timeout > 5000) {
|
|
|
162 |
request->send(500, "application/json", "{\"error\": \"timeout\"}");
|
|
|
163 |
addLogRecord = true;
|
|
|
164 |
return;
|
|
|
165 |
}
|
|
|
166 |
}
|
|
|
167 |
}
|
|
|
168 |
|
|
|
169 |
// This handler will be called from login page to check password
|
|
|
170 |
void handleCheckHash(AsyncWebServerRequest *request) {
|
|
|
171 |
|
|
|
172 |
// Even if user con login, only user with level >= 5 can edit users table
|
|
|
173 |
if (getUserLevel(request->arg("username"), request->arg("hash"))) {
|
|
|
174 |
request->send(200, "text/plain", "OK");
|
|
|
175 |
}
|
|
|
176 |
else {
|
|
|
177 |
request->send(401, "text/plain", "Wrong password");
|
|
|
178 |
}
|
|
|
179 |
}
|
|
|
180 |
|
|
|
181 |
// This handler will be called from login page on login succesfull
|
|
|
182 |
void handleMainPage(AsyncWebServerRequest *request) {
|
|
|
183 |
// Check again user and password to avoid direct page loading
|
|
|
184 |
int level = getUserLevel(request->arg("username"), request->arg("hash"));
|
|
|
185 |
if (level) {
|
|
|
186 |
// Even if any user con login succesfully, only user with level >= 5 can edit users table
|
|
|
187 |
// Username and user level is set here using cookie.
|
|
|
188 |
String cookie = "username=" ;
|
|
|
189 |
cookie += request->arg("username");
|
|
|
190 |
cookie += ","; cookie += level; cookie += "; Path=/";
|
|
|
191 |
AsyncWebServerResponse *response = request->beginResponse(200, "text/html", (const uint8_t*)index_htm, sizeof(index_htm));
|
|
|
192 |
response->addHeader("Set-Cookie", cookie);
|
|
|
193 |
request->send(response);
|
|
|
194 |
}
|
|
|
195 |
else {
|
|
|
196 |
request->send(401, "text/plain", "Wrong password");
|
|
|
197 |
}
|
|
|
198 |
}
|
|
|
199 |
|
|
|
200 |
|
|
|
201 |
//////////////////// Load application options from filesystem ////////////////////
|
|
|
202 |
bool loadOptions() {
|
|
|
203 |
if (LittleFS.exists(myWebServer.getConfiFileName())) {
|
|
|
204 |
myWebServer.getOptionValue(MY_SQL_HOST, dbHost);
|
|
|
205 |
myWebServer.getOptionValue(MY_SQL_PORT, dbPort);
|
|
|
206 |
myWebServer.getOptionValue(MY_SQL_DB, database);
|
|
|
207 |
myWebServer.getOptionValue(MY_SQL_USER, user);
|
|
|
208 |
myWebServer.getOptionValue(MY_SQL_PASS, password);
|
|
|
209 |
Serial.printf(MY_SQL_HOST ": %s\n", dbHost.c_str());
|
|
|
210 |
Serial.printf(MY_SQL_PORT ": %d\n", dbPort);
|
|
|
211 |
Serial.printf(MY_SQL_DB ": %s\n", database.c_str());
|
|
|
212 |
Serial.printf(MY_SQL_USER ": %s\n", user.c_str());
|
|
|
213 |
Serial.printf(MY_SQL_PASS ": %s\n", password.c_str());
|
|
|
214 |
return true;
|
|
|
215 |
}
|
|
|
216 |
else
|
|
|
217 |
Serial.printf("File \"%s\" not exist\n", myWebServer.getConfiFileName());
|
|
|
218 |
return false;
|
|
|
219 |
}
|
|
|
220 |
|
|
|
221 |
//////////////////////////////// Filesystem /////////////////////////////////////////
|
|
|
222 |
|
|
|
223 |
// Configure and start webserver
|
|
|
224 |
bool startWebServer(bool clear = false) {
|
|
|
225 |
bool connected = false;
|
|
|
226 |
// FILESYSTEM INIT
|
|
|
227 |
if (!LittleFS.begin()) {
|
|
|
228 |
Serial.println("ERROR on mounting filesystem. It will be formmatted!");
|
|
|
229 |
LittleFS.format();
|
|
|
230 |
ESP.restart();
|
|
|
231 |
}
|
|
|
232 |
|
|
|
233 |
if (clear) {
|
|
|
234 |
LittleFS.remove(myWebServer.getConfiFileName());
|
|
|
235 |
}
|
|
|
236 |
|
|
|
237 |
// Load configuration (if not present, default will be created when webserver will start)
|
|
|
238 |
Serial.println("Load application otions:");
|
|
|
239 |
if (!loadOptions()) Serial.println("Error!! Options NOT loaded!");
|
|
|
240 |
Serial.println();
|
|
|
241 |
|
|
|
242 |
// Try to connect to WiFi (will start AP if not connected after timeout)
|
|
|
243 |
if (!myWebServer.startWiFi(20000)) {
|
|
|
244 |
Serial.println("\nWiFi not connected! Starting AP mode...");
|
|
|
245 |
myWebServer.startCaptivePortal("ESP32_LOGGER", "", "/setup");
|
|
|
246 |
}
|
|
|
247 |
else
|
|
|
248 |
connected = true;
|
|
|
249 |
|
|
|
250 |
// Configure /setup page and start Web Server
|
|
|
251 |
myWebServer.addOptionBox("MySQL setup");
|
|
|
252 |
myWebServer.addOption(MY_SQL_HOST, dbHost);
|
|
|
253 |
myWebServer.addOption(MY_SQL_PORT, dbPort);
|
|
|
254 |
myWebServer.addOption(MY_SQL_DB, database);
|
|
|
255 |
myWebServer.addOption(MY_SQL_USER, user);
|
|
|
256 |
myWebServer.addOption(MY_SQL_PASS, password);
|
|
|
257 |
|
|
|
258 |
// Add endpoints request handlers
|
|
|
259 |
myWebServer.on("/logs", HTTP_ANY, handleGetLogs);
|
|
|
260 |
myWebServer.on("/users", HTTP_GET, handleGetUsers);
|
|
|
261 |
myWebServer.on("/addUser", HTTP_POST, handleNewUser);
|
|
|
262 |
myWebServer.on("/deleUser", HTTP_POST, handleRemoveUser);
|
|
|
263 |
myWebServer.on("/getCode", HTTP_GET, handleGetCode);
|
|
|
264 |
myWebServer.on("/waitCode", HTTP_GET, [](AsyncWebServerRequest *request){
|
|
|
265 |
addLogRecord = false;
|
|
|
266 |
request->send(200, "text/plain", "OK");
|
|
|
267 |
});
|
|
|
268 |
|
|
|
269 |
/*
|
|
|
270 |
* To avoid ugly and basic login prompt avalaible with "stardard" DIGEST_AUTH
|
|
|
271 |
* let's use a custom login web page (from flash literal string). This web page
|
|
|
272 |
* will send a POST request to /rfid enpoint passing username and password SHA256 hash
|
|
|
273 |
*/
|
|
|
274 |
myWebServer.on("/", HTTP_ANY, [](AsyncWebServerRequest *request){
|
|
|
275 |
request->send(200, "text/html", (const uint8_t*)login_htm, sizeof(login_htm));
|
|
|
276 |
});
|
|
|
277 |
myWebServer.on("/login", HTTP_ANY, [](AsyncWebServerRequest *request){
|
|
|
278 |
request->send(200, "text/html", (const uint8_t*)login_htm, sizeof(login_htm));
|
|
|
279 |
});
|
|
|
280 |
myWebServer.on("/rfid", HTTP_POST, handleCheckHash);
|
|
|
281 |
/*
|
|
|
282 |
* If client calculated password SHA256 hash string match with the user DB stored
|
|
|
283 |
* we can serve the /rfid web page (from flash literal string, same as login page)
|
|
|
284 |
*/
|
|
|
285 |
myWebServer.on("/rfid", HTTP_GET, handleMainPage);
|
|
|
286 |
|
|
|
287 |
// To enable add/edit/delete buttons, user must be admin (level >= 5)
|
|
|
288 |
myWebServer.on("/userLevel", HTTP_GET, [](AsyncWebServerRequest *request){
|
|
|
289 |
DataQuery_t data;
|
|
|
290 |
if (queryExecute(data, "SELECT password, level FROM users WHERE username = '%s';", request->arg("username"))) {
|
|
|
291 |
String cookie = "user_level=" + String(data.getRowValue(0, "level")) + "; Path=/";
|
|
|
292 |
AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", "OK");
|
|
|
293 |
response->addHeader("Set-Cookie", cookie);
|
|
|
294 |
request->send(response);
|
|
|
295 |
}
|
|
|
296 |
});
|
|
|
297 |
|
|
|
298 |
// Enable ACE FS file web editor and add FS info callback function
|
|
|
299 |
myWebServer.enableFsCodeEditor();
|
|
|
300 |
|
|
|
301 |
// Start the webserver
|
|
|
302 |
myWebServer.init();
|
|
|
303 |
Serial.print("\n\nESP Web Server started on IP Address: ");
|
|
|
304 |
Serial.println(myWebServer.getServerIP());
|
|
|
305 |
Serial.println(
|
|
|
306 |
"Open /setup page to configure optional parameters.\n"
|
|
|
307 |
"Open /edit page to view, edit or upload example or your custom webserver source files."
|
|
|
308 |
);
|
|
|
309 |
|
|
|
310 |
return connected;
|
|
|
311 |
}
|