Beispiel #1
0
 private void CreateDefaultRoles()
 {
     if (!RoleManager.RoleExists("Developer"))
     {
         RoleManager.Create(new IdentityRole()
         {
             Name = "Developer"
         });
     }
     if (!RoleManager.RoleExists("SuperAdmin"))
     {
         RoleManager.Create(new IdentityRole()
         {
             Name = "SuperAdmin"
         });
     }
     if (!RoleManager.RoleExists("Admin"))
     {
         RoleManager.Create(new IdentityRole()
         {
             Name = "Admin"
         });
     }
     if (!RoleManager.RoleExists("User"))
     {
         RoleManager.Create(new IdentityRole()
         {
             Name = "User"
         });
     }
 }
        public void SetInitialData()
        {
            ApplicationRole userRole = new ApplicationRole {
                Name = "user"
            };
            ApplicationRole adminRole = new ApplicationRole {
                Name = "admin"
            };
            ApplicationRoleManager roleManager = repository.RoleManager;

            roleManager.Create(userRole);
            roleManager.Create(adminRole);

            ApplicationUser admin = new ApplicationUser
            {
                UserName             = "******",
                Email                = "admin",
                RegistrationDateTime = DateTime.UtcNow
            };
            ApplicationUserManager userManager = repository.UserManager;

            userManager.Create(admin, "1234qwerA");
            userManager.AddToRole(admin.Id, adminRole.Name);
            repository.Save();
        }
        private void InitializeUsers(PassengersContext context)
        {
            var roleManager = new ApplicationRoleManager(new RoleStore <ApplicationRole>(context));
            var userManager = new ApplicationUserManager(new UserStore <AppUser>(context));

            var roleAdmin = new ApplicationRole {
                Name = "Admin"
            };
            var roleUser = new ApplicationRole {
                Name = "User"
            };

            roleManager.Create(roleAdmin);
            roleManager.Create(roleUser);

            var admin = new AppUser {
                Email = "*****@*****.**", UserName = "******", FirstName = "Darya", LastName = "Drahun"
            };
            var user = new AppUser {
                Email = "*****@*****.**", UserName = "******", FirstName = "Darya", LastName = "Drahun"
            };

            userManager.Create(admin, "qwerty");
            userManager.Create(user, "qwerty");
            userManager.AddToRole(admin.Id, "Admin");
            userManager.AddToRole(user.Id, "User");
            base.Seed(context);
        }
Beispiel #4
0
        protected override void Seed(WebTestSecirity.Models.ApplicationDbContext context)
        {
            var userManager = new ApplicationUserManager(new UserStore <ApplicationUser>(context));
            var roleManager = new ApplicationRoleManager(new RoleStore <IdentityRole>(context));

            // создаем две роли
            var roleAdmin = new IdentityRole {
                Name = "Admin"
            };
            var roleUser = new IdentityRole {
                Name = "User"
            };

            // добавляем роли в бд
            roleManager.Create(roleAdmin);
            roleManager.Create(roleUser);

            string email    = "*****@*****.**";
            string password = "******";
            // создаем пользователей
            var admin = new ApplicationUser {
                Email = email, UserName = email
            };
            var result = userManager.Create(admin, password);

            // если создание пользователя прошло успешно
            if (result.Succeeded)
            {
                // добавляем для пользователя роль
                userManager.AddToRole(admin.Id, roleAdmin.Name);
                userManager.AddToRole(admin.Id, roleUser.Name);
            }
        }
