Ejemplo n.º 1
0
        public UserViewModel ObtenerJefePorUnidadTecnica(int unidadTecnicaId)
        {
            var jefaturaRole = _roleManager.FindByName("Jefatura");
            var jefe         = _userManager.Users
                               .Where(x => x.UnidadTecnicaId == unidadTecnicaId && x.Roles.Any(r => r.RoleId == jefaturaRole.Id))
                               .FirstOrDefault();

            if (jefe == null)
            {
                return(null);
            }

            return(new UserViewModel()
            {
                Id = jefe.Id,
                Nombre = jefe.Nombre,
                PrimerApellido = jefe.PrimerApellido,
                SegundoApellido = jefe.SegundoApellido,
                Email = jefe.Email,
                UnidadTecnica = jefe.UnidadTecnica,
                Categoria = jefe.Categoria,
                EstaActivo = jefe.EstaActivo,
                FechaIngreso = jefe.FechaIngreso,
                FechaCreacion = jefe.FechaCreacion,
                PhoneNumber = jefe.PhoneNumber,
                SaldoDiasDisponibles = jefe.SaldoDiasEmpleado.SaldoDiasDisponibles
            });
        }
Ejemplo n.º 2
0
        public void ApplicationRoleManager_FindByName_Test()
        {
            string _name = "Admin";
            var    _role = _sut.FindByName(_name);

            Console.WriteLine(_role.ToString());
            Assert.AreEqual(_name, _role.Name);
        }
Ejemplo n.º 3
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    //Create Role Admin if it does not exist
                    const string adminRoleName = "Admin";

                    //Create User Role if it does not exist
                    const string userRoleName = "User";
                    var          userRole     = RoleManager.FindByName(userRoleName);
                    if (userRole == null)
                    {
                        userRole = new IdentityRole(userRoleName);
                        var roleResult = RoleManager.Create(userRole);
                    }

                    //Add the first user to the admin role
                    var adminRole = RoleManager.FindByName(adminRoleName);
                    if (adminRole == null)
                    {
                        adminRole = new IdentityRole(adminRoleName);
                        var roleResult = RoleManager.Create(adminRole);
                        UserManager.AddToRole(user.Id, adminRole.Name);
                    }
                    else
                    {
                        UserManager.AddToRole(user.Id, userRole.Name);
                    }

                    // For more information on how to enable account confirmation and password reset please visit http://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);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Ejemplo n.º 4
0
        protected override void Seed(ApplicationDbContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data.

            var userManager = new ApplicationUserManager(new UserStore <ApplicationUser, ApplicationRole, string, IdentityUserLogin, ApplicationUserRole, IdentityUserClaim>(context));
            var roleManager = new ApplicationRoleManager(new RoleStore <ApplicationRole, string, ApplicationUserRole>(context));

            const string name     = "*****@*****.**";
            const string password = "******";

            //Create Role Admin if it does not exist
            var role = roleManager.FindByName(AppRoles.Admin);

            if (role == null)
            {
                role = new ApplicationRole(AppRoles.Admin);
                var roleresult = roleManager.Create(role);
            }

            var user = userManager.FindByName(name);

            if (user == null)
            {
                user = new ApplicationUser {
                    UserName = name, Email = name
                };
                var result = userManager.Create(user, password);
                result = userManager.SetLockoutEnabled(user.Id, false);
            }

            // Add user admin to Role Admin if not already added
            var rolesForUser = userManager.GetRoles(user.Id);

            if (!rolesForUser.Contains(role.Name))
            {
                var result = userManager.AddToRole(user.Id, role.Name);
            }

            foreach (var appRole in AppRoles.GetRoleNames())
            {
                if (roleManager.FindByName(appRole) == null)
                {
                    var roleresult = roleManager
                                     .Create(new ApplicationRole(appRole));
                }
            }
        }
        private void InitializeRole(string roleName)
        {
            IdentityRole role = roleManager.FindByName(roleName);

            if (role == null)
            {
                role = new IdentityRole(roleName);
                IdentityResult result = roleManager.Create(role);
                if (!result.Succeeded)
                {
                    throw new ApplicationException(result.Errors.ToString());
                }
            }
        }
