Пример #1
0
 public static void Apply(this AppClients clients, AppClientUpdated @event)
 {
     if (clients.TryGetValue(@event.Id, out var client))
     {
         client.Update(@event.Permission);
     }
 }
Пример #2
0
 public void FromSource(AppClients source)
 {
     foreach (var(key, client) in source)
     {
         Add(key, client);
     }
 }
Пример #3
0
 public static void Apply(this AppClients clients, AppClientRenamed @event)
 {
     if (clients.TryGetValue(@event.Id, out var client))
     {
         client.Rename(@event.Name);
     }
 }
Пример #4
0
        public static void CanUpdate(AppClients clients, UpdateClient command, Roles roles)
        {
            Guard.NotNull(command, nameof(command));

            GetClientOrThrow(clients, command.Id);

            Validate.It(e =>
            {
                if (string.IsNullOrWhiteSpace(command.Id))
                {
                    e(Not.Defined("Clientd"), nameof(command.Id));
                }

                if (command.Role != null && !roles.Contains(command.Role))
                {
                    e(Not.Valid(nameof(command.Role)), nameof(command.Role));
                }

                if (command.ApiCallsLimit != null && command.ApiCallsLimit < 0)
                {
                    e(Not.GreaterEqualsThan(nameof(command.ApiCallsLimit), "0"), nameof(command.ApiCallsLimit));
                }

                if (command.ApiTrafficLimit != null && command.ApiTrafficLimit < 0)
                {
                    e(Not.GreaterEqualsThan(nameof(command.ApiTrafficLimit), "0"), nameof(command.ApiTrafficLimit));
                }
            });
        }
Пример #5
0
 public PageContext(AppClients appClients, CacheBust cacheBust, IAppContext appContext, IUserContext userContext, IHostEnvironment hostEnvironment)
 {
     this.appClients      = appClients;
     this.cacheBust       = cacheBust;
     this.appContext      = appContext;
     this.userContext     = userContext;
     this.hostEnvironment = hostEnvironment;
 }
Пример #6
0
        private void WriteExceptionErrorToClient(TcpServerConnection client, Exception ex)
        {
            string returnMsg = TcpAppCommandStatus.ERR + " " + ex.Message;
            TcpAppServerConnection appServerClient = AppClients.FirstOrDefault(x => x.Connection == client);
            string clientName = appServerClient == null?client.ClientIPAddress.ToString() : appServerClient.Name;

            Debug.WriteLine("AppServer[" + clientName + "]-Error: " + returnMsg);
            client.WriteLineToClient(returnMsg);
        }
Пример #7
0
        private IAppEntity App(AppClients clients)
        {
            var app = A.Fake <IAppEntity>();

            A.CallTo(() => app.Clients)
            .Returns(clients);
            A.CallTo(() => app.Roles)
            .Returns(roles);

            return(app);
        }
 public static void Init()
 {
     //AppClients = new DAO_Common<AppClientsEntity>().QueryList().ToDictionary(e => e.AppKey);
     AppClients.Add("Mars.Mobile", new AppClientsEntity()
     {
         AppKey = "Mars.Mobile", AppSecrect = "41578020073147cdb707f99dbb6eeb46"
     });
     AppClients.Add("Mars.Mobile.iOS", new AppClientsEntity()
     {
         AppKey = "Mars.Mobile.iOS", AppSecrect = "88A63725299A4B4EB6B11039B3A4F265"
     });
 }
Пример #9
0
 private TcpAppServerConnection AddClientToAppClientsList(TcpServerConnection client)
 {
     lock (AppClients)
     {
         TcpAppServerConnection result = new TcpAppServerConnection()
         {
             Connection = client, Name = "#" + client.ClientIPAddress.ToString()
         };
         AppClients.Add(result);
         client.ProcessReceivedMessageCallback = Client_ProcessReceivedMessage;
         return(result);
     }
 }
Пример #10
0
        public static void CanRevoke(AppClients clients, RevokeClient command)
        {
            Guard.NotNull(command, nameof(command));

            GetClientOrThrow(clients, command.Id);

            Validate.It(() => "Cannot revoke client.", e =>
            {
                if (string.IsNullOrWhiteSpace(command.Id))
                {
                    e(Not.Defined("Client id"), nameof(command.Id));
                }
            });
        }
Пример #11
0
        public static void CanRevoke(AppClients clients, RevokeClient command)
        {
            Guard.NotNull(command, nameof(command));

            GetClientOrThrow(clients, command.Id);

            Validate.It(() => "Cannot revoke client.", error =>
            {
                if (string.IsNullOrWhiteSpace(command.Id))
                {
                    error(new ValidationError("Client id is required.", nameof(command.Id)));
                }
            });
        }