Beispiel #5
0
        protected override void Seed(AccountingDemoApp.DAL.ApplicationDbContext db)
        {
            //  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 roleManager = new ApplicationRoleManager(new RoleStore <ApplicationRole>(db));

            if (!roleManager.Roles.Any())
            {
                roleManager.Create(new ApplicationRole {
                    Name = "Admin"
                });
                roleManager.Create(new ApplicationRole {
                    Name = "User"
                });
            }
            var userManager = new ApplicationUserManager(new UserStore <ApplicationUser>(db));

            if (!userManager.Users.Any())
            {
                var admin = new ApplicationUser
                {
                    Id             = Guid.NewGuid().ToString(),
                    Email          = "*****@*****.**",
                    UserName       = "******",
                    EmailConfirmed = true,
                    Deposit        = 25000m
                };
                userManager.Create(admin, "jason12345");
                userManager.AddToRoles(admin.Id, new string[] { "Admin", "User" });
            }
            SaveData(db);
        }
        protected override void Seed(IEP.Security.ApplicationSecurityDbContext 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.

            if (!context.Roles.Any())
            {
                var store   = new RoleStore <ApplicationRole, int, ApplicationUserRole>(context);
                var manager = new ApplicationRoleManager(store);

                var role = new ApplicationRole {
                    Name = "Admin"
                };
                manager.Create(role);

                role = new ApplicationRole {
                    Name = "Registred User"
                };
                manager.Create(role);
            }

            if (!context.Users.Any(u => u.UserName == "Admin"))
            {
                var store   = new UserStore <ApplicationUser, ApplicationRole, int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>(context);
                var manager = new ApplicationUserManager(store);
                var user    = new ApplicationUser {
                    UserName = "******", Email = "*****@*****.**", FirstName = "Admin", LastName = "Admin"
                };

                manager.Create(user, "password");
                manager.AddToRole(user.Id, "Admin");
            }
        }
        public void PerformInitialSetup(ApplicationDbContext context)
        {
            ApplicationUserManager userMgr = new ApplicationUserManager(new UserStore <ApplicationUser>(context));
            ApplicationRoleManager roleMgr = new ApplicationRoleManager(new RoleStore <ApplicationRole>(context));
            string roleName  = "Administrators";
            string roleName1 = "GS";
            string userName  = "******";
            string password  = "******";
            string email     = "*****@*****.**";

            if (!roleMgr.RoleExists(roleName))
            {
                roleMgr.Create(new ApplicationRole(roleName));
                roleMgr.Create(new ApplicationRole(roleName1));
            }
            ApplicationUser user = userMgr.FindByName(userName);

            if (user == null)
            {
                userMgr.Create(new ApplicationUser {
                    UserName = email, Email = email
                },
                               password);
                user = userMgr.FindByName(email);
            }
            if (!userMgr.IsInRole(user.Id, roleName))
            {
                userMgr.AddToRole(user.Id, roleName);
                userMgr.AddToRole(user.Id, roleName1);
            }
        }
Beispiel #8
0
 public void RegistraRegras()
 {
     if (_roleManager.FindByName("Administrador") == null)
     {
         _roleManager.Create(new IdentityRole("Administrador"));
         _roleManager.Create(new IdentityRole("Usuario"));
     }
 }
Beispiel #9
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));
        }
Beispiel #10
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));
        }
        protected override void Seed(ApplicationDbContext context)
        {
            var userManager = new ApplicationUserManager(new UserStore <ApplicationUser>(context));
            var roleManager = new ApplicationRoleManager(new RoleStore <IdentityRole>(context));

            var roleAdmin = new IdentityRole()
            {
                Name = "admin"
            };
            var roleOperator = new IdentityRole()
            {
                Name = "operator"
            };
            var roleExecutor = new IdentityRole()
            {
                Name = "executor"
            };

            roleManager.Create(roleAdmin);
            roleManager.Create(roleOperator);
            roleManager.Create(roleExecutor);

            var admin = new ApplicationUser()
            {
                Email    = "*****@*****.**",
                UserName = "******"
            };
            var passw = "hamster";
            var res   = userManager.Create(admin, passw);

            if (res.Succeeded)
            {
                userManager.AddToRole(admin.Id, roleAdmin.Name);
            }
            for (int i = 0; i < 60; i++)
            {
                context.SupportRequests.Add(new RequestModel()
                {
                    ClientName      = "client" + i,
                    Executor        = "Exec" + i,
                    Id              = i,
                    Operator        = "Operator" + i,
                    SolutionComment = "sdfs",
                    State           = "Зарегистриван",
                    Text            = "sdf",
                    Time            = DateTime.Now
                });
            }
            //context.SaveChanges();
            base.Seed(context);
        }
Beispiel #12
0
        private void PerformInitialSetup(ApplicationDbContext context)
        {
            var userMgr = new ApplicationUserManager(new UserStore <ApplicationUser>(context));
            var roleMgr = new ApplicationRoleManager(new RoleStore <ApplicationRole>(context));

            string roleName = "admin";
            string password = "******";
            string email    = "*****@*****.**";

            if (!roleMgr.RoleExists(roleName))
            {
                roleMgr.Create(new ApplicationRole(roleName));
            }

            var user = userMgr.FindByEmail(email);

            if (user == null)
            {
                userMgr.Create(new ApplicationUser {
                    UserName = email, Email = email
                }, password);
                user = userMgr.FindByEmail(email);
            }
            if (!userMgr.IsInRole(user.Id, roleName))
            {
                userMgr.AddToRole(user.Id, roleName);
            }

            string roleName1 = "user";
            string password1 = "1_MYpassword";
            string email1    = "*****@*****.**";

            if (!roleMgr.RoleExists(roleName1))
            {
                roleMgr.Create(new ApplicationRole(roleName1));
            }

            var user1 = userMgr.FindByEmail(email1);

            if (user1 == null)
            {
                userMgr.Create(new ApplicationUser {
                    UserName = email1, Email = email1
                }, password1);
                user1 = userMgr.FindByEmail(email1);
            }
            if (!userMgr.IsInRole(user1.Id, roleName1))
            {
                userMgr.AddToRole(user1.Id, roleName1);
            }
        }
        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());
                }
            }
        }