Ejemplo n.º 6
0
        public void InitializeIdentityForEF()
        {
            var context = new ApplicationDbContext();

            var roleStore   = new ApplicationRoleStore(context);
            var roleManager = new ApplicationRoleManager(roleStore);

            var userStore   = new ApplicationUserStore(context);
            var userManager = new ApplicationUserManager(userStore);

            const string adminUsername = "******";
            const string password      = "******";
            const string adminRoleName = "Admin";
            const string userRoleName  = "User";

            var adminRole = roleManager.FindByName(adminRoleName);

            if (adminRole == null)
            {
                adminRole = new ApplicationRole(adminRoleName);
                var roleResult = roleManager.Create(adminRole);
            }

            var userRole = roleManager.FindByName(userRoleName);

            if (userRole == null)
            {
                userRole = new ApplicationRole(userRoleName);
                var roleResult = roleManager.Create(userRole);
            }

            var adminUser = userManager.FindByName(adminUsername);

            if (adminUser == null)
            {
                adminUser = new ApplicationUser {
                    UserName = adminUsername, Email = adminUsername
                };
                var result = userManager.Create(adminUser, password);
                result = userManager.SetLockoutEnabled(adminUser.Id, false);
            }

            var rolesForUser = userManager.GetRoles(adminUser.Id);

            if (!rolesForUser.Contains(adminRole.Name))
            {
                var result = userManager.AddToRole(adminUser.Id, adminRole.Name);
            }
        }
        public async Task <string> Get(string roleName, string action)
        {
            var context     = ApplicationDbContext.Create();
            var roleManager = new ApplicationRoleManager(new RoleStore <ApplicationRole>(context));

            switch (action)
            {
            case createAction:
                if (roleManager.RoleExists(roleName))
                {
                    return("新增角色失败,该角色名称已存在");
                }
                await roleManager.CreateAsync(new ApplicationRole(roleName));

                return("新增角色成功");

            case deleteAction:
                if (!roleManager.RoleExists(roleName))
                {
                    return("删除角色失败,该角色名称不存在");
                }
                var role = roleManager.FindByName(roleName);
                await roleManager.DeleteAsync(role);

                return("删除角色成功");

            default:
                return("无效的操作指令");
            }
        }
        internal static IQueryable <T> GetPermissible <T>(ApplicationDbContext db, IPrincipal User, ApplicationUserManager UserManager, ApplicationRoleManager RoleManager)
            where T : Auditable, Permissible
        {
            var publicRoleId = RoleManager.FindByName(Roles.Public)?.Id;
            var items        = (IQueryable <T>)db.Active <T>();

            if (User.Identity.IsAuthenticated)
            {
                if (!User.IsInRole(Roles.Administrators))
                {
                    List <string> roles     = new List <string>();
                    var           userId    = User.Identity.GetUserId();
                    var           roleNames = UserManager.GetRoles(userId);
                    if (roleNames != null && roleNames.Count() > 0)
                    {
                        roles = RoleManager.Roles.Where(r => roleNames.Contains(r.Name)).Select(r => r.Id).ToList();
                    }
                    roles.Add(publicRoleId);
                    items = items.Where(m => m.Permissions.Any(p => p.Grant &&
                                                               (p.AppliesTo_Id == userId || roles.Contains(p.AppliesToRole_Id))
                                                               ));
                }
            }
            else
            {
                items = items.Where(m => m.Permissions.Any(
                                        item => item.Grant &&
                                        item.AppliesToRole_Id == publicRoleId));
            }
            return(items);
        }
Ejemplo n.º 9
0
        // Check if a role is exist if it is exist then
        private async Task <IdentityResult> AddUserRole(ApplicationUser user)
        {
            IdentityResult addtorole, roleexist = new IdentityResult();

            var default_RoleName        = DEFAULT_ROLE.MEMBER.ROLENAME;
            var default_RoleDescription = DEFAULT_ROLE.MEMBER.DESCRIPTIOIN;

            var role = RoleManager.FindByName(default_RoleName);

            if (role == null)
            {
                role             = new ApplicationRole();
                role.Name        = default_RoleName;
                role.Description = default_RoleDescription;
                roleexist        = RoleManager.Create(role);
                if (!roleexist.Succeeded)
                {
                    return(roleexist);
                }
                else
                {
                    addtorole = await UserManager.AddToRoleAsync(user.Id, default_RoleName);
                }
            }
            else
            {
                addtorole = await UserManager.AddToRoleAsync(user.Id, default_RoleName);
            }
            return(addtorole);
        }
