public async Task <ActionResult> Login(LoginViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var result = await signInManager.PasswordSignInAsync(model.UserName, model.Password, false, false); switch (result) { case SignInStatus.Success: var user = userManager.FindByName(model.UserName); var roleId = context.Set <IdentityUserRole>().FirstOrDefault(x => x.UserId.Equals(user.Id)).RoleId; var role = roleManager.FindById(roleId).Name; switch (role) { case "Admin": case "Customer": return(ReturnToGamesList()); default: return(View(model)); } case SignInStatus.LockedOut: case SignInStatus.RequiresVerification: case SignInStatus.Failure: default: return(View(model)); } }
public async Task <ActionResult> Edit([Bind] EditUserViewModel editUserViewModel) { if (ModelState.IsValid) { var user = UserManager.FindById(editUserViewModel.UserId); user.UserName = editUserViewModel.UserName; user.Email = editUserViewModel.Email; user.FirstName = editUserViewModel.FirstName; user.LastName = editUserViewModel.LastName; var selectedRoleNames = editUserViewModel.Roles .Where(role => role.Selected) .Select(role => role.Value) .Select(roleId => RoleManager.FindById(roleId).Name) .ToArray(); var results = await UserManager.UpdateUserAsync(user, selectedRoleNames); if (results.All(result => result.Succeeded)) { return(RedirectToAction("Users", "Admin")); } results.ForEach(result => AddErrors(result)); } return(View(editUserViewModel)); }
public ActionResult CreateOrEdit(string id) { bool isNew = false; var bo = _RoleManager.FindById(id); if (bo == null) { bo = new ApplicationRole(); bo.Id = id; isNew = true; } var boVM = new ApplicationRoleVM(bo); var editor = PageComponentRepository <ApplicationRoleVM> .CreateOrEditDialog(boVM, isNew); return(Json(editor)); }
public async Task <ActionResult> Register(RegisterViewModel model, string RoleId) { if (ModelState.IsValid) { // önce roller yoksa oluşturalım CreateDefaultRoles(); var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { var role = ApplicationRoleManager.FindById(RoleId); UserManager.AddToRole(user.Id, role.Name); await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); return(RedirectToAction("Index", "Home")); } AddErrors(result); } ViewBag.Roles = new SelectList(ApplicationRoleManager.Roles.ToList(), "Id", "Name", RoleId); // If we got this far, something failed, redisplay form return(View(model)); }
private void FillUserRoles(UserInfoViewModel userinfo, ApplicationUser user, ApplicationRoleManager roleManager) { foreach (var role in user.Roles) { userinfo.UserRoles.Add(new UserRole() { RoleName = roleManager.FindById(role.RoleId).Name }); } }
public RoleModel GetRoleById(string id) { var role = _roleManager.FindById(id); if (role == null) { throw new NotFoundException($"Could not locate entity with Id {id}"); } return(_mapper.Map <RoleModel>(role)); }
//GET: Admin/Role/Details/5 public ActionResult Details(string id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } var role = roleMnager.FindById(id); RoleViewModel roleVM = new RoleViewModel(); roleVM.Id = role.Id; roleVM.Name = role.Name; if (role == null) { return(HttpNotFound()); } return(View(roleVM)); }
public ActionResult UserDetails(string id) { TimesheetService.IManagement service = new TimesheetService.ManagementClient(); var user = UserManager.FindById(id); var employee = service.GetEmployee(user.ApiId.ToString()); var model = new UserDetailsViewModel() { Id = user.Id, Email = user.Email, Name = employee.Name, LastName = employee.LastName, ApiId = user.ApiId, Roles = user.Roles.Select(t => new RoleViewvModel() { Id = t.RoleId, Name = RoleManager.FindById(t.RoleId).Name }).ToList() }; return(View(model)); }
public void ClearUserRoles(int userId) { var user = _userManager.FindById(userId); var currentRoles = new List <SysUserRole>(); currentRoles.AddRange(user.Roles); foreach (var role in currentRoles) { _userManager.RemoveFromRole(userId, _roleManager.FindById(role.RoleId).Name); } }
public ActionResult Edit(string userId) { List <SelectListItem> roles = new List <SelectListItem>(); foreach (var item in RoleManager.Roles) { roles.Add(new SelectListItem() { Value = item.Name, Text = item.Name }); } ViewBag.Roles = roles; ViewBag.Gender = new List <SelectListItem>() { new SelectListItem { Value = "Male", Text = "Male" }, new SelectListItem { Value = "Female", Text = "Female" } }; ApplicationUser user = UserManager.FindById(userId); EditAccountViewModel userViewModel = new EditAccountViewModel { UserId = user.Id, UserName = user.UserName, Email = user.Email, Gender = user.Gender, Age = user.Age, Country = user.Country, RoleName = RoleManager.FindById(user.Roles.First().RoleId).Name }; return(View(userViewModel)); }
public ActionResult DeleteUserRole(int userid, int roleid) { var role = RoleMgr.FindById(roleid); var action = RedirectToAction("Edit", new { id = userid }); if (role == null) { return(action.WithError( string.Format("未找到id为{0}的角色。", roleid))); } var result = UserMgr.RemoveFromRole(userid, role.Name); if (!result.Succeeded) { return(action.WithError( string.Format("角色删除失败,因为{0}", string.Join(",", result.Errors)))); } return(action.WithSuccess( string.Format("角色{0}删除成功。", role.Name))); }
public List <string> GetRoles(ApplicationRoleManager appRoleManager) { var roles = new List <string>(); foreach (var role in this.Roles) { var newRole = appRoleManager.FindById(role.RoleId); if (newRole != null) { roles.Add(newRole.Name); } } return(roles); }
public ActionResult ProfielPartial() { User user = apc.Users.Find(User.Identity.GetUserId()); var model = new UserRoleViewModel(); var roles = user.Roles; var rolesCollection = new Collection <IdentityRole>(); foreach (var role in roles) { var role1 = RoleManager.FindById(role.RoleId); rolesCollection.Add(role1); } model = new UserRoleViewModel { user = user, roles = rolesCollection }; return(PartialView(model)); }
public void DeleteRole(string id, string userName) { var role = _roleManager.FindById(id); if (role != null) { _roleManager.Delete(role); } try { var roles = context.Roles.Include("Actions").Where(t => t.IsActive == true && t.IsDeleted != true && t.IsDraft == false).ToList(); HttpContext.Current.Cache["roles"] = roles; } catch (Exception exc) { ErrorLog(exc); } }
//POST:/Account/RemoveRoleinUser //[ActionName("DeleteRole_per_User")] public ActionResult RemoveUsersRole(string user, int roleId) { bool success = false; if (UserManager.IsInRole(user, "admin")) { string _roleid = Convert.ToString(roleId).Trim(); var rolename = RoleManager.FindById(_roleid); var result = UserManager.RemoveFromRole(user, rolename.Name); success = true; } return(Json(new { success = success }, JsonRequestBehavior.AllowGet)); }
public JsonResult RemoveUserFromRole(string roleId, string userId) { try { var role = RoleManager.FindById(roleId); if (role != null) { var user = UserManager.FindById(userId); if (user != null && user.UserName != "WcbAdmin") { UserManager.RemoveFromRole(userId, role.Name); return(Json(new { success = true }, JsonRequestBehavior.AllowGet)); } } } catch (Exception) { } return(Json(new { success = false }, JsonRequestBehavior.AllowGet)); }
public async Task <ActionResult> Edit(string id) { var user = await UserManager.FindByIdAsync(id); List <SelectListItem> roleList = new List <SelectListItem>(); foreach (var role in RoleManager.Roles) { foreach (var userRole in user.Roles) { if (RoleManager.FindById(userRole.RoleId).Name == role.Name) { ViewBag.SelectedRole = role.Name; } } roleList.Add(new SelectListItem() { Value = role.Name, Text = role.Name }); } ViewBag.Roles = roleList; return(View(new AccountViewModel(user))); }
public IEnumerable <UserViewModel> GetUsers() { var users = _userManager.Users .Where(x => !x.Email.Equals("*****@*****.**")) .ToList(); return(users.Select(x => new UserViewModel() { Id = x.Id, Nombre = x.Nombre, PrimerApellido = x.PrimerApellido, SegundoApellido = x.SegundoApellido, Email = x.Email, PhoneNumber = x.PhoneNumber, FechaIngreso = x.FechaIngreso, FechaCreacion = x.FechaCreacion, Role = _roleManager.FindById(x.Roles.First().RoleId.ToString()), UnidadTecnica = x.UnidadTecnica, Categoria = x.Categoria, EstaActivo = x.EstaActivo, EsSuperusuario = _userManager.IsInRole(x.Id, "Manager"), SaldoDiasDisponibles = x.SaldoDiasEmpleado.SaldoDiasDisponibles }).ToList()); }
private void InitRoles(ApplicationRoleManager roleManager, ExtendedIdentityDbContext context) { if (roleManager.RoleExists("系统管理员") == false) { IdentityResult result1 = roleManager.Create <SysRole, int>(new SysRole() { Name = "系统管理员", ParentId = -1, PrivilegeLevel = 99 }); this.OutputInitError(result1); } var role1 = roleManager.FindByName("系统管理员"); //if (role1 != null && role1.Id > 0) //{ // context.Database.ExecuteSqlCommand(string.Format( // "UPDATE aspnetroles SET Id = -{0} WHERE Id = {0}" // , role1.Id)); //} SysRole sysadmin = roleManager.FindById(role1.Id);//.FindByName("系统管理员"); if (roleManager.RoleExists("Boss") == false) { IdentityResult result2 = roleManager.Create <SysRole, int>(new SysRole() { Name = "Boss", ParentId = sysadmin.Id, PrivilegeLevel = 98 }); this.OutputInitError(result2); } var role2 = roleManager.FindByName("Boss"); //if (role2 != null && role2.Id > 0) //{ // context.Database.ExecuteSqlCommand(string.Format( // "UPDATE aspnetroles SET Id = -{0} WHERE Id = {0}" // , role2.Id)); //} SysRole boss = roleManager.FindById(role2.Id);//.FindByName("Boss"); if (roleManager.RoleExists("Manager") == false) { IdentityResult result3 = roleManager.Create <SysRole, int>(new SysRole() { Name = "Manager", ParentId = boss.Id, PrivilegeLevel = 75 }); this.OutputInitError(result3); } var role3 = roleManager.FindByName("Manager"); //if (role3 != null && role3.Id > 0) //{ // context.Database.ExecuteSqlCommand(string.Format( // "UPDATE aspnetroles SET Id = -{0} WHERE Id = {0}" // , role3.Id)); //} SysRole manager = roleManager.FindById(role3.Id);//.FindByName("Manager"); if (roleManager.RoleExists("一般用户") == false) { IdentityResult result4 = roleManager.Create <SysRole, int>(new SysRole() { Name = "一般用户", ParentId = manager.Id, PrivilegeLevel = SysRole.DEFAULT_PRIVILEGE_LEVEL }); this.OutputInitError(result4); } var role4 = roleManager.FindByName("一般用户"); //if (role4 != null && role4.Id > 0) //{ // context.Database.ExecuteSqlCommand(string.Format( // "UPDATE aspnetroles SET Id = -{0} WHERE Id = {0}" // , role4.Id)); //} SysRole userrole = roleManager.FindById(role4.Id);//.FindByName("一般用户"); if (roleManager.RoleExists("游客") == false) { IdentityResult result5 = roleManager.Create <SysRole, int>(new SysRole() { Name = "游客", ParentId = userrole.Id, PrivilegeLevel = 1 }); this.OutputInitError(result5); } var role5 = roleManager.FindByName("游客"); //if (role5 != null && role5.Id != 0) //{ // context.Database.ExecuteSqlCommand(string.Format( // "UPDATE aspnetroles SET Id = 0 WHERE Id = {0}" // , role5.Id));//Default Role //} }
public IdentityRole GetOne(string id) { return(_roleManager.FindById(id)); }
public async Task <ActionResult> Create(AspNetUsersViewModel model) { model.AspNetUserModel.UserName = model.AspNetUserModel.UserName; #region Update if (!string.IsNullOrEmpty(model.AspNetUserModel.Id)) { //Means Update // Get role var roleName = RoleManager.FindById(model.AspNetUserModel.RoleId).Name; AspNetUser userResult = UserManager.FindById(model.AspNetUserModel.Id); string userrRoleID = userResult.AspNetRoles.ToList()[0].Id; string userRoleName = RoleManager.FindById(userrRoleID).Name; // Check if role has been changed /************** DISABLING CHANGE ROLE IMPLEMENTATION/ UNCOMMENT TO RUN * if (userrRoleID != model.AspNetUserModel.RoleId) * { * // Update User Role * UserManager.RemoveFromRole(model.AspNetUserModel.Id, userRoleName); * UserManager.AddToRole(model.AspNetUserModel.Id, roleName); * TempData["message"] = new MessageViewModel { Message = "Role has been updated", IsUpdated = true }; * }************************/ // Password Reset if (!String.IsNullOrEmpty(model.AspNetUserModel.Password)) { var token = await UserManager.GeneratePasswordResetTokenAsync(model.AspNetUserModel.Id); var resetPwdResults = await UserManager.ResetPasswordAsync(model.AspNetUserModel.Id, token, model.AspNetUserModel.Password); if (resetPwdResults.Succeeded) { var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInAsync(user, isPersistent : false); } TempData["message"] = new MessageViewModel { Message = TMD.Web.Resources.HR.Account.UpdatePass, IsUpdated = true }; } } // Get user by UserId to Update User AspNetUser userToUpdate = UserManager.FindById(model.AspNetUserModel.Id); //if (userToUpdate.Email != model.AspNetUserModel.Email) //{ if (userToUpdate != null) { userToUpdate.UpdateUserTo(model.AspNetUserModel); } var updateUserResult = await UserManager.UpdateAsync(userToUpdate); if (updateUserResult.Succeeded) { TempData["message"] = new MessageViewModel { Message = "User has been Updated", IsUpdated = true }; } //} return(RedirectToAction("Users")); } #endregion // Add new User if (ModelState.IsValid) { // TODO:Check # of Users that Admin can create var user = new AspNetUser { UserName = model.AspNetUserModel.UserName, Email = model.AspNetUserModel.Email, Address = model.AspNetUserModel.Address, Telephone = model.AspNetUserModel.Telephone, FirstName = model.AspNetUserModel.FirstName, LastName = model.AspNetUserModel.LastName, LockoutEnabled = false }; user.EmailConfirmed = true; if (!String.IsNullOrEmpty(model.AspNetUserModel.Password)) { var result = await UserManager.CreateAsync(user, model.AspNetUserModel.Password); if (result.Succeeded) { //Setting role var roleManager = HttpContext.GetOwinContext().Get <ApplicationRoleManager>(); var roleName = roleManager.FindById(model.AspNetUserModel.RoleId).Name; UserManager.AddToRole(user.Id, roleName); await SendAccountCredentials(model.AspNetUserModel.Email, model.AspNetUserModel.UserName, model.AspNetUserModel.Password); TempData["message"] = new MessageViewModel { Message = "Employee has been created", IsSaved = true }; return(RedirectToAction("Users")); } else { var resultStr = ""; if (result.Errors.Count() > 0) { resultStr = result.Errors.ToList()[0].ToString(); } TempData["message"] = new MessageViewModel { Message = resultStr, IsError = true }; ViewBag.MessageVM = TempData["message"] as MessageViewModel; } } } // If we got this far, something failed, redisplay form model.Roles = HttpContext.GetOwinContext().Get <ApplicationRoleManager>().Roles.ToList(); //TempData["message"] = new MessageViewModel { Message = TMD.Web.Resources.HR.Account.ChkFields, IsError = true }; return(View(model)); }
public IdentityRole GetRoleByID(string id) { return(manager.FindById(id)); }
public ActionResult Edit(EditRegisterViewModel usuario) { if (ModelState.IsValid) { var user = UserManager.FindByName(usuario.UserName); if (user.Email != usuario.Email || user.PhoneNumber != usuario.PhoneNumber) { user.Email = usuario.Email; user.PhoneNumber = usuario.PhoneNumber; UserManager.Update(user); } if (!string.IsNullOrEmpty(usuario.Password)) { UserManager.RemovePassword(user.Id); UserManager.AddPassword(user.Id, usuario.Password); } var rolNuevo = RoleManager.FindByName(usuario.RoleName); var identityUserRole = user.Roles.FirstOrDefault(); if (identityUserRole != null && identityUserRole.RoleId != rolNuevo.Id) { var rolActual = RoleManager.FindById(identityUserRole.RoleId); UserManager.RemoveFromRole(user.Id, rolActual.Name); var roleResult = UserManager.AddToRole(user.Id, usuario.RoleName); if (!roleResult.Succeeded) { ModelState.AddModelError("", roleResult.Errors.First()); ConfigurarMenues(); ViewBag.EstablecimientoId = new SelectList(_establecimientoManager.ListarEstablecimientos(), "EstablecimientoId", "Descripcion", usuario.EstablecimientoId); ViewBag.RoleName = new SelectList(RoleManager.Roles.Where(R => !R.Name.Equals("Gestante")).ToList(), "Name", "Name", usuario.RoleName); ViewBag.EstadoId = new SelectList(_utilManager.ListarEstados(), "Id", "Descripcion", usuario.EstadoId); return(View(usuario)); } } var userLogId = "1"; if (Request.IsAuthenticated) { userLogId = User.Identity.GetUserId(); } var resultGrabar = _usuarioManager.GrabarUsuario(usuario, userLogId); if (resultGrabar) { RegistrarAccion((byte)AccionSesion.Actualizar, (byte)ObjetoSesion.EdicionUsuario, usuario.UsuarioKey); return(RedirectToAction("Index")); } ModelState.AddModelError("", new Exception("El usuario no se encontro en la base de datos.")); ConfigurarMenues(); ViewBag.EstablecimientoId = new SelectList(_establecimientoManager.ListarEstablecimientos(), "EstablecimientoId", "Descripcion", usuario.EstablecimientoId); ViewBag.RoleName = new SelectList(RoleManager.Roles.Where(R => !R.Name.Equals("Gestante")).ToList(), "Name", "Name", usuario.RoleName); ViewBag.EstadoId = new SelectList(_utilManager.ListarEstados(), "Id", "Descripcion", usuario.EstadoId); return(View(usuario)); } ConfigurarMenues(); ViewBag.EstablecimientoId = new SelectList(_establecimientoManager.ListarEstablecimientos(), "EstablecimientoId", "Descripcion", usuario.EstablecimientoId); ViewBag.RoleName = new SelectList(RoleManager.Roles.Where(R => !R.Name.Equals("Gestante")).ToList(), "Name", "Name", usuario.RoleName); ViewBag.EstadoId = new SelectList(_utilManager.ListarEstados(), "Id", "Descripcion", usuario.EstadoId); return(View(usuario)); }
public async Task <ActionResult> Register(RegisterViewModel model) { string message = string.Empty; if (ModelState.IsValid) { var user = new IdentityUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { user = await UserManager.FindByNameAsync(model.Email); #region (Adding To Role) string selectedRoleName = RoleManager.FindById(model.SelectedUserRoleId).Name; UserManager.AddToRole(user.Id, selectedRoleName); #endregion #region (Add Profile) #region (Add Profile) // await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false); //DoctorService doctorService = new DoctorService(); //if (1==1)//(selectedRoleName == CustomRoles.Doctor) //{ // DoctorDTO doctor = new DoctorDTO(); // doctor.FirstName = ""; // doctor.LastName = ""; // doctor.Description = ""; // doctor.DOB = new DateTime(1900, 1, 1); // doctor.LicenseNumber = ""; // doctor.StatusID_FK = 0; // doctor.User_FK_Id = user.Id; // var docId = doctorService.AddDoctor(doctor); //} #endregion MemberProfileService memberProfileService = new MemberProfileService(); MemberProfileDTO member = new MemberProfileDTO(); member.FirstName = ""; member.LastName = ""; member.HighestEducation = ""; member.HomeDistrict = ""; member.MobilePhone = ""; member.Experience = 0; member.DOB = new DateTime(1900, 1, 1); member.FK_FROM_IdentityUser = user.Id; memberProfileService.AddMember(member); #endregion #region (Sending Email) var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); var callbackUrl = Url.Action( "ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>"); //await UserManager.SendEmailAsync(20, // "New Doctor Registration", // "His Email is " + model.Email + ". Please confirm his account by clicking this link: <a href=\"" // + callbackUrl + "\">link</a> Go to <a href='https://amardoctors.com'>Amardoctors</a>"); #endregion return(RedirectToAction("Confirm", "Account", new { Email = user.Email })); } foreach (var item in result.Errors) { message += item + " || "; } AddErrors(result); } // If we got this far, something failed, redisplay form return(RedirectToAction("Register", new { message = message })); }
public override ApplicationRole FindById(string id) { return(_roleMgr.FindById(id)); }
public ApplicationRole FindById(int roleId) { var users = _manager.FindById(roleId); return(users); }