예제 #1
0
 public override void Command(MenuItem menuItem, string UserInput)
 {
     try
     {
         string[] commands = UserInput.Split(" ");
         if (commands.Length < 3 || commands.Length > 4 || !commands[0].Equals(this.Name, StringComparison.OrdinalIgnoreCase))
         {
             menuItem.PrintInvalidOptionError(UserInput);
             EliteConsole.PrintFormattedErrorLine("Usage: Create <username> <password> [<roles>]");
             return;
         }
         CovenantUser user = this.CovenantClient.ApiUsersPost(new CovenantUserLogin(commands[1], commands[2]));
         if (user != null)
         {
             if (commands.Length == 4)
             {
                 string[] roleNames = commands[3].Split(",");
                 foreach (string roleName in roleNames)
                 {
                     IdentityRole role = this.CovenantClient.ApiRolesGet().FirstOrDefault(R => R.Name == roleName);
                     this.CovenantClient.ApiUsersByIdRolesByRidPost(user.Id, role.Id);
                 }
             }
         }
         else
         {
             EliteConsole.PrintFormattedErrorLine("Failed to create user: \"" + commands[1] + "\"");
         }
     }
     catch (HttpOperationException e)
     {
         EliteConsole.PrintFormattedWarningLine("CovenantException: " + e.Response.Content);
     }
 }
예제 #2
0
        // POST: /grunttasking/create
        public async Task <IActionResult> Create(GruntTasking tasking)
        {
            try
            {
                CovenantUser currentUser = await _context.GetCurrentUser(_userManager, HttpContext.User);

                tasking.Grunt = await _context.GetGrunt(tasking.GruntId);

                tasking.GruntTask = await _context.GetGruntTask(tasking.GruntTaskId);

                GruntCommand createdCommand = await _context.CreateGruntCommand(new GruntCommand
                {
                    Command         = GetCommand(tasking),
                    CommandTime     = DateTime.UtcNow,
                    CommandOutputId = 0,
                    CommandOutput   = new CommandOutput(),
                    User            = currentUser,
                    GruntId         = tasking.Grunt.Id,
                    Grunt           = tasking.Grunt
                }, _grunthub);

                tasking.GruntCommand   = createdCommand;
                tasking.GruntCommandId = createdCommand.Id;

                GruntTasking created = await _context.CreateGruntTasking(tasking);

                return(RedirectToAction(nameof(Interact), new { id = created.Id }));
            }
            catch (Exception e) when(e is ControllerNotFoundException || e is ControllerBadRequestException || e is ControllerUnauthorizedException)
            {
                return(RedirectToAction(nameof(Index)));
            }
        }
예제 #3
0
        private IdentityResult CreateCovenantUser(CovenantUser user, string password)
        {
            Task <IdentityResult> task = _userManager.CreateAsync(user, password);

            task.Wait();
            return(task.Result);
        }
예제 #4
0
        public ActionResult <CovenantUser> EditUser([FromBody] CovenantUserLogin user)
        {
            var matching_user = _context.Users.FirstOrDefault(U => user.UserName == U.UserName);

            if (matching_user == null)
            {
                return(NotFound($"NotFound - Could not find CovenantUser with username: {user.UserName}"));
            }
            CovenantUser currentUser = GetCurrentAPIUser();
            var          admins      = from users in _context.Users
                                       join userroles in _context.UserRoles on users.Id equals userroles.UserId
                                       join roles in _context.Roles on userroles.RoleId equals roles.Id
                                       where roles.Name == "Administrator"
                                       select users.UserName;

            if (currentUser.UserName != matching_user.UserName && !admins.Contains(currentUser.UserName))
            {
                return(BadRequest($"BadRequest - Current user: {currentUser.UserName} is not an Administrator and cannot change password of user: {user.Password}"));
            }
            matching_user.PasswordHash = _userManager.PasswordHasher.HashPassword(matching_user, user.Password);
            Task <IdentityResult> task = _userManager.UpdateAsync(matching_user);

            task.Wait();
            if (!task.Result.Succeeded)
            {
                return(BadRequest($"BadRequest - Could not set new password for CovenantUser with username: {user.UserName}"));
            }
            _context.Users.Update(matching_user);
            _context.SaveChanges();
            matching_user.PasswordHash  = "";
            matching_user.SecurityStamp = "";
            return(matching_user);
        }
