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.8 KiB

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