Пример #12
0
        private static AppClient GetClientOrThrow(AppClients clients, string id)
        {
            if (id == null)
            {
                return(null);
            }

            if (!clients.TryGetValue(id, out var client))
            {
                throw new DomainObjectNotFoundException(id, "Clients", typeof(AppDomainObject));
            }

            return(client);
        }
Пример #13
0
        private static AppClient?GetClientOrThrow(AppClients clients, string id)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                return(null);
            }

            if (!clients.TryGetValue(id, out var client))
            {
                throw new DomainObjectNotFoundException(id);
            }

            return(client);
        }
Пример #14
0
    private async Task <IServiceProvider> setup(AppVersionKey versionKey, string domain = "www.xartogg.com")
    {
        var host = Host.CreateDefaultBuilder()
                   .ConfigureServices
                   (
            (hostContext, services) =>
        {
            services.AddMemoryCache();
            services.AddFakesForXtiWebApp(hostContext.Configuration);
            services.AddSingleton <FakeAppOptions>();
            services.AddSingleton(sp => FakeInfo.AppKey);
            services.AddScoped <FakeAppApiFactory>();
            services.AddScoped <AppApiFactory>(sp => sp.GetRequiredService <FakeAppApiFactory>());
            services.AddScoped <FakeAppSetup>();
            services.AddSingleton(_ => new FakeAppClientDomain(domain));
            services.AddSingleton(sp =>
            {
                var cache      = sp.GetRequiredService <IMemoryCache>();
                var appClients = new AppClients(cache);
                appClients.AddAppVersion("Fake", "Current");
                appClients.AddAppClientDomain(sp.GetRequiredService <FakeAppClientDomain>());
                return(appClients);
            });
        }
                   )
                   .Build();
        var scope        = host.Services.CreateScope();
        var sp           = scope.ServiceProvider;
        var pathAccessor = (FakeXtiPathAccessor)sp.GetRequiredService <IXtiPathAccessor>();

        pathAccessor.SetPath
        (
            new XtiPath
            (
                FakeInfo.AppKey.Name.DisplayText,
                versionKey.DisplayText,
                "",
                "",
                ModifierKey.Default
            )
        );
        var setup = sp.GetRequiredService <FakeAppSetup>();
        await setup.Run(AppVersionKey.Current);

        var userContext = sp.GetRequiredService <FakeUserContext>();

        userContext.AddUser(new AppUserName("someone"));
        return(sp);
    }
Пример #15
0
        public static void CanAttach(AppClients clients, AttachClient command)
        {
            Guard.NotNull(command, nameof(command));

            Validate.It(e =>
            {
                if (string.IsNullOrWhiteSpace(command.Id))
                {
                    e(Not.Defined("ClientId"), nameof(command.Id));
                }
                else if (clients.ContainsKey(command.Id))
                {
                    e(T.Get("apps.clients.idAlreadyExists"));
                }
            });
        }
Пример #16
0
        public static void CanAttach(AppClients clients, AttachClient command)
        {
            Guard.NotNull(command, nameof(command));

            Validate.It(() => "Cannot attach client.", e =>
            {
                if (string.IsNullOrWhiteSpace(command.Id))
                {
                    e(Not.Defined("Client id"), nameof(command.Id));
                }
                else if (clients.ContainsKey(command.Id))
                {
                    e("A client with the same id already exists.");
                }
            });
        }
Пример #17
0
        public static void CanAttach(AppClients clients, AttachClient command)
        {
            Guard.NotNull(command, nameof(command));

            Validate.It(() => "Cannot attach client.", error =>
            {
                if (string.IsNullOrWhiteSpace(command.Id))
                {
                    error(new ValidationError("Client id is required.", nameof(command.Id)));
                }
                else if (clients.ContainsKey(command.Id))
                {
                    error(new ValidationError("Client id already added.", nameof(command.Id)));
                }
            });
        }
Пример #18
0
        public static void CanUpdate(AppClients clients, UpdateClient command)
        {
            Guard.NotNull(command, nameof(command));

            var client = GetClientOrThrow(clients, command.Id);

            Validate.It(() => "Cannot update client.", e =>
            {
                if (string.IsNullOrWhiteSpace(command.Id))
                {
                    e("Client id is required.", nameof(command.Id));
                }

                if (string.IsNullOrWhiteSpace(command.Name) && command.Permission == null)
                {
                    e("Either name or permission must be defined.", nameof(command.Name), nameof(command.Permission));
                }

                if (command.Permission.HasValue && !command.Permission.Value.IsEnumValue())
                {
                    e("Permission is not valid.", nameof(command.Permission));
                }

                if (client == null)
                {
                    return;
                }

                if (!string.IsNullOrWhiteSpace(command.Name) && string.Equals(client.Name, command.Name))
                {
                    e("Client has already this name.", nameof(command.Name));
                }

                if (command.Permission == client.Permission)
                {
                    e("Client has already this permission.", nameof(command.Permission));
                }
            });
        }
