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.

44 lines
1.9 KiB

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