Ejemplo n.º 10
0
        private void CreateAdmin(ApplicationUserManager userManager, ApplicationRoleManager roleManager)
        {
            const string adminUser  = "******";
            const string adminEmail = "*****@*****.**";
            const string roleName   = "Admin";

            var role = roleManager.FindByName(roleName);

            if (role == null)
            {
                role = new IdentityRole(roleName);
                roleManager.Create(role);
            }

            var user = userManager.FindByName(adminUser);

            if (user == null)
            {
                user = new ApplicationUser {
                    UserName = adminUser, Email = adminEmail
                };
                var result = userManager.Create(user, SecretKeys.Passwords.Admin);
                userManager.SetLockoutEnabled(user.Id, false);
            }

            // Add user admin to Role Admin if not already added
            var rolesForUser = userManager.GetRoles(user.Id);

            if (!rolesForUser.Contains(role.Name))
            {
                var result = userManager.AddToRole(user.Id, role.Name);
            }
        }
Ejemplo n.º 11
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Username, Email = model.Email
                };
                //создали юзера
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    if (RoleManager.FindByName("User") != null)
                    {
                        await UserManager.AddToRoleAsync(user.Id, "User");
                    }

                    return(RedirectToAction("Login", "Account"));
                }
                else
                {
                    await UserManager.DeleteAsync(user);

                    foreach (string error in result.Errors)
                    {
                        ModelState.AddModelError("", error);
                    }
                }
            }

            // Появление этого сообщения означает наличие ошибки; повторное отображение формы
            return(View(model));
        }
        public List <SelectListItem> GetApproverList()
        {
            List <SelectListItem> approvers = new List <SelectListItem>();

            if (_userManager != null && _userManager.SupportsUserRole)
            {
                ApplicationRole approverRole = _roleManager.FindByName(AppConstants.APPROVER_ROLE);
                foreach (ApplicationUser user in _userManager.Users.ToList())
                {
                    // this code does not work
                    //var identityUserRole = new IdentityUserRole() { UserId = user.Id, RoleId = approverRole.Id };
                    //if (user.Roles.Contains<IdentityUserRole>(identityUserRole))
                    //    approvers.Add(user.UserName);

                    foreach (IdentityUserRole role in user.Roles)
                    {
                        if (role.RoleId == approverRole.Id)
                        {
                            approvers.Add(new SelectListItem {
                                Text = user.UserName, Value = user.UserName
                            });
                            break;
                        }
                    }
                }
            }
            return(approvers);
        }
Ejemplo n.º 13
0
        private void InitializeIdentityAdmin(PSContext db)
        {
            var userStore   = new UserStore <ApplicationUser>(db);
            var userManager = new UserManager <ApplicationUser>(userStore);

            userManager.UserValidator = new UserValidator <ApplicationUser>(userManager)
            {
                AllowOnlyAlphanumericUserNames = false
            };
            // Configure validation logic for passwords
            userManager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit            = true,
                RequireLowercase        = true,
                RequireUppercase        = true,
            };
            var roleStore   = new RoleStore <IdentityRole>(db);
            var roleManager = new ApplicationRoleManager(roleStore);

            const string name     = "admin";
            const string password = "******";
            const string roleName = "Admin";

            //Create Role Admin if it does not exist
            var role = roleManager.FindByName(roleName);

            if (role == null)
            {
                role = new IdentityRole(roleName);
                var roleresult = roleManager.Create(role);
            }

            //Create the admin
            var user = userManager.FindByName(name);

            //Delete the current admin because we want to update him
            if (user != null)
            {
                userManager.Delete(user);
                user = null;
            }
            if (user == null)
            {
                user = new ApplicationUser {
                    UserName = name,
                };
                var result = userManager.Create(user, password);
                result = userManager.SetLockoutEnabled(user.Id, false);
            }

            // Add user admin to Role Admin if not already added
            var rolesForUser = userManager.GetRoles(user.Id);

            if (!rolesForUser.Contains(role.Name))
            {
                var result = userManager.AddToRole(user.Id, role.Name);
            }
        }
