Skip to content

Commit

Permalink
feat: authentication support (#15)
Browse files Browse the repository at this point in the history
  • Loading branch information
mathieucarbou committed Dec 14, 2023
1 parent b95e0eb commit f9b2289
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
14 changes: 12 additions & 2 deletions src/WebSerial.cpp
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
#include "WebSerialLite.h"
#include "WebSerialWebPage.h"

void WebSerialClass::begin(AsyncWebServer *server, const char *url) {
void WebSerialClass::begin(AsyncWebServer *server, const char *url, const String &username, const String &password) {
_server = server;
_server->on(url, HTTP_GET, [](AsyncWebServerRequest *request) {
_username = username;
_password = password;
_auth = !_username.isEmpty() && !_password.isEmpty();

_server->on(url, HTTP_GET, [this](AsyncWebServerRequest *request) {
if(_auth && !request->authenticate(_username.c_str(), _password.c_str())) {
return request->requestAuthentication();
}
// Send Webpage
AsyncWebServerResponse *response = request->beginResponse_P(
200, "text/html", WEBSERIAL_HTML, WEBSERIAL_HTML_SIZE);
Expand All @@ -15,6 +22,9 @@ void WebSerialClass::begin(AsyncWebServer *server, const char *url) {
String backendUrl = url;
backendUrl.concat("ws");
_ws = new AsyncWebSocket(backendUrl);
if(_auth) {
_ws->setAuthentication(_username.c_str(), _password.c_str());
}
_ws->onEvent([&](AsyncWebSocket *server, AsyncWebSocketClient *client,
AwsEventType type, void *arg, uint8_t *data,
size_t len) -> void {
Expand Down
5 changes: 4 additions & 1 deletion src/WebSerialLite.h
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ typedef std::function<void(AsyncWebSocketClient *, uint16_t code,

class WebSerialClass : public Print {
public:
void begin(AsyncWebServer *server, const char *url = "/webserial");
void begin(AsyncWebServer *server, const char *url = "/webserial", const String &username = "", const String &password = "");

void onConnect(ConnHandler callbackFunc);
void onDisconnect(DisconnHandler callbackFunc);
Expand All @@ -54,6 +54,9 @@ class WebSerialClass : public Print {
RecvMsgHandler _recvMsgCallback = NULL;
RecvMsgHandlerPlus _recvMsgCallbackPlus = NULL;
ErrHandler _errCallback = NULL;
String _username;
String _password;
bool _auth;

#if defined(WEBSERIAL_DEBUG)
void DEBUG_WEB_SERIAL(const char *message);
Expand Down

0 comments on commit f9b2289

Please sign in to comment.