예제 #5
0
        private IdentityResult CreateUserRole(CovenantUser user, string rolename)
        {
            Task <IdentityResult> task = _userManager.AddToRoleAsync(user, rolename);

            task.Wait();
            return(task.Result);
        }
예제 #6
0
        public ActionResult <IdentityUserRole <string> > CreateUserRole(string id, string rid)
        {
            CovenantUser user = _context.Users.FirstOrDefault(U => U.Id == id);
            IdentityRole role = _context.Roles.FirstOrDefault(R => R.Id == rid);

            if (user == null)
            {
                return(NotFound($"NotFound - Could not find CovenantUser with id: {id}"));
            }
            if (role == null)
            {
                return(NotFound($"NotFound - Could not find UserRole with rid: {rid}"));
            }

            IdentityResult result = this.CreateUserRole(user, role.Name);

            if (!result.Succeeded)
            {
                string ErrorMessage = $"BadRequest - Could not add CovenantUser: {user.UserName} to role: {role.Name}";
                foreach (IdentityError error in result.Errors)
                {
                    ErrorMessage += Environment.NewLine + error.Description;
                }
                return(BadRequest(ErrorMessage));
            }
            IdentityUserRole <string> userRole = _context.UserRoles.FirstOrDefault(UR => UR.UserId == id && UR.RoleId == rid);

            if (userRole == null)
            {
                return(NotFound($"NotFound - Could not find UserRole with user id: {id} and role id: {rid}"));
            }
            return(CreatedAtRoute(nameof(GetUserRole), new { id = id, rid = rid }, userRole));
        }
예제 #7
0
        public ActionResult <CovenantUserLoginResult> Login([FromBody] CovenantUserLogin login)
        {
            Microsoft.AspNetCore.Identity.SignInResult result = this.GetPasswordSignInResult(login.UserName, login.Password);
            if (!result.Succeeded)
            {
                return(new UnauthorizedResult());
            }
            CovenantUser user = _userManager.Users.FirstOrDefault(U => U.UserName == login.UserName);

            if (user == null)
            {
                return(NotFound($"NotFound - User with username: {login.UserName}"));
            }
            List <string> userRoles = _context.UserRoles.Where(UR => UR.UserId == user.Id).Select(UR => UR.RoleId).ToList();
            List <string> roles     = _context.Roles.Where(R => userRoles.Contains(R.Id)).Select(R => R.Name).ToList();

            string token = Utilities.GenerateJwtToken(
                login.UserName, user.Id, roles.ToArray(),
                _configuration["JwtKey"], _configuration["JwtIssuer"],
                _configuration["JwtAudience"], _configuration["JwtExpireDays"]
                );

            return(new CovenantUserLoginResult {
                success = true, token = token
            });
        }
예제 #8
0
 public override void Command(MenuItem menuItem, string UserInput)
 {
     try
     {
         string[] commands = UserInput.Split(" ");
         if (commands.Length != 2 || !commands[0].Equals(this.Name, StringComparison.OrdinalIgnoreCase))
         {
             menuItem.PrintInvalidOptionError(UserInput);
             EliteConsole.PrintFormattedErrorLine("Usage: Delete <username>");
             return;
         }
         List <CovenantUser> Users = ((UsersMenuItem)menuItem).Users;
         CovenantUser        user  = Users.FirstOrDefault(U => U.UserName == commands[1]);
         if (user != null)
         {
             EliteConsole.PrintFormattedWarning("Delete user: \"" + commands[1] + "\"? [y/N] ");
             string input = EliteConsole.Read();
             if (input.StartsWith("y", StringComparison.OrdinalIgnoreCase))
             {
                 this.CovenantClient.ApiUsersByIdDelete(user.Id);
             }
         }
         else
         {
             EliteConsole.PrintFormattedErrorLine("User: \"" + commands[1] + "\" does not exist.");
         }
     }
     catch (HttpOperationException e)
     {
         EliteConsole.PrintFormattedWarningLine("CovenantException: " + e.Response.Content);
     }
 }
