private ICommand InstanceCommand(string input) { List<string> inputParams = input.Split("|").ToList(); string commandName = inputParams[0].ToLower(); inputParams.RemoveAt(0); var commandType = Assembly.GetEntryAssembly() ?.GetTypes() .Where(type => typeof(ICommand).IsAssignableFrom(type)) .FirstOrDefault(type => type.Name.Replace("Command", string.Empty).ToLower() == commandName); if (commandType != null) { ICommand command = (ICommand)Activator.CreateInstance(commandType); command.ConsoleReader = this.consoleReader; command.ConsoleWriter = this.consoleWriter; command.Parameters = inputParams; command.Principal = this.currentlyLoggedInUser; return command; } return null; }
public void HandleInput() { this.consoleWriter.Write(Constants.ConsoleForumOutputPrefix); string input = this.consoleReader.ReadLine(); ICommand command = this.InstanceCommand(input); if (command == null) { this.consoleWriter.Write(Constants.ConsoleForumOutputPrefix); this.consoleWriter.ErrorLine("Unsupported command..."); Thread.Sleep(Constants.NotificationDelay); this.Reset(); } else { if (!this.IsAuthorized(command)) { this.consoleWriter.Write(Constants.ConsoleForumOutputPrefix); this.consoleWriter.ErrorLine("You have no access to this command."); Thread.Sleep(Constants.NotificationDelay); this.Reset(); } else { command.Execute(); if (command.ResetsConsole) this.Reset(); } } }
private bool IsAuthorized(ICommand command) { var authAttributes = command .GetType() .GetCustomAttributes() .Where(attribute => attribute.GetType().Name.Contains("CommandAttribute")) .ToList(); if (!authAttributes.Any()) { return true; } else { return (this.IsLoggedIn() && authAttributes .Any(attribute => attribute.GetType().Name.Contains(this.currentlyLoggedInUser.User.Role.ToString()))) || (!this.IsLoggedIn() && authAttributes .Any(attribute => attribute.GetType() == typeof(GuestCommandAttribute))); } }