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.
 
 
 
 

56 rivejä
2.0 KiB

  1. using System;
  2. using System.Text;
  3. using System.Threading.Tasks;
  4. using IronPython.Runtime;
  5. using Microsoft.Extensions.Logging;
  6. using MQTTnet.Protocol;
  7. using MQTTnet.Server.Scripting;
  8. namespace MQTTnet.Server.Mqtt
  9. {
  10. public class MqttConnectionValidator : IMqttServerConnectionValidator
  11. {
  12. private readonly PythonScriptHostService _pythonScriptHostService;
  13. private readonly ILogger _logger;
  14. public MqttConnectionValidator(PythonScriptHostService pythonScriptHostService, ILogger<MqttConnectionValidator> logger)
  15. {
  16. _pythonScriptHostService = pythonScriptHostService ?? throw new ArgumentNullException(nameof(pythonScriptHostService));
  17. _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  18. }
  19. public Task ValidateConnectionAsync(MqttConnectionValidatorContext context)
  20. {
  21. try
  22. {
  23. string passwordString = null;
  24. if (context.Password != null)
  25. {
  26. passwordString = Encoding.UTF8.GetString(context.Password);
  27. }
  28. var pythonContext = new PythonDictionary
  29. {
  30. { "client_id", context.ClientId },
  31. { "endpoint", context.Endpoint },
  32. { "is_secure_connection", context.IsSecureConnection },
  33. { "username", context.Username },
  34. { "password", context.Password },
  35. { "password_string", passwordString },
  36. { "result", PythonConvert.Pythonfy(context.ReturnCode) }
  37. };
  38. _pythonScriptHostService.InvokeOptionalFunction("on_validate_client_connection", pythonContext);
  39. context.ReturnCode = PythonConvert.ParseEnum<MqttConnectReturnCode>((string)pythonContext["result"]);
  40. }
  41. catch (Exception exception)
  42. {
  43. _logger.LogError(exception, "Error while validating client connection.");
  44. }
  45. return Task.CompletedTask;
  46. }
  47. }
  48. }