예제 #9
0
        public override void Command(MenuItem menuItem, string UserInput)
        {
            UsersMenuItem usersMenuItem = (UsersMenuItem)menuItem;

            usersMenuItem.Refresh();
            string[] commands = UserInput.Split(" ");
            if (commands.Length != 2 || commands[0].ToLower() != "delete")
            {
                menuItem.PrintInvalidOptionError(UserInput);
                EliteConsole.PrintFormattedErrorLine("Usage: Delete <username>");
                return;
            }

            CovenantUser user = usersMenuItem.Users.FirstOrDefault(U => U.UserName == commands[1]);

            if (user != null)
            {
                EliteConsole.PrintFormattedWarning("Delete user: \"" + commands[1] + "\"? [y/N] ");
                string input = EliteConsole.Read();
                if (input.ToLower().StartsWith("y"))
                {
                    this.CovenantClient.ApiUsersByUidDelete(user.Id);
                }
            }
            else
            {
                EliteConsole.PrintFormattedErrorLine("User: \"" + commands[1] + "\" does not exist.");
            }
        }
예제 #10
0
        public async Task GetSuggestions(string gruntName)
        {
            CovenantUser user = await _context.GetUserByUsername(this.Context.User.Identity.Name);

            List <string> suggestions = await interact.GetSuggestions(gruntName);

            await this.Clients.Caller.SendAsync("ReceiveSuggestions", suggestions);
        }
예제 #11
0
        public ActionResult <IdentityUserRole <string> > CreateUserRole(string uid, string rid)
        {
            CovenantUser user = _context.Users.FirstOrDefault(U => U.Id == uid);
            IdentityRole role = _context.Roles.FirstOrDefault(R => R.Id == rid);

            _userManager.AddToRoleAsync(user, role.Name).Wait();
            IdentityUserRole <string> userRole = _context.UserRoles.FirstOrDefault(UR => UR.UserId == uid && UR.RoleId == rid);

            return(CreatedAtRoute(nameof(GetUserRole), new { uid = uid, rid = rid }, userRole));
        }
예제 #12
0
        public ActionResult <CovenantUser> CreateUser([FromBody] CovenantUserLogin login)
        {
            CovenantUser user = new CovenantUser {
                UserName = login.UserName
            };

            _userManager.CreateAsync(user, login.Password).Wait();
            CovenantUser savedUser = _context.Users.FirstOrDefault(U => U.UserName == user.UserName);

            return(CreatedAtRoute(nameof(GetUser), new { uid = savedUser.Id }, savedUser));
        }
예제 #13
0
        public ActionResult <CovenantUser> GetCurrentUser()
        {
            CovenantUser user = GetCurrentAPIUser();

            if (user == null)
            {
                return(NotFound($"NotFound - Could not identify current username"));
            }
            user.PasswordHash  = "";
            user.SecurityStamp = "";
            return(user);
        }
예제 #14
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            try
            {
                if (!_userManager.Users.ToList().Where(U => _userManager.IsInRoleAsync(U, "Administrator").WaitResult()).Any())
                {
                    if (CovenantUserRegister.Password != CovenantUserRegister.ConfirmPassword)
                    {
                        return(BadRequest($"BadRequest - Password does not match ConfirmPassword."));
                    }

                    CovenantUser user = new CovenantUser {
                        UserName = CovenantUserRegister.UserName
                    };
                    IdentityResult userResult = await _userManager.CreateAsync(user, CovenantUserRegister.Password);

                    await _userManager.AddToRoleAsync(user, "User");

                    await _userManager.AddToRoleAsync(user, "Administrator");

                    await _signInManager.PasswordSignInAsync(CovenantUserRegister.UserName, CovenantUserRegister.Password, true, lockoutOnFailure : false);

                    // return RedirectToAction(nameof(Index));
                    return(LocalRedirect("/home/index"));
                }
                else
                {
                    var result = await _signInManager.PasswordSignInAsync(CovenantUserRegister.UserName, CovenantUserRegister.Password, true, lockoutOnFailure : false);

                    if (!result.Succeeded == true)
                    {
                        ModelState.AddModelError(string.Empty, "Incorrect username or password");
                        return(Page());
                    }
                    // if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
                    // {
                    //     return LocalRedirect(returnUrl);
                    // }
                    // return RedirectToAction("Index", "Home");
                    return(LocalRedirect("/home/index"));
                }
            }
            catch (Exception e) when(e is ControllerNotFoundException || e is ControllerBadRequestException || e is ControllerUnauthorizedException)
            {
                ModelState.AddModelError(string.Empty, e.Message);
                return(Page());
            }
        }