Пример #19
0
        public static void CanUpdate(AppClients clients, UpdateClient command, Roles roles)
        {
            Guard.NotNull(command, nameof(command));

            var client = GetClientOrThrow(clients, command.Id);

            Validate.It(() => "Cannot update client.", e =>
            {
                if (string.IsNullOrWhiteSpace(command.Id))
                {
                    e(Not.Defined("Client id"), nameof(command.Id));
                }

                if (string.IsNullOrWhiteSpace(command.Name) && command.Role == null)
                {
                    e(Not.DefinedOr("name", "role"), nameof(command.Name), nameof(command.Role));
                }

                if (command.Role != null && !roles.ContainsKey(command.Role))
                {
                    e(Not.Valid("role"), nameof(command.Role));
                }

                if (client == null)
                {
                    return;
                }

                if (!string.IsNullOrWhiteSpace(command.Name) && string.Equals(client.Name, command.Name))
                {
                    e(Not.New("Client", "name"), nameof(command.Name));
                }

                if (command.Role == client.Role)
                {
                    e(Not.New("Client", "role"), nameof(command.Role));
                }
            });
        }
Пример #20
0
        public static void CanUpdate(AppClients clients, UpdateClient command, Roles roles)
        {
            Guard.NotNull(command, nameof(command));

            var client = GetClientOrThrow(clients, command.Id);

            Validate.It(() => "Cannot update client.", e =>
            {
                if (string.IsNullOrWhiteSpace(command.Id))
                {
                    e("Client id is required.", nameof(command.Id));
                }

                if (string.IsNullOrWhiteSpace(command.Name) && command.Role == null)
                {
                    e("Either name or role must be defined.", nameof(command.Name), nameof(command.Role));
                }

                if (command.Role != null && !roles.ContainsKey(command.Role))
                {
                    e("Role is not valid.", nameof(command.Role));
                }

                if (client == null)
                {
                    return;
                }

                if (!string.IsNullOrWhiteSpace(command.Name) && string.Equals(client.Name, command.Name))
                {
                    e("Client has already this name.", nameof(command.Name));
                }

                if (command.Role == client.Role)
                {
                    e("Client has already this role.", nameof(command.Role));
                }
            });
        }
Пример #21
0
    public static void ConfigureAppClients(this IServiceCollection services, Action <AppClients> configure)
    {
        var existing = services.FirstOrDefault(s => s.ImplementationType == typeof(AppClients));

        if (existing != null)
        {
            services.Remove(existing);
        }
        services.AddScoped
        (
            sp =>
        {
            var cache      = sp.GetRequiredService <IMemoryCache>();
            var appClients = new AppClients(cache);
            var appKey     = sp.GetRequiredService <AppKey>();
            var versionKey = sp.GetRequiredService <AppVersionKey>();
            appClients.AddAppVersion(appKey.Name.DisplayText, versionKey.DisplayText);
            appClients.AddAppClientDomain(sp.GetRequiredService <SelfAppClientDomain>());
            configure(appClients);
            return(appClients);
        }
        );
    }
