2019-05-18 18:35:27 +00:00
|
|
|
#include <AuthenticationService.h>
|
|
|
|
|
2020-06-09 20:57:44 +00:00
|
|
|
#if FT_ENABLED(FT_SECURITY)
|
|
|
|
|
2019-12-03 23:16:06 +00:00
|
|
|
AuthenticationService::AuthenticationService(AsyncWebServer* server, SecurityManager* securityManager) :
|
2020-05-14 22:23:45 +00:00
|
|
|
_securityManager(securityManager),
|
|
|
|
_signInHandler(SIGN_IN_PATH,
|
|
|
|
std::bind(&AuthenticationService::signIn, this, std::placeholders::_1, std::placeholders::_2)) {
|
2019-12-03 23:16:06 +00:00
|
|
|
server->on(VERIFY_AUTHORIZATION_PATH,
|
|
|
|
HTTP_GET,
|
|
|
|
std::bind(&AuthenticationService::verifyAuthorization, this, std::placeholders::_1));
|
2019-05-18 18:35:27 +00:00
|
|
|
_signInHandler.setMethod(HTTP_POST);
|
2019-05-29 22:48:16 +00:00
|
|
|
_signInHandler.setMaxContentLength(MAX_AUTHENTICATION_SIZE);
|
2019-09-28 20:29:46 +00:00
|
|
|
server->addHandler(&_signInHandler);
|
2019-05-18 18:35:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Verifys that the request supplied a valid JWT.
|
|
|
|
*/
|
2019-12-03 23:16:06 +00:00
|
|
|
void AuthenticationService::verifyAuthorization(AsyncWebServerRequest* request) {
|
2019-05-18 18:35:27 +00:00
|
|
|
Authentication authentication = _securityManager->authenticateRequest(request);
|
2020-02-01 08:44:26 +00:00
|
|
|
request->send(authentication.authenticated ? 200 : 401);
|
2019-05-18 18:35:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2019-12-03 23:16:06 +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
|
|
|
*/
|
2020-05-14 22:23:45 +00:00
|
|
|
void AuthenticationService::signIn(AsyncWebServerRequest* request, JsonVariant& json) {
|
|
|
|
if (json.is<JsonObject>()) {
|
|
|
|
String username = json["username"];
|
|
|
|
String password = json["password"];
|
2019-05-18 18:35:27 +00:00
|
|
|
Authentication authentication = _securityManager->authenticate(username, password);
|
2020-02-01 08:44:26 +00:00
|
|
|
if (authentication.authenticated) {
|
|
|
|
User* user = authentication.user;
|
2019-12-03 23:16:06 +00:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
}
|
2019-12-03 23:16:06 +00:00
|
|
|
AsyncWebServerResponse* response = request->beginResponse(401);
|
2019-05-18 18:35:27 +00:00
|
|
|
request->send(response);
|
|
|
|
}
|
2020-06-09 20:57:44 +00:00
|
|
|
|
|
|
|
#endif // end FT_ENABLED(FT_SECURITY)
|