예제 #1
0
        public async Task <IActionResult> AssignUserToRole(int id, int roleid)
        {
            ApplicationUser user = await usermanager.FindByIdAsync(id.ToString());

            if (user == null)
            {
                return(NotFound());
            }

            ApplicationRole role = await rolemanager.FindByIdAsync(roleid.ToString());

            if (role == null)
            {
                return(NotFound());
            }

            IdentityResult result = await usermanager.AddToRoleAsync(user, role.Name);

            if (result.Succeeded)
            {
                return(Ok());
            }

            return(BadRequest(result.Errors));
        }
예제 #2
0
        //[HttpPost]
        //public async Task<ActionResult> Roles(RoleViewModel roleViewModel)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        if (!RoleManager.RoleExists(roleViewModel.Name))
        //        {
        //            var role = new IdentityRole(roleViewModel.Name);
        //            var roleresult = await RoleManager.CreateAsync(role);
        //            if (!roleresult.Succeeded)
        //            {
        //                ViewBag.Msg = _hlp.getMsg(AlertType.success.ToString(), "Added successfully!");
        //                ModelState.AddModelError("", roleresult.Errors.First());
        //                return View(RoleManager.Roles);
        //            }
        //        }
        //        else
        //        {
        //            ViewBag.Msg = _hlp.getMsg(AlertType.danger.ToString(), "The role already exist!");
        //        }

        //    }
        //    return View(RoleManager.Roles);
        //}

        public async Task <ActionResult> RoleDetails(string id)
        {
            if (id == null)
            {
                return(View("Response", new ResponseViewModel()
                {
                    Msg = "Bad Request!"
                }));
            }
            var role = await RoleManager.FindByIdAsync(id);

            // Get the list of Users in this Role
            var users = new List <ApplicationUser>();

            // Get the list of Users in this Role
            foreach (var user in UserManager.Users.ToList())
            {
                if (await UserManager.IsInRoleAsync(user.Id, role.Name))
                {
                    users.Add(user);
                }
            }

            ViewBag.Users     = users;
            ViewBag.UserCount = users.Count();
            return(View(role));
        }
        //
        // GET: /Roles/Details/5
        public async Task <ActionResult> Details(string id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            var role = await _roleManager.FindByIdAsync(id);


            //pega a lista de usuarios nessa role

            var users = new List <ApplicationUser>();

            //pega a lista de usuarios nessa role
            foreach (var user in _userManager.Users.ToList())
            {
                if (await _userManager.IsInRoleAsync(user.Id, role.Name))
                {
                    //adiciona o usuario na lista de aplicationUser junto com as roles por id e o nome
                    users.Add(user);
                }
            }

            ViewBag.Users     = users;
            ViewBag.UserCount = users.Count();
            return(View(role));
        }
예제 #4
0
        public async Task <ActionResult> Details(string id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            var role = await _roleManager.FindByIdAsync(id);

            // Get the list of Users in this Role
            var users = new List <ApplicationUser>();

            // Get the list of Users in this Role
            foreach (var user in _userManager.Users.ToList())
            {
                if (await _userManager.IsInRoleAsync(user.Id, role.Name))
                {
                    users.Add(user);
                }
            }

            ViewBag.Users     = users;
            ViewBag.UserCount = users.Count();

            return(View(role));
        }
예제 #5
0
        public async Task <IHttpActionResult> GetRole(Guid Id)
        {
            var role = await _applicationRoleManager.FindByIdAsync(Id);

            if (role != null)
            {
                return(Ok(_identityRoleResponseFactory.Create(role)));
            }

            return(NotFound());
        }
예제 #6
0
        public async Task <IdentityResult> editrole(RoleViewModel roleModel)
        {
            var role = await _rm.FindByIdAsync(roleModel.Id);

            role.Name = roleModel.Name;
            // Update the new Description property:
            //role.Description = roleModel.Description;
            var result = await _rm.UpdateAsync(role);

            return(result);
        }
예제 #7
0
        public override async Task <IdentityRoleDto> GetByIdAsync(object id)
        {
            if (!await ExistsAsync(id))
            {
                CustomException.ThrowNotFoundException($"There is no role with id = {id}.");
            }

            var role = await _roleManager.FindByIdAsync((string)id);

            return(_roleModelFactory.GetModel(role));
        }
