Fork of the excellent esp8266-react - https://github.com/rjwats/esp8266-react
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

48 lines
1.9 KiB

  1. #include <AuthenticationService.h>
  2. AuthenticationService::AuthenticationService(AsyncWebServer* server, SecurityManager* securityManager) :
  3. _securityManager(securityManager) {
  4. server->on(VERIFY_AUTHORIZATION_PATH,
  5. HTTP_GET,
  6. std::bind(&AuthenticationService::verifyAuthorization, this, std::placeholders::_1));
  7. _signInHandler.setUri(SIGN_IN_PATH);
  8. _signInHandler.setMethod(HTTP_POST);
  9. _signInHandler.setMaxContentLength(MAX_AUTHENTICATION_SIZE);
  10. _signInHandler.onRequest(
  11. std::bind(&AuthenticationService::signIn, this, std::placeholders::_1, std::placeholders::_2));
  12. server->addHandler(&_signInHandler);
  13. }
  14. AuthenticationService::~AuthenticationService() {
  15. }
  16. /**
  17. * Verifys that the request supplied a valid JWT.
  18. */
  19. void AuthenticationService::verifyAuthorization(AsyncWebServerRequest* request) {
  20. Authentication authentication = _securityManager->authenticateRequest(request);
  21. request->send(authentication.authenticated ? 200 : 401);
  22. }
  23. /**
  24. * Signs in a user if the username and password match. Provides a JWT to be used in the Authorization header in
  25. * subsequent requests.
  26. */
  27. void AuthenticationService::signIn(AsyncWebServerRequest* request, JsonDocument& jsonDocument) {
  28. if (jsonDocument.is<JsonObject>()) {
  29. String username = jsonDocument["username"];
  30. String password = jsonDocument["password"];
  31. Authentication authentication = _securityManager->authenticate(username, password);
  32. if (authentication.authenticated) {
  33. User* user = authentication.user;
  34. AsyncJsonResponse* response = new AsyncJsonResponse(false, MAX_AUTHENTICATION_SIZE);
  35. JsonObject jsonObject = response->getRoot();
  36. jsonObject["access_token"] = _securityManager->generateJWT(user);
  37. response->setLength();
  38. request->send(response);
  39. return;
  40. }
  41. }
  42. AsyncWebServerResponse* response = request->beginResponse(401);
  43. request->send(response);
  44. }