@brief Check Basic Authentication for HTTP request @param req HTTP request handle @param password Expected password @return true if authentication successful, false otherwise
| 355 | /// @param password Expected password |
| 356 | /// @return true if authentication successful, false otherwise |
| 357 | bool checkBasicAuth(httpd_req_t *req, const char* password) { |
| 358 | // Check Basic Auth |
| 359 | size_t auth_len = httpd_req_get_hdr_value_len(req, "Authorization"); |
| 360 | if (auth_len == 0) { |
| 361 | // No auth header, request authentication |
| 362 | httpd_resp_set_hdr(req, "WWW-Authenticate", "Basic realm=\"OTA Update\""); |
| 363 | httpd_resp_send_err(req, HTTPD_401_UNAUTHORIZED, "Authentication required"); |
| 364 | return false; |
| 365 | } |
| 366 | |
| 367 | // Get the auth header value |
| 368 | char* auth_value = (char*)malloc(auth_len + 1); // ok bare allocation |
| 369 | if (!auth_value) { |
| 370 | httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Memory allocation failed"); |
| 371 | return false; |
| 372 | } |
| 373 | |
| 374 | if (httpd_req_get_hdr_value_str(req, "Authorization", auth_value, auth_len + 1) != ESP_OK) { |
| 375 | free(auth_value); // ok bare allocation |
| 376 | httpd_resp_send_err(req, HTTPD_401_UNAUTHORIZED, "Invalid authentication"); |
| 377 | return false; |
| 378 | } |
| 379 | |
| 380 | // Verify Basic Auth format: "Basic <base64>" |
| 381 | if (strncmp(auth_value, "Basic ", 6) != 0) { |
| 382 | free(auth_value); // ok bare allocation |
| 383 | httpd_resp_set_hdr(req, "WWW-Authenticate", "Basic realm=\"OTA Update\""); |
| 384 | httpd_resp_send_err(req, HTTPD_401_UNAUTHORIZED, "Invalid authentication format"); |
| 385 | return false; |
| 386 | } |
| 387 | |
| 388 | // Decode Base64 credentials |
| 389 | char decoded[256]; |
| 390 | int decoded_len = decodeBase64(auth_value + 6, decoded, sizeof(decoded)); |
| 391 | free(auth_value); // ok bare allocation |
| 392 | |
| 393 | if (decoded_len < 0) { |
| 394 | httpd_resp_set_hdr(req, "WWW-Authenticate", "Basic realm=\"OTA Update\""); |
| 395 | httpd_resp_send_err(req, HTTPD_401_UNAUTHORIZED, "Invalid Base64 encoding"); |
| 396 | return false; |
| 397 | } |
| 398 | |
| 399 | // Expected format: "admin:password" |
| 400 | // Find the colon separator |
| 401 | char* colon = strchr(decoded, ':'); |
| 402 | if (!colon) { |
| 403 | httpd_resp_set_hdr(req, "WWW-Authenticate", "Basic realm=\"OTA Update\""); |
| 404 | httpd_resp_send_err(req, HTTPD_401_UNAUTHORIZED, "Invalid credentials format"); |
| 405 | return false; |
| 406 | } |
| 407 | |
| 408 | // Split username and password |
| 409 | *colon = '\0'; |
| 410 | const char* username = decoded; |
| 411 | const char* user_password = colon + 1; |
| 412 | |
| 413 | // Verify username is "admin" and password matches |
| 414 | if (strcmp(username, "admin") != 0 || strcmp(user_password, password) != 0) { |