MqttConnectionValidator.cs 2.0 KB
Newer Older
C
Christian 已提交
1
using System;
2
using System.Text;
C
Christian 已提交
3 4 5 6 7 8 9 10 11 12 13
using System.Threading.Tasks;
using IronPython.Runtime;
using Microsoft.Extensions.Logging;
using MQTTnet.Protocol;
using MQTTnet.Server.Scripting;

namespace MQTTnet.Server.Mqtt
{
    public class MqttConnectionValidator : IMqttServerConnectionValidator
    {
        private readonly PythonScriptHostService _pythonScriptHostService;
14
        private readonly ILogger _logger;
C
Christian 已提交
15 16 17 18 19 20 21 22 23 24 25

        public MqttConnectionValidator(PythonScriptHostService pythonScriptHostService, ILogger<MqttConnectionValidator> logger)
        {
            _pythonScriptHostService = pythonScriptHostService ?? throw new ArgumentNullException(nameof(pythonScriptHostService));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        public Task ValidateConnectionAsync(MqttConnectionValidatorContext context)
        {
            try
            {
26 27 28 29 30 31
                string passwordString = null;
                if (context.Password != null)
                {
                    passwordString = Encoding.UTF8.GetString(context.Password);
                }

C
Christian 已提交
32 33 34 35
                var pythonContext = new PythonDictionary
                {
                    { "client_id", context.ClientId },
                    { "endpoint", context.Endpoint },
36
                    { "is_secure_connection", context.IsSecureConnection },
C
Christian 已提交
37 38
                    { "username", context.Username },
                    { "password", context.Password },
39
                    { "password_string", passwordString },
C
Christian 已提交
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
                    { "result", PythonConvert.Pythonfy(context.ReturnCode) }
                };

                _pythonScriptHostService.InvokeOptionalFunction("on_validate_client_connection", pythonContext);

                context.ReturnCode = PythonConvert.ParseEnum<MqttConnectReturnCode>((string)pythonContext["result"]);
            }
            catch (Exception exception)
            {
                _logger.LogError(exception, "Error while validating client connection.");
            }

            return Task.CompletedTask;
        }
    }
}