예제 #1
0
 public void StartAsync(Action <bool> callback)
 {
     TaskUtils.StartLongRunning(() =>
     {
         _warningHandler.Info("Service starting: " + _settings.GetAddress());
         var binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
         binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
         binding.CloseTimeout        =
             binding.OpenTimeout     =
                 binding.SendTimeout = TimeSpan.FromMinutes(ServerTimoutMinutes);
         var address = new Uri(_settings.GetAddress());
         var service = new LazuriteService(_settings.SecretKey);
         _host       = new WebServiceHost(service, address);
         _host.AddServiceEndpoint(typeof(IServer), binding, address);
         _host.Credentials.UserNameAuthentication.UserNamePasswordValidationMode  = UserNamePasswordValidationMode.Custom;
         _host.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new LoginValidator();
         _host.Credentials.ServiceCertificate.SetCertificate(
             StoreLocation.LocalMachine,
             StoreName.My,
             X509FindType.FindByThumbprint,
             _settings.CertificateHash);
         _host.Open();
         _warningHandler.Info("Service started: " + _settings.GetAddress());
         callback?.Invoke(true);
         Started = true;
         StatusChanged?.Invoke(this, new EventsArgs <LazuriteServer>(this));
     },
                                (exception) => {
         _warningHandler.Error("Ошибка запуска сервиса: " + _settings.GetAddress(), exception);
         callback?.Invoke(false);
         Started = false;
         StatusChanged?.Invoke(this, new EventsArgs <LazuriteServer>(this));
     });
 }
예제 #2
0
        public ServerSettingsView()
        {
            InitializeComponent();

            var strOriginalBtChangeFileSecretKeyText = btChangeFileSecretKey.Content.ToString();

            if (!_dataEncryptor.IsSecretKeyExist)
            {
                btChangeFileSecretKey.Content = "Задать ключ шифрования файлов";
            }

            _settings                = (ServerSettings)Lazurite.Windows.Utils.Utils.CloneObject(_server.Settings);
            tbPort.Validation        = (v) => EntryViewValidation.UShortValidation().Invoke(v);
            tbPort.TextChanged      += (o, e) => SettingsChanged();
            btChangeCert.Click      += (o, e) => CertificateSelectView.Show(_settings, (s) => SettingsChanged());
            _server.StatusChanged   += Server_StatusChanged;
            btChangeSecretKey.Click += (o, e) => {
                EnterPasswordView.Show(
                    "Введите новый секретный ключ сервера...",
                    (pass) => {
                    _settings.SecretKey = pass;
                    SettingsChanged();
                },
                    (pass) => pass.Length == 16,
                    "Длина секретного ключа должна быть равна 16-и символам");
            };
            btChangeFileSecretKey.Click += (o, e) => {
                EnterPasswordView.Show(
                    "Введите ключ шифрования файлов...",
                    (pass) => {
                    _dataEncryptor.SecretKey      = pass;
                    btChangeFileSecretKey.Content = strOriginalBtChangeFileSecretKeyText;
                },
                    (pass) => pass.Length == 16,
                    "Длина секретного ключа должна быть равна 16-и символам");
            };

            btApply.Click += (o, e) => {
                try
                {
                    _settings.Port    = ushort.Parse(tbPort.Text);
                    _server.Settings  = _settings;
                    btApply.IsEnabled = false;
                    _server.Restart(null);
                }
                catch (Exception exception)
                {
                    _warningHandler.Error("Во время применения настроек сервера произошла ошибка.", exception);
                }
            };

            Unloaded += (o, e) => Dispose();

            Refresh();
        }
        public ServerSettingsView()
        {
            InitializeComponent();
            _settings                = (ServerSettings)Lazurite.Windows.Utils.Utils.CloneObject(_server.GetSettings());
            tbPort.Validation        = (v) => EntryViewValidation.UShortValidation().Invoke(v);
            tbServiceName.Validation = (v) => {
                var value = v.InputString.Replace(" ", "");
                if (value.Length == 0)
                {
                    value       = "Lazurite";
                    v.SelectAll = true;
                }
                v.OutputString = value;
            };
            tbPort.TextChanged        += (o, e) => SettingsChanged();
            tbServiceName.TextChanged += (o, e) => SettingsChanged();
            btChangeCert.Click        += (o, e) => CertificateSelectView.Show(_settings, (s) => SettingsChanged());
            btChangeSecretKey.Click   += (o, e) => {
                EnterPasswordView.Show(
                    "Введите новый секретный ключ сервера...",
                    (pass) => {
                    _settings.SecretKey = pass;
                    SettingsChanged();
                },
                    (pass) => pass.Length == 16,
                    "Длина секретного ключа должна быть равна 16-и символам");
            };
            _server.StatusChanged += _server_StatusChanged;

            btApply.Click += (o, e) => {
                try
                {
                    _settings.Port        = ushort.Parse(tbPort.Text);
                    _settings.ServiceName = tbServiceName.Text;
                    _server.SetSettings(_settings);
                    Lazurite.Windows.Server.Utils.NetshAddSslCert(_settings.CertificateHash, _settings.Port);
                    Lazurite.Windows.Server.Utils.NetshAddUrlacl(_settings.GetAddress());
                    Lazurite.Windows.Server.Utils.NetshAllowPort(_settings.Port);
                    _server.Restart(null);
                    btApply.IsEnabled = false;
                }
                catch (Exception exception)
                {
                    _warningHandler.Error("Во время применения настроек сервера произошла ошибка", exception);
                }
            };
            Refresh();
        }