Beispiel #15
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);
            }
        }
        private void CreateAdminAccountAndApplicationRoles()
        {
            var dbContext   = new ApplicationDbContext();
            var userManager = new ApplicationUserManager(new UserStore <User>(dbContext));
            var roleManager = new ApplicationRoleManager(new RoleStore <IdentityRole>(dbContext));

            if (!roleManager.RoleExists("Administrator"))
            {
                roleManager.Create(new IdentityRole
                {
                    Name = "Administrator"
                });

                var user = new User
                {
                    UserName = "******",
                    Email    = "*****@*****.**"
                };
                var adminCreated = userManager.Create(user, "123admin123");
                if (adminCreated.Succeeded)
                {
                    userManager.AddToRole(user.Id, "Administrator");
                }
            }

            if (!roleManager.RoleExists("Organizator"))
            {
                roleManager.Create(new IdentityRole
                {
                    Name = "Organizator"
                });
            }

            if (!roleManager.RoleExists("Member"))
            {
                roleManager.Create(new IdentityRole
                {
                    Name = "Member"
                });
            }

            if (!roleManager.RoleExists("User"))
            {
                roleManager.Create(new IdentityRole
                {
                    Name = "User"
                });
            }
        }
Beispiel #17
0
        public void PerformInitialSetup(ApplicationDbContext context)
        {
            ApplicationUserManager userMgr = new ApplicationUserManager(new UserStore <ApplicationUser>(context));
            ApplicationRoleManager roleMgr = new ApplicationRoleManager(new RoleStore <ApplicationRole>(context));

            string roleAdmin = "Administrators";

            string userName = "******";
            string password = "******";
            string email    = "*****@*****.**";

            if (!roleMgr.RoleExists(roleAdmin))
            {
                roleMgr.Create(new ApplicationRole(roleAdmin));
            }

            ApplicationUser user = userMgr.FindByName(userName);

            if (user == null)
            {//, City = Cities.CHICAGO, Country = Countries.USA
                user = new ApplicationUser {
                    UserName = userName, Email = email
                };
                userMgr.Create(user, password);
                user = userMgr.FindByName(userName);
            }

            if (!userMgr.IsInRole(user.Id, roleAdmin))
            {
                userMgr.AddToRole(user.Id, roleAdmin);
            }
        }
Beispiel #18
0
        protected override void Seed(ApplicationDbContext context)
        {
            var userManager = new ApplicationUserManager(new UserStore <ApplicationUser>(context));
            var roleManager = new ApplicationRoleManager(new RoleStore <ApplicationRole>(context));

            const string role     = "Administrators";
            const string userName = "******";
            const string password = "******";
            const string mail     = "*****@*****.**";

            if (!roleManager.RoleExists(role))
            {
                roleManager.Create(new ApplicationRole(role));
            }

            var user = userManager.FindByName(userName);

            if (user == null)
            {
                userManager.Create(new ApplicationUser {
                    UserName = userName, Email = mail
                }, password);
                user = userManager.FindByName(userName);
            }

            if (!userManager.IsInRole(user.Id, role))
            {
                userManager.AddToRole(user.Id, role);
            }

            context.SaveChanges();
        }
Beispiel #19
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)
                {
                    var roles = ApplicationRoleManager.Create(HttpContext.GetOwinContext());

                    if (!await roles.RoleExistsAsync("Shop"))
                    {
                        await roles.CreateAsync(new IdentityRole { Name = "Shop" });
                    }
                    await UserManager.AddToRoleAsync(user.Id, "Shop");

                    string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                    var callbackUrl = Url.Action("ConfirmEmail", "Dashboard", 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", "Shops"));
                }
                AddErrors(result);
            }

            return(View(model));
        }
