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

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