Ejemplo n.º 14
0
        //public ActionResult MakeAdmin()
        //{
        //    UserManager.AddToRole(User.Identity.GetUserId(), "Admin");
        //    return RedirectToAction("Index", "Home");
        //}

        public ActionResult ManageAdmins()
        {
            var roleID = RoleManager.FindByName("Admin").Id;
            var admins = UserManager.Users.Where(u => u.Roles.FirstOrDefault(r => r.RoleId == roleID) != null).ToList();

            return(View(admins));
        }
        private static void AddTestAccount(ApplicationUserManager userManager, ApplicationRoleManager roleManager, string password, string username, string rolename)
        {
            var adminRole = roleManager.FindByName(rolename);

            if (adminRole == null)
            {
                adminRole = new IdentityRole(rolename);
                var roleresult = roleManager.Create(adminRole);
            }

            var adminUser = userManager.FindByName(username);

            if (adminUser == null)
            {
                adminUser = new ApplicationUser
                {
                    UserName = username,
                    Email    = username
                };

                var result = userManager.Create(adminUser, password);
                result = userManager.SetLockoutEnabled(adminUser.Id, false);
            }

            var roleForUser = userManager.GetRoles(adminUser.Id);

            if (!roleForUser.Contains(adminRole.Name))
            {
                var result = userManager.AddToRole(adminUser.Id, adminRole.Name);
            }
        }
Ejemplo n.º 16
0
        public ActionResult Login(string returnUrl)
        {
            string roleName = "Admin";
            var    res      = RoleManager.FindByName(roleName);

            if (res == null)
            {
                ApplicationRole appRole = new ApplicationRole
                {
                    Name = roleName
                };
                RoleManager.Create(appRole);
            }
            string email = "*****@*****.**";
            var    user  = UserManager.FindByEmail(email);

            if (user == null)
            {
                ApplicationUser appUser = new ApplicationUser
                {
                    Email    = email,
                    UserName = email
                };
                UserManager.Create(appUser, "Qwerty1-");
            }
            user = UserManager.FindByEmail(email);
            UserManager.AddToRole(user.Id, roleName);

            ViewBag.ReturnUrl = returnUrl;
            return(View());
        }
Ejemplo n.º 17
0
        public ActionResult AddRoleToUser(RoleToUserViewModel model)
        {
            var roles = EnumHelper.GetUserRoleView();

            ViewBag.Roles = new SelectList(roles, "Text", "Text"); //Just need role name

            var user = UserManager.FindByEmail(model.UserName);
            var role = RoleManager.FindByName(model.RoleName);

            if (user == null)
            {
                ViewBag.Errors = new List <string> {
                    "User not found"
                };
                return(View(model));
            }


            //if (user == null)
            //{
            //    ModelState.AddModelError("UserName", "User not found");
            //    return View(model);
            //}

            var result = UserManager.AddToRole(user.Id, role.Name);

            ViewBag.Errors = result.Errors;

            if (result.Succeeded)
            {
                return(RedirectToAction("Roles"));
            }

            return(View(model));
        }
Ejemplo n.º 18
0
        public ActionResult ReadAjaxUserRolesGrid([DataSourceRequest] DataSourceRequest request, string role)
        {
            DataSourceResult result = null;

            try
            {
                var applicationRoleId = _roleManager.FindByName(role).Id;
                result = _userManager.Users.Where(u => u.Roles.Any(x => x.RoleId == applicationRoleId)).ToDataSourceResult(request, Mapper.Map <ApplicationUser, UserViewModel>);
            }
            catch (Exception ex)
            {
                _contextManager.ResponseManager.StatusCode = 500;
                _contextManager.ResponseManager.AppendHeader(ModelStateErrorNames.ErrorMessage, ex.Message);
            }

            return(Json(result));
        }
Ejemplo n.º 19
0
 public void RegistraRegras()
 {
     if (_roleManager.FindByName("Administrador") == null)
     {
         _roleManager.Create(new IdentityRole("Administrador"));
         _roleManager.Create(new IdentityRole("Usuario"));
     }
 }
Ejemplo n.º 20
0
        private static void CreateRole(ApplicationRoleManager roleManager, string roleName, bool IsAssignable)
        {
            var role = roleManager.FindByName(roleName);

            if (role == null)
            {
                role = new ApplicationRole(roleName);
                role.IsAssignable = IsAssignable;
                roleManager.Create(role);
            }
        }
Ejemplo n.º 21
0
        private static IdentityRole CreateRole(ApplicationRoleManager roleManager, string roleName)
        {
            var role = roleManager.FindByName(roleName);

            if (role == null)
            {
                role = new IdentityRole(roleName);
                var roleresult = roleManager.Create(role);
            }
            return(role);
        }