예제 #4
0
 public bool Authenticate(string userName, string password)
 {
     try
     {
         WarningHandler.Debug("Authentication try: " + userName);
         var passwordHash = CryptoUtils.CreatePasswordHash(password);
         var user         = UsersRepository.Users.SingleOrDefault(x => x.Login.Equals(userName) && x.PasswordHash.Equals(passwordHash));
         if (user == null)
         {
             WarningHandler.Debug("Authentication failed: " + userName);
             return(false);
         }
         WarningHandler.Debug("Authentication success: " + userName);
         return(true);
     }
     catch (Exception e)
     {
         WarningHandler.Error("Error while user authentication: " + userName, e);
         return(false);
     }
 }
예제 #5
0
        public RemoteScenarioView(RemoteScenario scenario)
        {
            InitializeComponent();
            Refresh(scenario);

            tbPort.Validation = (v) => EntryViewValidation.UShortValidation().Invoke(v);

            tbServiceName.TextChanged    += (o, e) => ApplyCurrent();
            tbSecretCode.PasswordChanged += (o, e) => ApplyCurrent();
            tbPort.TextChanged           += (o, e) => ApplyCurrent();
            tbPassword.PasswordChanged   += (o, e) => ApplyCurrent();
            tbLogin.TextChanged          += (o, e) => ApplyCurrent();
            tbHost.TextChanged           += (o, e) => ApplyCurrent();
            btExitingCredentials.Click   += (o, e) => {
                var credentialsSelect = new ExistingConnectionSelect(ClientFactory.ConnectionCredentials);
                var dialog            = new DialogView(credentialsSelect);
                credentialsSelect.SelectedCredentialsChanged += (o1, args) => {
                    tbHost.Text           = args.Value.Host;
                    tbLogin.Text          = args.Value.Login;
                    tbPassword.Password   = args.Value.Password;
                    tbPort.Text           = args.Value.Port.ToString();
                    tbSecretCode.Password = args.Value.SecretKey;
                    tbServiceName.Text    = args.Value.ServiceName;
                    Modified?.Invoke();
                    dialog.Close();
                };
                dialog.Show();
            };
            btScenariosList.Click += (o, e) =>
            {
                try
                {
                    var remoteScenarios = _scenario.GetServer().GetScenariosInfo().Decrypt(_scenario.Credentials.SecretKey).ToArray();
                    if (!remoteScenarios.Any())
                    {
                        throw new Exception("На удаленном сервере отсутсвуют сценарии.");
                    }
                    var selectScenarioControl = new RemoteScenarioSelect(remoteScenarios, _scenario.RemoteScenarioId);
                    var dialog = new DialogView(selectScenarioControl);
                    selectScenarioControl.ScenarioInfoSelected += (info) =>
                    {
                        dialog.Close();
                        _scenario.RemoteScenarioId   = info.ScenarioId;
                        _scenario.RemoteScenarioName = info.Name;
                        tbScenario.Text = _scenario.RemoteScenarioName;
                        var loadWindowCloseToken = MessageView.ShowLoad("Соединение с удаленным сервером...");
                        _scenario.InitializeAsync((result) =>
                        {
                            loadWindowCloseToken.Cancel();
                            Dispatcher.BeginInvoke(new Action(() => {
                                if (result)
                                {
                                    Modified?.Invoke();
                                    Succeed?.Invoke();
                                }
                                else
                                {
                                    WarningHandler.Error("Невозможно получить список сценариев.");
                                    Failed?.Invoke();
                                }
                            }));
                        });
                    };
                    dialog.Show();
                }
                catch (Exception exception)
                {
                    WarningHandler.Error("Невозможно получить список сценариев.", exception);
                    Failed?.Invoke();
                }
            };
            btTest.Click += (o, e) => {
                var loadWindowCloseToken = MessageView.ShowLoad("Соединение с удаленным сервером...");
                _scenario.InitializeAsync((result) => {
                    loadWindowCloseToken.Cancel();
                    if (result)
                    {
                        MessageView.ShowMessage("Соединение успешно!", "Тест удаленного сценария", Icons.Icon.Check);
                        Dispatcher.BeginInvoke(new Action(() => Succeed?.Invoke()));
                    }
                    else
                    {
                        MessageView.ShowMessage("Невозможно активировать удаленный сценарий!", "Тест удаленного сценария", Icons.Icon.Cancel);
                        Dispatcher.BeginInvoke(new Action(() => Failed?.Invoke()));
                    }
                });
            };
        }