Beispiel #20
0
        // Add CreateAdminIfNeeded
        #region private void CreateAdminIfNeeded()
        private void CreateAdminIfNeeded()
        {
            // Get Admin Account
            string AdminUserName = ConfigurationManager.AppSettings["AdminUserName"];
            string AdminPassword = ConfigurationManager.AppSettings["AdminPassword"];
            // See if Admin exists
            var objAdminUser = UserManager.FindByEmail(AdminUserName);

            if (objAdminUser == null)
            {
                //See if the Admin role exists
                if (!RoleManager.RoleExists("Administrator"))
                {
                    // Create the Admin Role (if needed)
                    IdentityRole objAdminRole = new IdentityRole("Administrator");
                    RoleManager.Create(objAdminRole);
                }
                // Create Admin user
                var objNewAdminUser = new ApplicationUser {
                    UserName = AdminUserName, Email = AdminUserName
                };
                var AdminUserCreateResult = UserManager.Create(objNewAdminUser, AdminPassword);
                // Put user in Admin role
                UserManager.AddToRole(objNewAdminUser.Id, "Administrator");
            }
        }
        public async Task <ActionResult> AddAdmin(RegisterViewModel model)
        {
            var context       = new ApplicationDbContext();
            var store         = new UserStore <CustomUser>(context);
            var manager       = new UserManager <CustomUser>(store);
            var signInManager = new SignInManager <CustomUser, string>(manager, HttpContext.GetOwinContext().Authentication);
            var roles         = ApplicationRoleManager.Create(HttpContext.GetOwinContext());

            if (!await roles.RoleExistsAsync(SecurityRoles.Admin))
            {
                await roles.CreateAsync(new IdentityRole { Name = SecurityRoles.Admin });
            }

            if (ModelState.IsValid)
            {
                var user = new CustomUser
                {
                    UserName  = model.Email,
                    Email     = model.Email,
                    FirstName = model.FirstName,
                    LastName  = model.LastName,
                    Login     = model.Login
                };

                await manager.CreateAsync(user, model.Password);

                await manager.AddToRoleAsync(user.Id, SecurityRoles.Admin);

                return(RedirectToAction("Index", "Admin"));
            }

            return(View(model));
        }
        public ActionResult SetGlobalAdmins()
        {
            var adminRoleName = "Administrator";

            if (!RoleManager.RoleExists(adminRoleName))
            {
                var adminIdentityRole = new IdentityRole(adminRoleName);
                RoleManager.Create(adminIdentityRole);
            }

            var rolands = UserManager.FindByEmail("*****@*****.**");

            if (rolands != null)
            {
                UserManager.AddToRole(rolands.Id, adminRoleName);
            }

            var larisa = UserManager.FindByEmail("*****@*****.**");

            if (larisa != null)
            {
                UserManager.AddToRole(larisa.Id, adminRoleName);
            }

            return(View());
        }
Beispiel #23
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);
            }
        }
Beispiel #24
0
        public JsonResult Create(string model)
        {
            string roleName = string.Empty;

            try
            {
                RoleManagementViewModel role    = JsonConvert.DeserializeObject <RoleManagementViewModel>(model);
                ApplicationRole         newRole = new ApplicationRole()
                {
                    Name = role.RoleName
                };

                IdentityResult result = _roleManager.Create(newRole);
                if (result == IdentityResult.Success)
                {
                    roleName            = newRole.Name;
                    role.RoleId         = _roleManager.Roles.Select(r => r.Id).First();
                    Response.StatusCode = (int)System.Net.HttpStatusCode.OK;
                    return(Json(role, JsonRequestBehavior.AllowGet));
                }
                throw new System.Exception("New role cannot be created.");
            }
            catch (Exception ex)
            {
                Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
                return(Json("Create role '" + roleName + "' fails. " + ex.Message, JsonRequestBehavior.AllowGet));
            }
        }