Ejemplo n.º 22
0
 public JsonResult AddUserToRole(string roleName, string userId)
 {
     try
     {
         var role = RoleManager.FindByName(roleName);
         if (role != null)
         {
             var user = UserManager.FindById(userId);
             if (user != null)
             {
                 UserManager.AddToRole(userId, role.Name);
                 return(Json(new { success = true }, JsonRequestBehavior.AllowGet));
             }
         }
     }
     catch (Exception)
     {
     }
     return(Json(new { success = false }, JsonRequestBehavior.AllowGet));
 }
Ejemplo n.º 23
0
        private List <CustomTuple> TuplifyString(string roles)
        {
            string[]           roleTokens = roles.Split(new char[] { ',' });
            List <CustomTuple> tuples     = new List <CustomTuple>();

            foreach (string role in roleTokens)
            {
                var appRole = _roleManager.FindByName(role);
                if (appRole != null)
                {
                    tuples.Add(new CustomTuple()
                    {
                        Id   = _roleManager.FindByName(role).Id,
                        Text = role
                    });
                }
                ;
            }
            return(tuples);
        }
Ejemplo n.º 24
0
        public async Task <ActionResult> Registrar(GoltaraSoft.SysBeauty.Web.Models.RegistrarViewModel model)
        {
            if (ModelState.IsValid)
            {
                EmpresaModel empresa = null;
                try
                {
                    _svEmpresa.Cadastrar(model.EmpresaCNPJ, model.EmpresaNome, model.Nome, model.Celular, model.Email);
                    empresa = _svEmpresa.FindCNPJ(model.EmpresaCNPJ);
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError(string.Empty, ex.Message);

                    return(View(model));
                }
                if (empresa != null)
                {
                    var user = new Usuario
                    {
                        Nome      = model.Nome,
                        UserName  = model.Email,
                        Email     = model.Email,
                        IdEmpresa = empresa.Id
                    };

                    var result = await _userManager.CreateAsync(user, model.Senha);

                    if (result.Succeeded)
                    {
                        if (_roleManager.FindByName("Administrador") == null)
                        {
                            _roleManager.Create(new IdentityRole("Administrador"));
                            _roleManager.Create(new IdentityRole("Usuario"));
                        }

                        Usuario usr = _userManager.FindByEmail(model.Email);

                        await _userManager.AddToRolesAsync(usr.Id, new[] { "Administrador" });

                        await _signInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                        return(RedirectToAction("Index", "Home"));
                    }
                    AddErrors(result);
                }

                ModelState.AddModelError(string.Empty, "Houve um erro ao tentar cadastrar a empresa.");
                return(View(model));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Ejemplo n.º 25
0
        private void CreateUserAndRoles(ApplicationDbContext c, string email, string password, string roleName)
        {
            //Create user
            ApplicationUser user = userManager.FindByName(email);

            if (user == null)
            {
                if (roleName.Equals("personeel"))
                {
                    user = new ApplicationUser {
                        UserName = email, Email = email, LockoutEnabled = false
                    };
                    c.Users.Add(user);
                }
                else
                {
                    user = new ApplicationUser {
                        UserName = email, Email = email, LockoutEnabled = false
                    };
                    c.Users.Add(user);
                }
                IdentityResult result = userManager.Create(user, password);
                if (!result.Succeeded)
                {
                    throw new ApplicationException(result.Errors.ToString());
                }
            }

            //Create roles
            IdentityRole role = roleManager.FindByName(roleName);

            if (role == null)
            {
                role = new IdentityRole(roleName);
                IdentityResult result = roleManager.Create(role);
                if (!result.Succeeded)
                {
                    throw new ApplicationException(result.Errors.ToString());
                }
            }

            //Associate user with role
            IList <string> rolesForUser = userManager.GetRoles(user.Id);

            if (!rolesForUser.Contains(role.Name))
            {
                IdentityResult result = userManager.AddToRole(user.Id, roleName);
                if (!result.Succeeded)
                {
                    throw new ApplicationException(result.Errors.ToString());
                }
            }
        }
Ejemplo n.º 26
0
        protected override void Seed(IdentityDbContext context)
        {
            const string adminRoleName = AppConstants.UserRole.Administrator;

            using (var roleManager = new ApplicationRoleManager(new RoleStore <ApplicationRole>(context)))
            {
                var adminRole = roleManager.FindByName(adminRoleName);

                if (adminRole == null)
                {
                    roleManager.Create(new ApplicationRole(adminRoleName));
                }

                // if admin already exists no need to create default admin
                if (adminRole != null && adminRole.Users.Any())
                {
                    return;
                }
            }


            using (var userManager = new ApplicationUserManager(new UserStore <ApplicationUser>(context)))
            {
                userManager.PasswordValidator = new PasswordValidator(); // default validator (any password valid)

                userManager.UserValidator = new UserValidator <ApplicationUser>(userManager)
                {
                    AllowOnlyAlphanumericUserNames = false,
                    RequireUniqueEmail             = false
                };

                const string userName     = "******";
                const string userPassword = "******";
                var          user         = userManager.FindByName(userName);

                if (user != null)
                {
                    return;
                }

                user = new ApplicationUser
                {
                    UserName             = userName,
                    LockoutEnabled       = true,
                    SpecializationsValue = Specializations.AllSpecializations,
                    RegisteredOnUtc      = DateTime.UtcNow
                };

                userManager.Create(user, userPassword);

                userManager.AddToRole(user.Id, adminRoleName);
            }
        }
Ejemplo n.º 27
0
        protected override void Seed(DbContext.ApplicationDbContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //

            ApplicationUserManager userManager = new ApplicationUserManager(new UserStore <ApplicationUser>(context));
            ApplicationRoleManager roleManager = new ApplicationRoleManager(new RoleStore <IdentityRole>(context));

            //var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
            //var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
            const string name     = "*****@*****.**";
            const string password = "******";
            const string roleName = "Admin";


            //Create Role Admin if it does not exist
            var role = roleManager.FindByName(roleName);

            if (role == null)
            {
                role = new IdentityRole(roleName);
                var roleresult = roleManager.Create(role);
            }

            var user = userManager.FindByName(name);

            if (user == null)
            {
                user = new ApplicationUser {
                    UserName = name, Email = name
                };
                var result = userManager.Create(user, password);
                result = userManager.SetLockoutEnabled(user.Id, false);
            }

            // Add user admin to Role Admin if not already added
            var rolesForUser = userManager.GetRoles(user.Id);

            if (!rolesForUser.Contains(role.Name))
            {
                var result = userManager.AddToRole(user.Id, role.Name);
            }
        }
        public ActionResult AddRoleToUser(UsersViewModel usersViewModel)
        {
            var _user = _userManager.FindById(usersViewModel.Id);
            var _role = _roleManager.FindByName(usersViewModel.SelectedRole);

            var result = _userManager.AddToRole(_user.Id, usersViewModel.SelectedRole);

            if (result.Succeeded)
            {
                return(RedirectToAction("Index", "Home"));
            }
            return(RedirectToAction("SetRoles"));
        }
        public async Task <string> Get(string roleName)
        {
            var context     = ApplicationDbContext.Create();
            var roleManager = new ApplicationRoleManager(new RoleStore <ApplicationRole>(context));

            if (!roleManager.RoleExists(roleName))
            {
                return("删除角色失败,该角色名称不存在");
            }
            var role = roleManager.FindByName(roleName);
            await roleManager.DeleteAsync(role);

            return("删除角色成功");
        }
Ejemplo n.º 30
0
        public async Task <IdentityResult> SetUserRole(PanelUser user, IdentityRole role)
        {
            if (_roleManager.FindByName(role.Name) == null)
            {
                var roleResult = await _roleManager.CreateAsync(role);

                if (!roleResult.Succeeded)
                {
                    return(roleResult);
                }
            }
            if (!_userManager.IsInRole(user.Id, role.Name))
            {
                var refreshTokens = _context.RefreshTokens.Where(item => item.Subject == user.UserName);
                foreach (var refreshToken in refreshTokens)
                {
                    _context.RefreshTokens.Remove(refreshToken);
                }
                _context.SaveChanges();
                return(_userManager.AddToRole(user.Id, role.Name));
            }
            return(null);
        }
        public async Task<string> Get(string roleName, string action)
        {
            var context = ApplicationDbContext.Create();
            var roleManager = new ApplicationRoleManager(new RoleStore<ApplicationRole>(context));
            switch (action)
            {
                case createAction:
                    if (roleManager.RoleExists(roleName)) return "新增角色失败,该角色名称已存在";
                    await roleManager.CreateAsync(new ApplicationRole(roleName));
                    return "新增角色成功";
                case deleteAction:
                    if (!roleManager.RoleExists(roleName)) return "删除角色失败,该角色名称不存在";
                    var role = roleManager.FindByName(roleName);
                    await roleManager.DeleteAsync(role);
                    return "删除角色成功";
                default:
                    return "无效的操作指令";
            }

        }