예제 #15
0
        public ActionResult <CovenantUser> EditUser([FromBody] CovenantUser user)
        {
            var matching_user = _context.Users.FirstOrDefault(U => user.Id == U.Id);

            if (matching_user == null)
            {
                return(NotFound());
            }
            _context.Users.Update(matching_user);
            _context.SaveChanges();
            return(Ok(matching_user));
        }
예제 #16
0
파일: GruntHub.cs 프로젝트: xct/Covenant
        public async Task GetInteract(string gruntName, string input)
        {
            CovenantUser user = await _service.GetUser(this.Context.UserIdentifier);

            Grunt grunt = await _service.GetGruntByName(gruntName);

            GruntCommand command = await _service.InteractGrunt(grunt.Id, user.Id, input);

            if (!string.IsNullOrWhiteSpace(command.CommandOutput.Output))
            {
                await this.Clients.Caller.SendAsync("ReceiveCommandOutput", command);
            }
        }
예제 #17
0
        public async Task GetInteract(string gruntName, string input)
        {
            CovenantUser user = await _context.GetUserByUsername(this.Context.User.Identity.Name);

            Grunt grunt = await _context.GetGruntByName(gruntName);

            GruntCommand command = await interact.Input(user, grunt, input);

            if (!string.IsNullOrWhiteSpace(command.CommandOutput.Output))
            {
                await this.Clients.Caller.SendAsync("ReceiveCommandOutput", command);
            }
        }
예제 #18
0
        // POST: /grunttasking/create
        public async Task <IActionResult> Create(GruntTasking tasking)
        {
            try
            {
                CovenantUser currentUser = await _context.GetCurrentUser(_userManager, HttpContext.User);

                tasking.Grunt = await _context.GetGrunt(tasking.GruntId);

                tasking.GruntTask = await _context.GetGruntTask(tasking.GruntTaskId);

                tasking.Type = tasking.GruntTask.TaskingType;
                for (int i = 0; i < Math.Min(tasking.Parameters.Count, tasking.GruntTask.Options.Count); i++)
                {
                    if (tasking.Parameters[i] == null)
                    {
                        tasking.Parameters[i] = "";
                        tasking.GruntTask.Options[i].Value = "";
                    }
                    else
                    {
                        tasking.GruntTask.Options[i].Value = tasking.Parameters[i];
                    }
                }
                for (int i = tasking.Parameters.Count; i < tasking.GruntTask.Options.Count; i++)
                {
                    tasking.GruntTask.Options[i].Value = "";
                }
                GruntCommand createdCommand = await _context.CreateGruntCommand(new GruntCommand
                {
                    Command         = GetCommand(tasking),
                    CommandTime     = DateTime.UtcNow,
                    CommandOutputId = 0,
                    CommandOutput   = new CommandOutput(),
                    User            = currentUser,
                    GruntId         = tasking.Grunt.Id,
                    Grunt           = tasking.Grunt
                }, _grunthub, _eventhub);

                tasking.GruntCommand   = createdCommand;
                tasking.GruntCommandId = createdCommand.Id;

                GruntTasking created = await _context.CreateGruntTasking(tasking, _grunthub);

                return(RedirectToAction(nameof(Interact), new { id = created.Id }));
            }
            catch (Exception e) when(e is ControllerNotFoundException || e is ControllerBadRequestException || e is ControllerUnauthorizedException)
            {
                return(RedirectToAction(nameof(Index)));
            }
        }