예제 #8
0
        public async Task <KoreRole> GetRoleById(object roleId)
        {
            string id   = roleId.ToString();
            var    role = await roleManager.FindByIdAsync(id);

            return(new KoreRole
            {
                Id = role.Id,
                Name = role.Name
            });
        }
예제 #9
0
        public async Task <IHttpActionResult> GetRole(string id)
        {
            var role = roleManager.FindByIdAsync(id);


            if (role != null)
            {
                return(Ok(role));
            }

            return(NotFound());
        }
예제 #10
0
        public async Task <ActionResult> GetRole(string id)
        {
            var result = await _roleManager.FindByIdAsync(id);

            if (result == null)
            {
                return(NotFound());
            }

            var role = _mapper.MapTo <RoleDto>(result);

            return(Ok(role));
        }
예제 #11
0
        // GET: ApplicationRoles/Details/5
        public async Task <ActionResult> Details(string id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ApplicationRole applicationRole = await RoleManager.FindByIdAsync(id);

            if (applicationRole == null)
            {
                return(HttpNotFound());
            }
            return(View(applicationRole));
        }
예제 #12
0
        public async Task <RoleClaimsResponseResult> GetClaimsByRoleId(
            [FromQuery][Required] string roleId)
        {
            ApplicationRole role = await _roleManager.FindByIdAsync(roleId);

            if (role != null)
            {
                var result = await _roleManager.GetClaimsAsync(role);

                return(new RoleClaimsResponseResult()
                {
                    Code = 200,
                    Data = (from one in result
                            select new ApplicationRoleClaim()
                    {
                        RoleId = roleId,
                        ClaimType = one.Type,
                        ClaimValue = one.Value
                    }).ToArray()
                });
            }

            return(new RoleClaimsResponseResult()
            {
                Code = 403,
                Message = "Role does not exists"
            });
        }
        public async Task <string> AssignRolesAsync(string username, string rolescsv)
        {
            string message = string.Empty;

            try
            {
                string[]        roles = rolescsv.Split(',');
                ApplicationUser user  = await userManager.FindByNameAsync(username);

                List <string> userAssignedRoles = new List <string>();
                foreach (ApplicationUserRole aur in user.Roles)
                {
                    ApplicationRole applicationRole = await roleManager.FindByIdAsync(aur.RoleId);

                    userAssignedRoles.Add(applicationRole.Name);
                }
                IdentityResult result = await userManager.RemoveFromRolesAsync(user.Id, userAssignedRoles.ToArray());

                result = await userManager.UpdateAsync(user);

                result = await userManager.AddToRolesAsync(user.Id, roles);

                result = await userManager.UpdateAsync(user);

                message = "Success - Role assignment successful";
            }
            catch (Exception ex)
            {
                message = string.Format("Error - Role assignment to user {0} unsuccessful, role names {1}", username, rolescsv);
                throw ex;
            }
            return(message);
        }
예제 #14
0
        public async Task <IActionResult> GetRole(int id)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            ApplicationRole role = await rolemanager.FindByIdAsync(id.ToString());

            if (role == null)
            {
                return(NotFound());
            }

            return(Ok(role));
        }
예제 #15
0
        public async Task <ActionResult> Create(string UserId, string RoleId)
        {
            if (ModelState.IsValid)
            {
                if (!String.IsNullOrEmpty(RoleId))
                {
                    //Find Role Admin
                    var role = await _roleManager.FindByIdAsync(RoleId);

                    var result = await _userManager.AddToRoleAsync(UserId, role.Name);

                    if (!result.Succeeded)
                    {
                        ModelState.AddModelError("", result.Errors.First().ToString());
                        ViewBag.RoleId = new SelectList(await _roleManager.Roles.ToListAsync(), "Id", "Name");
                        return(View());
                    }
                }
                return(RedirectToAction("Index"));
            }
            else
            {
                ViewBag.RoleId = new SelectList(_roleManager.Roles, "Id", "Name");
                return(View());
            }
        }
예제 #16
0
        public async Task <ActionResult> Edit(string id)
        {
            var role = await _roleManager.FindByIdAsync(id);

            if (role == null)
            {
                return(RedirectToAction("Index"));
            }
            var editRole = new EditRoleViewModel
            {
                Id          = role.Id,
                Name        = role.Name,
                Description = role.Description
            };

            return(View(editRole));
        }