Beispiel #25
0
        /// <summary>
        /// Registers the type mappings with the Unity container.
        /// </summary>
        /// <param name="container">The unity container to configure.</param>
        /// <remarks>
        /// There is no need to register concrete types such as controllers or
        /// API controllers (unless you want to change the defaults), as Unity
        /// allows resolving a concrete type even if it was not previously
        /// registered.
        /// </remarks>
        public static void RegisterTypes(IUnityContainer container)
        {
            // NOTE: To load from web.config uncomment the line below.
            // Make sure to add a Unity.Configuration to the using statements.
            // container.LoadConfiguration();

            RegisterLoggerType(container);

            container.RegisterType <ApplicationContext>();
            container.RegisterType <IIdentityMessageService, SendGridEmailService>();

            container.RegisterType <ApplicationUserManager>(
                new InjectionFactory(
                    c => ApplicationUserManager.Create(
                        c.Resolve <ApplicationContext>(),
                        c.Resolve <IIdentityMessageService>()))
                );

            container.RegisterType <ApplicationRoleManager>(
                new InjectionFactory(c => ApplicationRoleManager.Create(c.Resolve <ApplicationContext>()))
                );

            container.RegisterType <IAuthRepository, AuthRepository>();
            container.RegisterType <IUserRepository, UserRepository>();
            container.RegisterType <IDealRepository, DealRepository>();
            container.RegisterType <IComplainRepository, ComplainRepository>();
            container.RegisterType <IReportRepository, ReportRepository>();
            container.RegisterType <IPhotoRepository, PhotoRepository>();
            container.RegisterType <ICreditCardRepository, CreditCardRepository>();

            container.RegisterType <IPushNotificationService, AndroidPushNotificationService>();

            //container.RegisterType<OrdersController>(new InjectionConstructor());
        }
        public void PerformInitialSetup(ApplicationDbContext context)
        {
            var    userMgr  = new ApplicationUserManager(new UserStore <ApplicationUser>(context));
            var    roleMgr  = new ApplicationRoleManager(new RoleStore <ApplicationRole>(context));
            string roleName = "Administrator";
            string userName = "******";
            string password = "******";
            string email    = "*****@*****.**";

            if (!roleMgr.RoleExists(roleName))
            {
                roleMgr.Create(new ApplicationRole(roleName));
            }

            ApplicationUser user = userMgr.FindByName(userName);

            if (user == null)
            {
                userMgr.Create(new ApplicationUser {
                    UserName = userName, Email = email
                },
                               password);
                user = userMgr.FindByName(userName);
            }
        }
 public bool CreateRole(string name)
 {
     var rm = new ApplicationRoleManager(
         new RoleStore<IdentityRole>(context));
     var idResult = rm.Create(new IdentityRole(name));
     return idResult.Succeeded;
 }
        // 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);
        }
        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);
            }
        }
Beispiel #30
0
        protected override void Seed(Tamin.Models.ApplicationDbContext context)
        {
            ApplicationUserManager userMgr = new ApplicationUserManager(new UserStore <ApplicationUser>(context));
            ApplicationRoleManager roleMgr = new ApplicationRoleManager(new RoleStore <ApplicationRole>(context));
            string roleName = "administrator";
            string password = "******";
            string email    = "*****@*****.**";

            if (!roleMgr.RoleExists(roleName))
            {
                roleMgr.Create(new ApplicationRole(roleName));
            }
            ApplicationUser user = userMgr.FindByName("supercoach");

            if (user == null)
            {
                userMgr.Create(new ApplicationUser {
                    UserName = "******", Email = email
                },
                               password);
                user = userMgr.FindByName("supercoach");
                if (!userMgr.IsInRole(user.Id, roleName))
                {
                    userMgr.AddToRole(user.Id, roleName);
                }
                context.SaveChanges();
            }
        }
Beispiel #31
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);
            }
        }
Beispiel #32
0
 public void CreateNewRole(Role model)
 {
     ApplicationRoleManager rm = new ApplicationRoleManager(new ApplicationRoleStore(new ApplicationDbContext()));
     rm.Create(new ApplicationRole(model.Name)
     {
         Id = Guid.NewGuid().ToString()
     });
 }
Beispiel #33
0
        public static void SeedIdentityForEF(ApplicationDbContext context)
        {
            if ((!context.Roles.Any()) && (!context.Users.Any()))
            {
                var roleStore = new ApplicationRoleStore(context);
                //var roleManager = new RoleManager<ApplicationRole, int>(roleStore);

                var roleManager = new ApplicationRoleManager(roleStore);

                var role = new ApplicationRole
                {
                    Name = "Admin",
                    Description = "Super Admin User group"
                };
                roleManager.Create(role);

                var userStore = new UserStore<ApplicationUser,
                                                ApplicationRole,
                                                int,
                                                ApplicationUserLogin,
                                                ApplicationUserRole,
                                                ApplicationUserClaim>(context);
                var userManager = new ApplicationUserManager(userStore);

                var user = new ApplicationUser
                {
                    Email = "*****@*****.**",
                    UserName = "******",
                    EmailConfirmed = true
                };

                user.FirstName = "Jack";
                user.LastName = "Smith";

                userManager.Create(user, "P@ssword");
                var result = userManager.SetLockoutEnabled(user.Id, false);

                userManager.AddToRole(user.Id, "Admin");

                //added group manager
                var groupManager = new ApplicationGroupManager(roleManager,userManager);
                var newGroup = new ApplicationGroup("SuperAdmins", "Full Access to All");

                groupManager.CreateGroup(newGroup);
                groupManager.SetUserGroups(user.Id, new int[] { newGroup.Id });
                groupManager.SetGroupRoles(newGroup.Id, new string[] { role.Name });
            }
        }