예제 #19
0
        public static async void InitializeUsers(UserManager <CovenantUser> userManager, IConfiguration configuration)
        {
            CovenantUser existing = await userManager.FindByNameAsync(configuration["CovenantUsername"]);

            if (existing == null)
            {
                CovenantUser user = new CovenantUser {
                    UserName = configuration["CovenantUsername"]
                };
                IdentityResult userResult = await userManager.CreateAsync(user, configuration["CovenantPassword"]);

                await userManager.AddToRoleAsync(user, "User");

                await userManager.AddToRoleAsync(user, "Administrator");
            }
        }
예제 #20
0
        public async Task <IActionResult> Edit(CovenantUserLogin login)
        {
            try
            {
                CovenantUser user = await _context.GetUserByUsername(login.UserName);

                await _context.EditUser(_userManager, user, login);

                return(RedirectToAction(nameof(Index)));
            }
            catch (Exception e) when(e is ControllerNotFoundException || e is ControllerBadRequestException || e is ControllerUnauthorizedException)
            {
                return(View(new CovenantUserLogin {
                    UserName = login.UserName, Password = "******"
                }));
            }
        }
예제 #21
0
        public async Task <ActionResult <HttpListener> > CreateHttpListener([FromBody] HttpListener listener = null)
        {
            if (listener == null || listener.Id == 0)
            {
                ListenerType httpType = _context.ListenerTypes.FirstOrDefault(LT => LT.Name == "HTTP");
                if (httpType == null)
                {
                    return(BadRequest());
                }
                listener = (HttpListener)_context.Listeners.FirstOrDefault(L => L.ListenerTypeId == httpType.Id && L.Status == Listener.ListenerStatus.Uninitialized);
                if (listener != null)
                {
                    return(Ok(listener));
                }
                else
                {
                    Profile profile = _context.Profiles.FirstOrDefault(HP => HP.Id == 1);
                    listener = new HttpListener(httpType.Id, profile.Id);
                }
            }

            // Append capital letter to appease Password complexity requirements, get rid of warning output
            string       covenantListenerUsername = Utilities.CreateSecureGuid().ToString();
            string       covenantListenerPassword = Utilities.CreateSecureGuid().ToString() + "A";
            CovenantUser covenantListenerUser     = new CovenantUser {
                UserName = covenantListenerUsername
            };
            await _userManager.CreateAsync(covenantListenerUser, covenantListenerPassword);

            await _userManager.AddToRoleAsync(covenantListenerUser, "Listener");

            var signInResult = await _signInManager.PasswordSignInAsync(covenantListenerUser.UserName, covenantListenerPassword, true, false);

            var token = Utilities.GenerateJwtToken(
                covenantListenerUser.UserName, covenantListenerUser.Id, new[] { "Listener" },
                _configuration["JwtKey"], _configuration["JwtIssuer"],
                _configuration["JwtAudience"], _configuration["JwtExpireDays"]
                );

            listener.CovenantToken = token;

            _context.Listeners.Add(listener);
            _context.SaveChanges();
            return(Ok(listener));
        }
 public async Task <ActionResult <CovenantUser> > EditUser([FromBody] CovenantUser user)
 {
     try
     {
         return(await _service.EditUser(user));
     }
     catch (ControllerNotFoundException e)
     {
         return(NotFound(e.Message));
     }
     catch (ControllerBadRequestException e)
     {
         return(BadRequest(e.Message));
     }
     catch (ControllerUnauthorizedException)
     {
         return(new UnauthorizedResult());
     }
 }
        public async Task <ActionResult <GruntCommand> > InteractGrunt(int id, [FromBody] string command)
        {
            try
            {
                CovenantUser user = await _service.GetCurrentUser(this.HttpContext.User);

                GruntCommand gruntCommand = await _service.InteractGrunt(id, user.Id, command);

                return(CreatedAtRoute("GetGruntCommand", new { id = gruntCommand.Id }, gruntCommand));
            }
            catch (ControllerNotFoundException e)
            {
                return(NotFound(e.Message));
            }
            catch (ControllerBadRequestException e)
            {
                return(BadRequest(e.Message));
            }
        }
