WordClockESP/lib/framework/AuthenticationService.cpp

49 lines
1.9 KiB
C++
Raw Normal View History

2019-05-18 18:35:27 +00:00
#include <AuthenticationService.h>
AuthenticationService::AuthenticationService(AsyncWebServer* server, SecurityManager* securityManager) :
_securityManager(securityManager) {
server->on(VERIFY_AUTHORIZATION_PATH,
HTTP_GET,
std::bind(&AuthenticationService::verifyAuthorization, this, std::placeholders::_1));
2019-05-18 18:35:27 +00:00
_signInHandler.setUri(SIGN_IN_PATH);
_signInHandler.setMethod(HTTP_POST);
2019-05-29 22:48:16 +00:00
_signInHandler.setMaxContentLength(MAX_AUTHENTICATION_SIZE);
_signInHandler.onRequest(
std::bind(&AuthenticationService::signIn, this, std::placeholders::_1, std::placeholders::_2));
server->addHandler(&_signInHandler);
2019-05-18 18:35:27 +00:00
}
AuthenticationService::~AuthenticationService() {
}
2019-05-18 18:35:27 +00:00
/**
* Verifys that the request supplied a valid JWT.
*/
void AuthenticationService::verifyAuthorization(AsyncWebServerRequest* request) {
2019-05-18 18:35:27 +00:00
Authentication authentication = _securityManager->authenticateRequest(request);
request->send(authentication.authenticated ? 200 : 401);
2019-05-18 18:35:27 +00:00
}
/**
* Signs in a user if the username and password match. Provides a JWT to be used in the Authorization header in
* subsequent requests.
2019-05-18 18:35:27 +00:00
*/
void AuthenticationService::signIn(AsyncWebServerRequest* request, JsonDocument& jsonDocument) {
2019-05-18 18:35:27 +00:00
if (jsonDocument.is<JsonObject>()) {
String username = jsonDocument["username"];
2019-05-18 18:35:27 +00:00
String password = jsonDocument["password"];
Authentication authentication = _securityManager->authenticate(username, password);
if (authentication.authenticated) {
User* user = authentication.user;
AsyncJsonResponse* response = new AsyncJsonResponse(false, MAX_AUTHENTICATION_SIZE);
2019-05-18 18:35:27 +00:00
JsonObject jsonObject = response->getRoot();
jsonObject["access_token"] = _securityManager->generateJWT(user);
response->setLength();
request->send(response);
return;
}
}
AsyncWebServerResponse* response = request->beginResponse(401);
2019-05-18 18:35:27 +00:00
request->send(response);
}