public static bool AddUser2Role(int _userId, int _roleId) { bool _retVal = false; try { using (RBACDbContext db = new RBACDbContext()) { ApplicationUser _user = GetUser(db, _userId); if (_user.Roles.Where(p => p.RoleId == _roleId).Count() == 0) { //_user.UserRoles.Add(_role); ApplicationUserRole _identityRole = new ApplicationUserRole { UserId = _userId, RoleId = _roleId }; if (!_user.Roles.Contains(_identityRole)) { _user.Roles.Add(_identityRole); } _user.LastModified = DateTime.Now; db.Entry(_user).State = EntityState.Modified; db.SaveChanges(); _retVal = true; } } } catch (Exception) { } return(_retVal); }
public static ApplicationIdentityUserRole ToApplicationIdentityUserRole(this ApplicationUserRole role) { return(role == null ? null : new ApplicationIdentityUserRole() { RoleId = role.RoleId, UserId = role.UserId }); }
public async override Task AddToRoleAsync(ApplicationUser user, string normalizedRoleName, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); ValidateParameters(user, normalizedRoleName); var roleEntity = await FindRoleAsync(normalizedRoleName, cancellationToken) ?? throw new InvalidOperationException($"Invalid role name [{normalizedRoleName}] to assign to user."); var roleAssignment = new ApplicationUserRole() { UserId = user.Id, RoleId = roleEntity.Id, ClientId = userPrincipalBuilder.GetCurrentClientId() }; Context.Set <ApplicationUserRole>().Add(roleAssignment); if (!user.IsSystemUser) { await auditTrailProvider.AddTrailsAsync(AuditOperation.Create, userPrincipalBuilder.UserPrincipal.UserName, new AuditableObjects <ApplicationUserRole>($"{roleAssignment.UserId}.{roleAssignment.RoleId}.{roleAssignment.ClientId}", roleAssignment), new string[] { nameof(ApplicationUserRole.IdentityUser), nameof(ApplicationUserRole.IdentityRole), nameof(ApplicationUserRole.UserName), nameof(ApplicationUserRole.Role) }); } }
public async Task <IActionResult> Delete([FromBody] ApplicationUserRole _ApplicationUserRole) { try { ApplicationUserRole customer = _context.UserRoles .Where(x => x.RoleId == _ApplicationUserRole.RoleId) .Where(x => x.UserId == _ApplicationUserRole.UserId) .FirstOrDefault(); if (customer != null) { _context.UserRoles.Remove(customer); await _context.SaveChangesAsync(); return(await Task.Run(() => Ok(_ApplicationUserRole))); } else { _logger.LogError($"No existe ese usuario con el rol enviado!"); return(await Task.Run(() => BadRequest($"No existe ese usuario con el rol enviado!"))); } } catch (Exception ex) { _logger.LogError($"Ocurrio un error: { ex.ToString() }"); return(await Task.Run(() => BadRequest($"Ocurrio un error:{ex.Message}"))); } }
public void ApplicationUserRole_PublicProperties() { var applicationRole = new ApplicationRole() { Id = "id" }; var testDate = DateTime.Today; var user = new ApplicationUser { Id = "123" }; var obj = new ApplicationUserRole { Role = applicationRole, CreatedAt = testDate, LastModifiedAt = testDate, CreatedBy = user, CreatedBy_Id = "123", LastModifiedBy = user, LastModifiedBy_Id = "123" }; Assert.AreEqual(applicationRole, obj.Role); Assert.AreEqual(testDate, obj.CreatedAt); Assert.AreEqual(testDate, obj.LastModifiedAt); Assert.AreEqual(user.Id, obj.CreatedBy_Id); Assert.AreEqual(user.Id, obj.LastModifiedBy_Id); }
//[AuthorizeOrErrorPage(Roles = UserRoles.Administrators)] public ActionResult Edit([Bind(Include = "Id,Email,PhoneNumber,UserName,RoleId")] UserEditViewModel viewModel) { ApplicationUser UpdatedUser = new ApplicationUser(); ApplicationUser existingUser = _db.Users.Find(viewModel.Id); var userRole = _db.UserRole.Where(x => x.UserId == existingUser.Id).FirstOrDefault(); if (ModelState.IsValid) { UpdatedUser = Mapper.Map(viewModel, existingUser); _db.Entry(UpdatedUser).State = EntityState.Modified; if (userRole == null) { var newUserRole = new ApplicationUserRole { Id = Guid.NewGuid(), UserId = UpdatedUser.Id, RoleId = UpdatedUser.RoleId }; _db.Entry(newUserRole).State = EntityState.Added; } else { userRole.RoleId = UpdatedUser.RoleId; _db.Entry(userRole).State = EntityState.Modified; } _db.SaveChanges(); return(RedirectToAction("Index")); } return(View(UpdatedUser)); }
public async Task <ActionResult <ApplicationRole> > Delete([FromBody] ApplicationUserRole _rol) { try { string baseadress = config.Value.urlbase; HttpClient _client = new HttpClient(); _client.DefaultRequestHeaders.Add("Authorization", "Bearer " + HttpContext.Session.GetString("token")); _rol.UsuarioCreacion = "l"; _rol.UsuarioModificacion = "l"; var result = await _client.PostAsJsonAsync(baseadress + "api/UserRol/Delete", _rol); string valorrespuesta = ""; if (result.IsSuccessStatusCode) { valorrespuesta = await(result.Content.ReadAsStringAsync()); _rol = JsonConvert.DeserializeObject <ApplicationUserRole>(valorrespuesta); } } catch (Exception ex) { _logger.LogError($"Ocurrio un error: { ex.ToString() }"); return(BadRequest($"Ocurrio un error: {ex.Message}")); } // return new ObjectResult(new DataSourceResult { Data = new[] { RoleId }, Total = 1 }); return(new ObjectResult(new DataSourceResult { Data = new[] { _rol }, Total = 1 })); }
public IActionResult GetOverview(bool logsAndCountersOnly) { try { string userId = GetCurrentUserId(); ApplicationUserRole role = GetCurrentUserRole(); object overview = null; switch (role) { case ApplicationUserRole.TeamMember: overview = _users.GetTeamMemberOverview(userId); break; case ApplicationUserRole.Supervisor: overview = _users.GetSupervisorOverview(userId, logsAndCountersOnly); break; case ApplicationUserRole.Admin: overview = _users.GetAdminOverview(userId, logsAndCountersOnly); break; } return(Ok(overview)); } catch (ClientException ex) { return(BadRequest(new { message = ex.Message })); } catch (Exception ex) { return(StatusCode(500, new { message = ex.Message })); } }
public async Task <IActionResult> Edit(Guid id, ApplicationUserRole applicationUserRole) { if (id != applicationUserRole.UserId) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(applicationUserRole); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ApplicationUserRoleExists(applicationUserRole.UserId)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(applicationUserRole)); }
public async Task <ActionResult <ApplicationUserRole> > Update(string Id, ApplicationUserRole _rol) { try { // TODO: Add insert logic here string baseadress = config.Value.urlbase; HttpClient _client = new HttpClient(); _client.DefaultRequestHeaders.Add("Authorization", "Bearer " + HttpContext.Session.GetString("token")); var result = await _client.PutAsJsonAsync(baseadress + "api/UserRol/Update", _rol); string valorrespuesta = ""; if (result.IsSuccessStatusCode) { valorrespuesta = await(result.Content.ReadAsStringAsync()); _rol = JsonConvert.DeserializeObject <ApplicationUserRole>(valorrespuesta); } } catch (Exception ex) { _logger.LogError($"Ocurrio un error: { ex.ToString() }"); return(BadRequest($"Ocurrio un error{ex.Message}")); } return(new ObjectResult(new DataSourceResult { Data = new[] { _rol }, Total = 1 })); }
private void UpdateApplicationUserRoles(string[] selectedRoles, ApplicationUser applicationUserToUpdate) { if (selectedRoles == null) { applicationUserToUpdate.UserRoles = new List <ApplicationUserRole>(); return; } var rolesToAssignHS = new HashSet <string>(selectedRoles); var assignedRoles = new HashSet <string>(applicationUserToUpdate.UserRoles.Select(ur => ur.Role.Id)); foreach (var rolePot in _context.ApplicationRole) { if (rolesToAssignHS.Contains(rolePot.Id)) { if (!assignedRoles.Contains(rolePot.Id)) { applicationUserToUpdate.UserRoles.Add(new ApplicationUserRole { UserId = applicationUserToUpdate.Id, RoleId = rolePot.Id }); } } else { if (assignedRoles.Contains(rolePot.Id)) { ApplicationUserRole roleToRemove = applicationUserToUpdate.UserRoles.SingleOrDefault(au => au.RoleId == rolePot.Id); _context.Remove(roleToRemove); } } } }
public IActionResult Details(int taskId) { ProjectTask task = _tasksMethods.GetByIdWithProjectTitle(taskId); if (task == null) { return(NotFound()); } string currentUserId = GetCurrentUserId(); ApplicationUserRole currentUserRole = GetCurrentUserRole(); bool isProjectSupervisor = false; if (currentUserRole == ApplicationUserRole.TeamMember && !_projectsMethods.MemberCanAccessProject(currentUserId, task.ProjectId)) { return(NotFound()); } else if (currentUserRole == ApplicationUserRole.Supervisor) { isProjectSupervisor = _projectsMethods.IsSupervisorOfProject(currentUserId, task.ProjectId); } ViewData["IsProjectSupervisor"] = isProjectSupervisor; return(View(task)); }
public IActionResult Index(int projectId) { Project project = _projectsMethods.GetById(projectId); if (project == null) { return(NotFound()); } string currentUserId = GetCurrentUserId(); ApplicationUserRole currentUserRole = GetCurrentUserRole(); bool isProjectSupervisor = false; if (currentUserRole == ApplicationUserRole.TeamMember && !_projectsMethods.MemberCanAccessProject(currentUserId, project.ID)) { return(NotFound()); } else if (currentUserRole == ApplicationUserRole.Supervisor) { isProjectSupervisor = _projectsMethods.IsSupervisorOfProject(currentUserId, project.ID); } ViewData["IsProjectSupervisor"] = isProjectSupervisor; return(View(project)); }
//PUT : /api/Administration/ public async Task <IActionResult> UpdateUserRole(string id, ApplicationUserRole applicationUserRole) { var user = await _userManager.FindByIdAsync(id); var role = await _roleManager.FindByNameAsync(applicationUserRole.Role); var oldRoles = await _userManager.GetRolesAsync(user); if (role == null) { return(BadRequest()); } IdentityResult result = null; if (oldRoles != null) { result = await _userManager.RemoveFromRolesAsync(user, oldRoles.ToArray()); _context.ApplicationUserRoles.Update(applicationUserRole); if (result.Succeeded) { result = await _userManager.AddToRoleAsync(user, role.Name); } } else { result = await _userManager.AddToRoleAsync(user, role.Name); } return(Ok(result)); }
public void CanAddUserRoles() { Guid userID = uow.RolePermissionRepo.GetApplicationUserByName("Admin"); uow.RolePermissionRepo.DeleteRoleByRoleName("AddUserRole"); ApplicationRole newRole = new ApplicationRole() { Name = "AddUserRole", Description = "CanAddUserRole", }; uow.RolePermissionRepo.AddNewRole(newRole); string RoleID = newRole.Id; ApplicationUserRole newUserRole = new ApplicationUserRole() { UserId = userID.ToString(), RoleId = RoleID, }; uow.RolePermissionRepo.AddNewUserRoles(newUserRole); uow.SaveChanges(); Assert.IsNotNull(uow.RolePermissionRepo.GetApplicationUserRole(userID.ToString(), RoleID)); }
public async Task AddUserToRole(AddToRoleDto model) { await ProcessRequest(async() => { ApplicationUser existingUser = await _unitOfWork.User.FindByNameAsync(model.UserName); if (existingUser == null) { throw new AppException(_logger, $"User name: {model.UserName} not found"); } List <ApplicationRole> currentRole = existingUser.UserRoles.Select(x => x.Role).ToList(); var existingRole = await _unitOfWork.Role.FindByNameAsync(model.RoleName); if (existingRole == null) { throw new AppException(_logger, $"Role name: {model.RoleName} not found"); } if (currentRole.Select(x => x.Name).Contains(model.RoleName.ToLower())) { throw new AppException(_logger, $"User already has an {model.RoleName} role"); } ApplicationUserRole applicationUserRole = new ApplicationUserRole() { RoleId = existingRole.Id, UserId = existingUser.Id }; await _unitOfWork.UserRole.CreateAsync(applicationUserRole); await _unitOfWork.SaveAsync(); }); }
public IActionResult AddUser(RolesAddUserViewModel model) { try { // make sure Administrator can not assign the role of Administrator or Superuser if (User.IsInRole("Administrator") && (model.RoleId == 1 || model.RoleId == 2)) { throw new ArgumentException("Only Superusers can assign this role."); } // New UserRole var userRole = new ApplicationUserRole() { RoleId = model.RoleId, UserId = model.UserId }; _context.UserRoles.Add(userRole); _context.SaveChanges(); return(RedirectToAction(nameof(Index))); // i don't remember writing this } catch (ArgumentException ex) { TempData["Error"] = ex.Message; return(RedirectToAction("AddUser", new { id = model.RoleId })); } }
public async Task <IdentityResult> AddToRoleAsync(ApplicationUser user, ApplicationTenant tenant, string role) { try { var Role = DbContext.Roles.Where(q => q.Name == role).FirstOrDefault(); if (Role != null) { ApplicationUserRole userRole = new ApplicationUserRole(); userRole.Role = Role; userRole.RoleId = Role.Id; userRole.Tenant = tenant; userRole.TenantId = tenant.Id; userRole.User = user; userRole.UserId = user.Id; var result = await DbContext.UserRoles.AddAsync(userRole); await DbContext.SaveChangesAsync(); return(IdentityResult.Success); } // if we got this far is because we did not found the role. return(IdentityResult.Failed(new IdentityError { Code = "RoleNotFound", Description = "Role not found" })); } catch (Exception ex) { return(IdentityResult.Failed(new IdentityError { Code = ex.HResult.ToString(), Description = ex.Message })); } }
public async Task <IdentityUserRole <string> > ChangeUserRole(ApplicationUserRole existingApplicationUserRole, string roleName) { try { var user = await _applicationContext.ApplicationUsers.FindAsync(existingApplicationUserRole.UserId); var existingRole = await _applicationContext.Roles.FindAsync(existingApplicationUserRole.RoleId); var proposedRole = await _applicationContext.Roles.SingleAsync(r => r.Name == roleName); var removeResult = await _userManager.RemoveFromRoleAsync(user, existingRole.Name); await _userManager.UpdateAsync(user); var addresult = await _userManager.AddToRoleAsync(user, proposedRole.Name); await _userManager.UpdateAsync(user); return(await _applicationContext.UserRoles.SingleOrDefaultAsync(i => i.UserId == user.Id && i.RoleId == proposedRole.Id)); } catch (Exception) { throw; } }
public static IdentityResult AddToRole(this ApplicationUserManager userManager, string userId, string[] roles, string assigner) { try { ApplicationUserRole role = null; using (ApplicationDbContext context = new ApplicationDbContext()) { foreach (var item in roles) { role = new ApplicationUserRole(); role.UserId = userId; role.RoleAssigner = assigner; role.RoleId = item; context.AspNetUserRoles.Add(role); } context.SaveChanges(); } return(new IdentityResult() { }); } catch (Exception ex) { return(new IdentityResult(ex.Message)); } }
public Task AddToRoleAsync(ApplicationUser user, string roleName, CancellationToken cancellationToken) { var temp = user ?? throw new ArgumentNullException(nameof(user)); if (string.IsNullOrEmpty(roleName)) { return(Task.FromResult(new object())); } return(_context.Roles.FirstOrDefaultAsync(m => m.NormalizedName.Equals( roleName, StringComparison.InvariantCultureIgnoreCase)) .ContinueWith(m => { if (m.Result != null) { ApplicationUserRole userRole = new ApplicationUserRole() { Id = IdGenerator.GenerateObjectId().ToString(), UserId = user.Id, RoleId = m.Result.Id, }; _context.Add(userRole); _context.SaveChanges(); } }, cancellationToken)); }
public void AddNewUserRoles(ApplicationUserRole newAppRole) { ApplicationDbContext UsersContext = new ApplicationDbContext(); UsersContext.Set <ApplicationUserRole>().Add(newAppRole); UsersContext.SaveChanges(); }
public void SeedUser( ModelBuilder builder, PasswordHasher <ApplicationUser> hasher, string byUserId, string id, string username, string email, string fn, string ln, string password, string title, ApplicationUserRole role, DateTime dob ) { builder.Entity <ApplicationUser>().HasData(new ApplicationUser { Id = id, UserName = username, FirstName = fn, LastName = ln, NormalizedUserName = username.ToUpper(), Email = email, NormalizedEmail = email.ToUpper(), EmailConfirmed = true, PasswordHash = hasher.HashPassword(null, password), SecurityStamp = string.Empty, RoleAssignedByUserId = byUserId, RoleAssignedDate = DateTime.Now, Title = title, RoleCode = (short)role, DateOfBirth = dob }); }
public async Task SeedAsync(ApplicationDbContext context, IServiceProvider services) { if (!context.Users.Any()) { _userManager = services.GetRequiredService <UserManager <ApplicationUser> >(); _roleManager = services.GetRequiredService <RoleManager <ApplicationUserRole> >(); var defaultRole = new ApplicationUserRole { Name = "Administrators", NormalizedName = "Administrators" }; await _roleManager.CreateAsync(defaultRole); var defaultUser = new ApplicationUser { UserName = "******", Email = "*****@*****.**", NormalizedUserName = "******", Avatar = "img.jpg", SecurityStamp = DateTime.Now.Ticks.ToString() }; var result = await _userManager.CreateAsync(defaultUser, "admin"); if (!result.Succeeded) { throw new Exception("初始默认用户失败"); } await _userManager.AddToRoleAsync(defaultUser, "Administrators"); } }
public ActionResult AddUserToRole(FormCollection collection) { ViewBag.Continental = (db.Continentals); if (collection != null) { string r = collection.Get("Role"); string u = collection.Get("User"); var UserRole = new ApplicationUserRole { RoleId = r,//"29b11ba5-a1cd-454a-aca5-a12f23e89764", UserId =u //"4caa7e95-8129-4c5c-be3f-b377c39f3bb3" }; try { db.ApplicationUserRoles.Add(UserRole); db.SaveChanges(); ViewData["Role"] = new SelectList(db.Roles, "Id", "Name"); ViewData["User"] = new SelectList(db.Users, "Id", "UserName"); return View(); } catch { ViewData["Role"] = new SelectList(db.Roles, "Id", "Name"); ViewData["User"] = new SelectList(db.Users, "Id", "UserName"); return View(); } } else { return HttpNotFound(); } }
public async Task <ActionResult <ApplicationUserRole> > Insert([FromBody] ApplicationUserRole _ApplicationUserRole) { try { List <ApplicationUserRole> _listrole = (_context.UserRoles .Where(q => q.RoleId == _ApplicationUserRole.RoleId) .Where(q => q.UserId == _ApplicationUserRole.UserId) ).ToList(); if (_listrole.Count == 0) { // IdentityUserRole<string> _userrole = mapper.Map<IdentityUserRole<string>>(_ApplicationUserRole); _context.UserRoles.Add(_ApplicationUserRole); await _context.SaveChangesAsync(); return(await Task.Run(() => Ok(_ApplicationUserRole))); } else { _logger.LogError($"Ya existe esta agregado el rol para el usuario"); return(await Task.Run(() => BadRequest("Ya existe esta agregado el rol para el usuario!"))); } } catch (Exception ex) { _logger.LogError($"Ocurrio un error: { ex.ToString() }"); return(await Task.Run(() => BadRequest($"Ocurrio un error:{ex.Message}"))); } // ApplicationUserRole _userrole = _ApplicationUserRole; }
public IActionResult Register(RegisterDTO dto) { string userId = Guid.NewGuid().ToString(); ApplicationUserRole userRole = new ApplicationUserRole() { RoleId = ApplicationRolesConst.ApplicationUserRoleId, UserId = userId }; List <ApplicationUserRole> LST = new List <ApplicationUserRole>(); LST.Add(userRole); ApplicationUser identityUser = new ApplicationUser() { Id = userId, UserName = dto.UserName, PasswordHash = HashGenerator.GenerateHash(dto.Password), UserRoles = LST }; var user = _userManager.CreateAsync(identityUser).Result; if (user != null) { return(Ok()); } else { return(BadRequest()); } }
public IActionResult GetCurrentUserTeamsViewModel() { try { string userId = GetCurrentUserId(); ApplicationUserRole role = GetCurrentUserRole(); if (role == ApplicationUserRole.Admin) { // this will get all the teams userId = null; } else if (role != ApplicationUserRole.Supervisor) { throw new UnauthorizedAccessException("unauthorized"); } List <SupervisingTeamModel> model = _teamsMethods.GetSupervisingTeamsModel(userId); return(Ok(model)); } catch (ClientException ex) { return(BadRequest(new { message = ex.Message })); } catch (Exception ex) { return(StatusCode(500, new { message = ex.Message })); } }
public async Task UpdateAsync(ApplicationUser newEnt, int id, int roleId) { ApplicationUser oldEnt = await GetAsync(id); if (oldEnt != null) { ApplicationUserRole userRole = oldEnt.UserRoles.First(); if (userRole != null) { ApplicationUserRole newUserRole = new ApplicationUserRole(); var existingUserRole = _context.UserRoles.IgnoreQueryFilters().Where(x => x.UserId == oldEnt.Id && x.RoleId == roleId).FirstOrDefault(); if (existingUserRole != null) { existingUserRole.IsDeleted = false; oldEnt.UserRoles.First().IsDeleted = true; } else { newUserRole.RoleId = roleId; newUserRole.UserId = oldEnt.Id; oldEnt.UserRoles.Remove(userRole); oldEnt.UserRoles.Add(newUserRole); } } // Update operations should be handled outside of repositories (in services) _context.Entry(oldEnt).CurrentValues.SetValues(newEnt); oldEnt.Update(newEnt); } }
/// <summary> /// convert new account view model to domain /// </summary> /// <param name="model"></param> /// <returns></returns> public ApplicationUser ConvertToDomain(NewAccountViewModel model) { ApplicationUser user = new ApplicationUser(); user.UserName = model.UserName; user.FirstName = model.FirstName; user.LastName = model.LastName; user.Email = model.Email; user.Phone = model.Phone; user.Department = model.Department; user.Position = model.Position; user.IsActive = true; if (model.Roles != null) { user.UserRoles = new List <ApplicationUserRole>(); foreach (var role in model.Roles) { if (role.Selected) { ApplicationUserRole userRole = new ApplicationUserRole(); { userRole.UserId = user.Id; userRole.RoleId = role.RoleId; } user.UserRoles.Add(userRole); } } } return(user); }
public async Task <IActionResult> PutApplicationUserRole(string userid, ApplicationUserRole existingApplicationUserRole, string rolename) { if (userid != existingApplicationUserRole.UserId) { return(BadRequest()); } try { await _iApplicationUserRole.ChangeUserRole(existingApplicationUserRole, rolename); } catch (DbUpdateConcurrencyException) { if (!_iApplicationUserRole.ApplicationUserRoleExists(existingApplicationUserRole)) { return(NotFound()); } else { return(Problem()); } } return(NoContent()); }