예제 #24
0
        public async Task <IActionResult> Create(CovenantUserRegister register)
        {
            try
            {
                if (register.Password != register.ConfirmPassword)
                {
                    return(BadRequest($"BadRequest - Password does not match ConfirmPassword."));
                }

                if (!_userManager.Users.Any())
                {
                    CovenantUser user = new CovenantUser {
                        UserName = register.UserName
                    };
                    IdentityResult userResult = await _userManager.CreateAsync(user, register.Password);

                    await _userManager.AddToRoleAsync(user, "User");

                    await _userManager.AddToRoleAsync(user, "Administrator");

                    await _signInManager.PasswordSignInAsync(register.UserName, register.Password, true, lockoutOnFailure : false);
                }
                else if (_signInManager.IsSignedIn(HttpContext.User) && HttpContext.User.IsInRole("Administrator"))
                {
                    CovenantUser user = new CovenantUser {
                        UserName = register.UserName
                    };
                    IdentityResult userResult = await _userManager.CreateAsync(user, register.Password);

                    await _userManager.AddToRoleAsync(user, "User");
                }
                else
                {
                    return(new UnauthorizedResult());
                }
                return(RedirectToAction("Index", "Home"));
            }
            catch (Exception e) when(e is ControllerNotFoundException || e is ControllerBadRequestException || e is ControllerUnauthorizedException)
            {
                ModelState.AddModelError(string.Empty, e.Message);
                return(RedirectToAction("Index", "Home"));
            }
        }
예제 #25
0
        public override void Command(MenuItem menuItem, string UserInput)
        {
            UsersMenuItem usersMenuItem = (UsersMenuItem)menuItem;

            usersMenuItem.Refresh();
            string[] commands = UserInput.Split(" ");
            if (commands.Length < 3 || commands.Length > 4 || commands[0].ToLower() != "create")
            {
                menuItem.PrintInvalidOptionError(UserInput);
                EliteConsole.PrintFormattedErrorLine("Usage: Create <username> <password> [<roles>]");
                return;
            }
            CovenantUser user = this.CovenantClient.ApiUsersPost(new CovenantUserLogin(commands[1], commands[2]));

            if (user != null)
            {
                EliteConsole.PrintFormattedHighlightLine("Created user: \"" + commands[1] + "\"");
                if (commands.Length == 4)
                {
                    string[] roleNames = commands[3].Split(",");
                    foreach (string roleName in roleNames)
                    {
                        IdentityRole role = this.CovenantClient.ApiRolesGet().FirstOrDefault(R => R.Name == roleName);
                        if (role != null)
                        {
                            IdentityUserRoleString roleResult = this.CovenantClient.ApiUsersByUidRolesByRidPost(user.Id, role.Id);
                            if (roleResult.UserId == user.Id && roleResult.RoleId == role.Id)
                            {
                                EliteConsole.PrintFormattedHighlightLine("Added user: \"" + commands[1] + "\"" + " to role: \"" + roleName + "\"");
                            }
                            else
                            {
                                EliteConsole.PrintFormattedErrorLine("Failed to add user: \"" + commands[1] + "\" to role: \"" + roleName + "\"");
                            }
                        }
                    }
                }
            }
            else
            {
                EliteConsole.PrintFormattedErrorLine("Failed to create user: \"" + commands[1] + "\"");
            }
        }
예제 #26
0
        public ActionResult <HttpListener> CreateHttpListener([FromBody] HttpListener listener)
        {
            ListenerType httpType = _context.ListenerTypes.FirstOrDefault(LT => LT.Name == "HTTP");

            if (httpType == null)
            {
                return(NotFound($"NotFound - HttpListener"));
            }
            listener = (HttpListener)_context.Listeners.FirstOrDefault(L => L.ListenerTypeId == httpType.Id && L.Status == Listener.ListenerStatus.Uninitialized);
            if (listener != null)
            {
                return(listener);
            }
            else
            {
                Profile profile = _context.Profiles.FirstOrDefault(HP => HP.Id == 1);
                listener = new HttpListener(httpType.Id, profile.Id);
            }

            // Append capital letter to appease Password complexity requirements, get rid of warning output
            string       covenantListenerUsername = Utilities.CreateSecureGuid().ToString();
            string       covenantListenerPassword = Utilities.CreateSecureGuid().ToString() + "A";
            CovenantUser covenantListenerUser     = new CovenantUser {
                UserName = covenantListenerUsername
            };

            this.CreateCovenantUser(covenantListenerUser, covenantListenerPassword);
            this.CreateUserRole(covenantListenerUser, "Listener");

            var signInResult = this.GetPasswordSignInResult(covenantListenerUser.UserName, covenantListenerPassword);
            var token        = Utilities.GenerateJwtToken(
                covenantListenerUser.UserName, covenantListenerUser.Id, new[] { "Listener" },
                _configuration["JwtKey"], _configuration["JwtIssuer"],
                _configuration["JwtAudience"], _configuration["JwtExpireDays"]
                );

            listener.CovenantToken = token;

            _context.Listeners.Add(listener);
            _context.SaveChanges();
            return(listener);
        }