Пример #22
0
        private void Client_ProcessReceivedMessage(TcpServerConnection client, string message, byte[] messageBytes)
        {
            //Parse and Execute Commands
            string[] cmdArg = TcpAppCommon.ParseCommand(message.Trim());
            try
            {
                //Register Client Connection
                TcpAppServerConnection ptrClient = AppClients.FirstOrDefault(x => x.Connection == client);
                if (ptrClient == null)
                {
                    //Reconstruct device which had already signed out
                    ptrClient = AddClientToAppClientsList(client);
                }
                Debug.WriteLine("AppServer[" + ptrClient.Name + "]-RX: " + message);

                TcpAppInputCommand inputCommand = TcpAppCommon.CreateInputCommand(Commands, cmdArg);
                if (inputCommand != null)
                {
                    inputCommand.AppClient = ptrClient;
                }
                else//Command keyword not exist
                {
                    //Check if command keyword is alias name
                    ITcpAppServerPlugin plugin = _Plugins.FirstOrDefault(x => string.Compare(x.Alias, cmdArg[0], true) == 0);
                    if (plugin != null)
                    {
                        //Execute plugin command
                        inputCommand           = plugin.GetPluginCommand(cmdArg.Skip(1).ToArray());
                        inputCommand.AppClient = ptrClient;
                        BeforeExecutePluginCommand?.Invoke(this, new TcpAppServerExEventArgs(ptrClient)
                        {
                            Plugin = plugin
                        });
                    }
                    else
                    {
                        //Error - Unrecognized command.
                        inputCommand = new TcpAppInputCommand()
                        {
                            Status        = TcpAppCommandStatus.ERR,
                            OutputMessage = "Invalid Command " + cmdArg[0]
                        };
                        WriteResultToClient(ptrClient, inputCommand);
                        return;
                    }
                }

                //Verify Client had signed in.
                if (!inputCommand.AppClient.SignedIn && !inputCommand.Command.IsSystemCommand)
                {
                    throw new Exception("Client not signed in! Execute SignIn first.");
                }

                if (inputCommand.Command.UseMessageQueue && !inputCommand.Command.IsSystemCommand)
                {
                    //Single thread execution, post message to message queue.
                    lock (CommandQueue)
                    {
                        inputCommand.ID = inputCommand.GetHashCode();
                        if (ptrClient.NextQueuedCommand == null)
                        {
                            ptrClient.NextQueuedCommand = inputCommand;                                      //Set pointer to next queued command.
                        }
                        //Add Command to Queue
                        CommandQueue.Add(inputCommand);
                        CommandQueueWaitSignal?.Set();
                        inputCommand.OutputMessage = inputCommand.ID.ToString();
                        inputCommand.Status        = TcpAppCommandStatus.QUEUED;
                    }
                }
                else if (inputCommand.Command.IsSystemCommand)
                {
                    inputCommand.ExecuteCallback();
                }
                else
                {
                    //Execute command, wait until return
                    if (ExecutionTimeout == 0)
                    {
                        inputCommand.ExecuteCallback();
                    }
                    //Execute command, terminate on timeout
                    else
                    {
                        ptrClient.ExecuteCommandAsync(inputCommand, ExecutionTimeout);
                    }
                }

                WriteResultToClient(ptrClient, inputCommand); //Send result back to client.
            }
            catch (Exception ex)
            {
                WriteExceptionErrorToClient(client, ex);
            }
        }
Пример #23
0
        public static void CanDelete(Roles roles, DeleteRole command, AppContributors contributors, AppClients clients)
        {
            Guard.NotNull(command, nameof(command));

            GetRoleOrThrow(roles, command.Name);

            Validate.It(() => "Cannot delete role.", e =>
            {
                if (string.IsNullOrWhiteSpace(command.Name))
                {
                    e(Not.Defined("Name"), nameof(command.Name));
                }
                else if (Role.IsDefaultRole(command.Name))
                {
                    e("Cannot delete a default role.");
                }

                if (clients.Values.Any(x => string.Equals(x.Role, command.Name, StringComparison.OrdinalIgnoreCase)))
                {
                    e("Cannot remove a role when a client is assigned.");
                }

                if (contributors.Values.Any(x => string.Equals(x, command.Name, StringComparison.OrdinalIgnoreCase)))
                {
                    e("Cannot remove a role when a contributor is assigned.");
                }
            });
        }
Пример #24
0
        public static void CanDelete(Roles roles, DeleteRole command, AppContributors contributors, AppClients clients)
        {
            Guard.NotNull(command, nameof(command));

            CheckRoleExists(roles, command.Name);

            Validate.It(e =>
            {
                if (string.IsNullOrWhiteSpace(command.Name))
                {
                    e(Not.Defined(nameof(command.Name)), nameof(command.Name));
                }
                else if (Roles.IsDefault(command.Name))
                {
                    e(T.Get("apps.roles.defaultRoleNotRemovable"));
                }

                if (clients.Values.Any(x => string.Equals(x.Role, command.Name, StringComparison.OrdinalIgnoreCase)))
                {
                    e(T.Get("apps.roles.usedRoleByClientsNotRemovable"));
                }

                if (contributors.Values.Any(x => string.Equals(x, command.Name, StringComparison.OrdinalIgnoreCase)))
                {
                    e(T.Get("apps.roles.usedRoleByContributorsNotRemovable"));
                }
            });
        }
Пример #25
0
 public static void Apply(this AppClients clients, AppClientAttached @event)
 {
     clients.Add(@event.Id, @event.Secret);
 }
Пример #26
0
 public static AppClients Apply(this AppClients clients, AppClientUpdated @event)
 {
     return(clients.Update(@event.Id, @event.Permission));
 }
Пример #27
0
 public static AppClients Apply(this AppClients clients, AppClientRenamed @event)
 {
     return(clients.Rename(@event.Id, @event.Name));
 }
Пример #28
0
 public static AppClients Apply(this AppClients clients, AppClientRevoked @event)
 {
     return(clients.Revoke(@event.Id));
 }
Пример #29
0
 public static AppClients Apply(this AppClients clients, AppClientAttached @event)
 {
     return(clients.Add(@event.Id, @event.Secret));
 }
Пример #30
0
 public static void Apply(this AppClients clients, AppClientRevoked @event)
 {
     clients.Revoke(@event.Id);
 }