예제 #17
0
        public async Task <IHttpActionResult> ManageUsersInRole(UserInRoleModel userInRoleModel)
        {
            IdentityRole identityRole = await ApplicationRoleManager.FindByIdAsync(userInRoleModel.Id);

            if (identityRole == null)
            {
                ModelState.AddModelError("", "Role does not exist");
                return(BadRequest(ModelState));
            }

            foreach (string userId in userInRoleModel.EnrolledUsers)
            {
                ApplicationUser applicationUser = await ApplicationUserManager.FindByIdAsync(userId);

                if (applicationUser == null)
                {
                    ModelState.AddModelError("", $"User by Id: {userId} dous not exist");
                    continue;
                }

                if (!ApplicationUserManager.IsInRole(userId, identityRole.Name))
                {
                    IdentityResult identityResult =
                        await ApplicationUserManager.AddToRoleAsync(userId, identityRole.Name);

                    if (!identityResult.Succeeded)
                    {
                        ModelState.AddModelError("", $"User by Id: {userId} could not be added to role");
                    }
                }
            }

            foreach (string userId in userInRoleModel.RemovedUsers)
            {
                ApplicationUser applicationUser = await ApplicationUserManager.FindByIdAsync(userId);

                if (applicationUser == null)
                {
                    ModelState.AddModelError("", $"User by Id: {userId} does not exist");
                    continue;
                }

                IdentityResult identityResult =
                    await ApplicationUserManager.RemoveFromRoleAsync(userId, identityRole.Name);

                if (!identityResult.Succeeded)
                {
                    ModelState.AddModelError("", $"User by Id: {userId} could not be removed from role");
                }
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            return(Ok());
        }
예제 #18
0
        public async Task <IHttpActionResult> ManageUsersInRole(UsersInRoleDto model)
        {
            var role = await ApplicationRoleManager.FindByIdAsync(model.Id);

            if (role == null)
            {
                ModelState.AddModelError("", "Role does not exist");
                return(BadRequest(ModelState));
            }

            foreach (var user in model.EnrolledUsers)
            {
                var appUser = await ApplicationUserManager.FindByIdAsync(user);

                if (appUser == null)
                {
                    ModelState.AddModelError("", $"User: {user} does not exists");
                    continue;
                }

                if (ApplicationUserManager.IsInRole(user, role.Name) == false)
                {
                    var result = await ApplicationUserManager.AddToRoleAsync(user, role.Name);

                    if (result.Succeeded == false)
                    {
                        ModelState.AddModelError("", $"User: {user} could not be added to role");
                    }
                }
            }

            foreach (var user in model.RemovedUsers)
            {
                var appUser = await ApplicationUserManager.FindByIdAsync(user);

                if (appUser == null)
                {
                    ModelState.AddModelError("", $"User: {user} does not exists");
                    continue;
                }

                var result = await ApplicationUserManager.RemoveFromRoleAsync(user, role.Name);

                if (!result.Succeeded)
                {
                    ModelState.AddModelError("", $"User: {user} could not be removed from role");
                }
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            return(Ok());
        }
예제 #19
0
        public async Task <ClaimModel> AddClaimAsync(string roleId, ClaimModel claim)
        {
            var roleEntity = await _roleManager.FindByIdAsync(roleId);

            if (roleEntity == null)
            {
                throw new NotFoundException($"Could not locate entity with Id {roleId}");
            }

            var roleClaim = new RoleClaim
            {
                RoleId     = roleEntity.Id,
                ClaimValue = claim.ClaimValue,
                ClaimType  = claim.ClaimType
            };
            await _roleClaimRepository.AddAsync(roleClaim);

            return(_mapper.Map <ClaimModel>(roleClaim));
        }
예제 #20
0
        public async Task <IHttpActionResult> GetRole(string id)
        {
            IdentityRole identityRole = await ApplicationRoleManager.FindByIdAsync(id);

            if (identityRole == null)
            {
                return(NotFound());
            }

            return(Ok(ModelFactory.Create(identityRole)));
        }
예제 #21
0
        public async Task <IHttpActionResult> DeleteRoleAsync(string id)
        {
            var role = await ApplicationRoleManager.FindByIdAsync(id);

            if (role == null)
            {
                return(NotFound());
            }

            var result = await ApplicationRoleManager.DeleteAsync(role);

            return(result.Succeeded ? Ok() : GetErrorResult(result));
        }
예제 #22
0
        public async Task <object> DeleteRole(Guid roleId)
        {
            ResponseMessageModel message;
            var role = await _roleManager.FindByIdAsync(roleId.ToString());

            if (role == null)
            {
                message = new ResponseMessageModel
                {
                    Code = MessageCode.OBJECT_NOT_FOUND
                };
                return(message);
            }
            var result = await _roleManager.DeleteAsync(role);

            if (result.Succeeded)
            {
                message = new ResponseMessageModel
                {
                    Code = MessageCode.SUCCESS,
                };
                return(message);
            }
            //error occurs
            string errorMessage = "";

            foreach (var error in result.Errors)
            {
                errorMessage += error.Description + "\r\n";
            }
            message = new ResponseMessageModel
            {
                Code         = MessageCode.SQL_ACTION_ERROR,
                ErrorMessage = errorMessage
            };
            return(message);
        }
예제 #23
0
        public async Task <IdentityResult> CreateOrUpdateAsync(RoleViewModel model)
        {
            if (model.Id == 0)
            {
                var applicationRole = Mapper.Map <ApplicationRole>(model);
                applicationRole.Id = 1;
                var result = await _applicationRoleManager.CreateAsync(applicationRole);

                model.Id = applicationRole.Id;
                return(result);
            }

            var role = _applicationRoleManager.FindByIdAsync(model.Id).Result;

            if (role == null)
            {
                return(IdentityResult.Failed());
            }

            MapApplicationRole(role, model);
            var updateResult = await _applicationRoleManager.UpdateAsync(role);

            return(updateResult);
        }
예제 #24
0
        public async Task<IdentityResult> UpdateRole(JObject newRole)
        {
            string roleName = ((dynamic)newRole).Name.Value;
            string roleId = ((dynamic)newRole).Id.Value;

            IdentityResult result = null;
            var roleStore = new RoleStore<IdentityRole>(_contextProvider.Context);
            var roleManager = new ApplicationRoleManager(roleStore);

            var role = await roleManager.FindByIdAsync(roleId);
            if (role != null)
            {
                role.Name = roleName;
                result = await roleManager.UpdateAsync(role);
            }
            return result;
        }
예제 #25
0
        public async Task <ActionResult> Delete(string id)
        {
            var role = await _roleManager.FindByIdAsync(id);

            if (role == null)
            {
                return(NotFound());
            }

            var result = await _roleManager.DeleteAsync(role);

            if (result.Succeeded)
            {
                return(NoContent());
            }

            return(BadRequest());
        }
예제 #26
0
        public async Task <IHttpActionResult> DeleteRole(string id)
        {
            IdentityRole identityRole = await ApplicationRoleManager.FindByIdAsync(id);

            if (identityRole == null)
            {
                NotFound();
            }

            IdentityResult identityResult = await ApplicationRoleManager.DeleteAsync(identityRole);

            if (!identityResult.Succeeded)
            {
                return(GetErrorResult(identityResult));
            }

            return(Ok());
        }
예제 #27
0
        public async Task <ActionResult> EditRoleUser(string id)
        {
            ApplicationRoleManager RoleManager = HttpContext.GetOwinContext().Get <ApplicationRoleManager>();
            ApplicationRole        role        = await RoleManager.FindByIdAsync(id);

            string[] memberIDs = role.Users.Select(x => x.UserId).ToArray();

            IEnumerable <ApplicationUser> members
                = UserManager.Users.Where(x => memberIDs.Any(y => y == x.Id));

            IEnumerable <ApplicationUser> nonMembers = UserManager.Users.Except(members);

            return(View(new RoleEditViewModel
            {
                Role = role,
                Members = members,
                NonMembers = nonMembers
            }));
        }
예제 #28
0
        public async Task <IActionResult> Roles()
        {
            var          failures = new List <string>();
            TimeZoneInfo pst      = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
            DateTime     longAgo  = new DateTime(1800, 1, 1);

            var legacyRoles = await legacyDb.Roles.ToArrayAsync();

            foreach (var role in legacyRoles)
            {
                await roleManager.CreateAsync(new ApplicationRole { Id = role.Id, Name = role.Name, Description = role.Description });
            }

            var             roleRoles = legacyDb.RoleRoles.OrderBy(f => f.RoleRow_Id).ToArray();
            ApplicationRole child     = new ApplicationRole();

            foreach (var row in roleRoles)
            {
                if (child == null || row.RoleRow_Id != child.Id)
                {
                    if (child != null)
                    {
                        await roleManager.UpdateAsync(child);
                    }
                    child = await roleManager.FindByIdAsync(row.RoleRow_Id);
                }
                child.Ancestors.Add(new RoleRoleMembership
                {
                    ParentId = row.RoleRow_Id1,
                    Child    = child,
                    IsDirect = true
                });
            }

            // await roleManager.RebuildInheritance();

            return(Content("Done\n\n" + string.Join("\n", failures)));
        }
예제 #29
0
 public async Task <IdentityRole> FindByIdAsync(string roleId)
 {
     return(await _appRoleManager.FindByIdAsync(roleId));
 }
예제 #30
0
        public async Task <bool> Crear(UserRolesUnidadCategoria usuario)
        {
            VerificarExistenciaJefaturas(usuario);

            try
            {
                var role = await _roleManager.FindByIdAsync(usuario.SelectedRoleId);

                var contrasenaTemporal = Membership.GeneratePassword(15, 2);
                var newUser            = new ApplicationUser()
                {
                    Id                   = usuario.Id,
                    Nombre               = usuario.Nombre,
                    PrimerApellido       = usuario.PrimerApellido,
                    SegundoApellido      = usuario.SegundoApellido,
                    Email                = usuario.Email,
                    PhoneNumber          = usuario.PhoneNumber,
                    UserName             = usuario.Email,
                    FechaIngreso         = usuario.FechaIngreso,
                    FechaCreacion        = DateTime.Now,
                    UnidadTecnicaId      = Convert.ToInt32(usuario.SelectedUnidadTecnicaId),
                    CategoriaId          = Convert.ToInt32(usuario.SelectedCategoriaId),
                    EstaActivo           = true,
                    EsContrasenaTemporal = true,
                    FotoRuta             = usuario.Foto != null ? usuario.Foto.FileName : null,
                    SaldoDiasEmpleado    = new SaldoDiasPorEmpleado()
                    {
                        Cedula = usuario.Id,
                        SaldoDiasDisponibles = 0,
                        UltimaActualizacion  = DateTime.Now
                    }
                };

                var result = await _userManager.CreateAsync(newUser, contrasenaTemporal);

                if (result.Succeeded)
                {
                    var userSaved = await _userManager.FindByEmailAsync(usuario.Email);

                    await _userManager.AddToRoleAsync(userSaved.Id.ToString(), role.Name);

                    if (usuario.EsSuperusuario)
                    {
                        await _userManager.AddToRoleAsync(userSaved.Id.ToString(), "Manager");
                    }

                    // Guardar foto de usuario, en caso que se haya seleccionado alguna
                    GuardarFoto(usuario.Foto);

                    // Envio contrasena temporal al correo del usuario
                    try
                    {
                        await _userManager.SendEmailAsync(userSaved.Id, "Contraseña Temporal", $"Su contraseña temporal para el sistema de solicitud de vacaciones es: <strong>{ contrasenaTemporal }</strong>");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                        throw;
                    }

                    return(true);
                }

                return(false);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
예제 #31
0
        public async Task<IdentityResult> SaveChanges(JObject newRole)
        {
            string roleName = ((dynamic)newRole).Name.Value;
            string roleId = ((dynamic)newRole).Id.Value;
            //dynamic oldRole = ((dynamic)newRole).oldRole.Value;

            IdentityResult result = null;
            var roleStore = new RoleStore<IdentityRole>(_contextProvider.Context);
            var roleManager = new ApplicationRoleManager(roleStore);

            var role = await roleManager.FindByIdAsync(roleId);
            if (role == null)
            {
                result = await roleManager.CreateAsync(new IdentityRole(roleName));
            }

            return result;
        }
예제 #32
0
 public Task <IdentityRole> GetRole(Guid id)
 {
     return(_applicationRoleManager.FindByIdAsync(id.ToString()));
 }