예제 #27
0
        public async Task <int> RunAsync(string newUsername, string newPassword)
        {
            var request = new RequestBuilder(Api);

            CovenantUser user = await request.CreateUser(newUsername, newPassword);

            Console.WriteLine($"Added User: {user.UserName} - {user.Id}");
            IList <IdentityRole> roles = await request.GetRoles();

            foreach (IdentityRole role in roles)
            {
                if (role.Name.ToLower() == "user" || role.Name.ToLower() == "administrator")
                {
                    await request.AddUserRole(user.Id, role.Id);

                    Console.WriteLine($"Added User to Role: {role.Name}");
                }
            }
            return(0);
        }
예제 #28
0
        public async Task <ActionResult <CovenantUser> > CreateUser([FromBody] CovenantUserLogin login)
        {
            try
            {
                CovenantUser user = await _context.CreateUser(_userManager, login, _eventhub);

                return(CreatedAtRoute(nameof(GetUser), new { id = user.Id }, user));
            }
            catch (ControllerNotFoundException e)
            {
                return(NotFound(e.Message));
            }
            catch (ControllerBadRequestException e)
            {
                return(BadRequest(e.Message));
            }
            catch (ControllerUnauthorizedException)
            {
                return(new UnauthorizedResult());
            }
        }
        public async Task <ActionResult <CovenantUser> > CreateUser([FromBody] CovenantUserRegister register)
        {
            try
            {
                CovenantUser user = await _service.CreateUserVerify(HttpContext.User, register);

                return(CreatedAtRoute(nameof(GetUser), new { id = user.Id }, user));
            }
            catch (ControllerNotFoundException e)
            {
                return(NotFound(e.Message));
            }
            catch (ControllerBadRequestException e)
            {
                return(BadRequest(e.Message));
            }
            catch (ControllerUnauthorizedException)
            {
                return(new UnauthorizedResult());
            }
        }
예제 #30
0
        public async Task <IActionResult> EditRoles(EditRolesModel roleadd)
        {
            try
            {
                CovenantUser user = await _context.GetUserByUsername(roleadd.UserName);

                IEnumerable <string> userRoles = (await _context.GetUserRoles(user.Id)).Select(UR =>
                {
                    Task <IdentityRole> t = _context.GetRole(UR.RoleId);
                    t.Wait();
                    return(t.Result.Name);
                });

                IEnumerable <string> userRolesRemain = userRoles.Where(UR => roleadd.Rolenames.Contains(UR));
                foreach (string rolename in roleadd.Rolenames)
                {
                    // Selected role that has not been added, must add
                    if (!userRolesRemain.Contains(rolename))
                    {
                        IdentityRole role = await _context.GetRoleByName(rolename);

                        await _context.CreateUserRole(_userManager, user.Id, role.Id);
                    }
                }

                IEnumerable <string> userRolesNotRemain = userRoles.Where(UR => !roleadd.Rolenames.Contains(UR));
                foreach (string rolename in userRolesNotRemain)
                {
                    // Did not select role that is already added, must remove
                    IdentityRole role = await _context.GetRoleByName(rolename);

                    await _context.DeleteUserRole(_userManager, user.Id, role.Id);
                }
                return(RedirectToAction(nameof(Index)));
            }
            catch (Exception e) when(e is ControllerNotFoundException || e is ControllerBadRequestException || e is ControllerUnauthorizedException)
            {
                return(RedirectToAction(nameof(Index)));
            }
        }