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)
                {
                    if (!UserManager.IsInRole(user.Id, model.Role) && RoleManager.RoleExists(model.Role))
                    {
                        await UserManager.AddToRoleAsync(user.Id, model.Role);
                    }

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

                    // 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("ListAllUsers"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        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("无效的操作指令");
            }
        }
예제 #3
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"
         });
     }
 }
예제 #4
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);
            }
        }
예제 #5
0
        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"
                });
            }
        }
예제 #6
0
        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 void Post(RoleUsersDto dto)
        {
            var context     = ApplicationDbContext.Create();
            var userManager = new ApplicationUserManager(new UserStore <ApplicationUser>(context));
            var roleManager = new ApplicationRoleManager(new RoleStore <ApplicationRole>(context));

            if (!roleManager.RoleExists(dto.RoleName))
            {
                return;
            }
            foreach (
                var user in
                dto.UserNames.Select(userName => userManager.FindByName(userName))
                .Where(user => user != null)
                .Where(user => !userManager.IsInRole(user.Id, dto.RoleName)))
            {
                userManager.AddToRole(user.Id, dto.RoleName);
            }
            foreach (
                var user in
                dto.UserNames.Select(userName => userManager.FindByName(userName))
                .Where(user => user != null)
                .Where(user => userManager.IsInRole(user.Id, dto.RoleName)))
            {
                userManager.RemoveFromRole(user.Id, dto.RoleName);
            }
        }
예제 #8
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");
            }
        }
예제 #9
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();
        }
예제 #10
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);
            }
        }
예제 #11
0
        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);
            }
        }
예제 #12
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();
            }
        }
        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());
        }
        protected void CreateUser_Click(object sender, EventArgs e)
        {
            ApplicationRoleManager roleMar = Context.GetOwinContext().Get <ApplicationRoleManager>();

            if (!roleMar.RoleExists(ddlRole.SelectedValue.ToString()))
            {
                IdentityRole role = new IdentityRole();
                role.Name = ddlRole.SelectedValue.ToString();
                IdentityResult roleResult = roleMar.Create(role);
                if (roleResult.Succeeded)
                {
                }
            }

            if (roleMar.RoleExists(ddlRole.SelectedValue.ToString()))
            {
                var manager = Context.GetOwinContext().GetUserManager <ApplicationUserManager>();

                var signInManager = Context.GetOwinContext().Get <ApplicationSignInManager>();
                var user          = new ApplicationUser()
                {
                    UserName = Email.Text, Email = Email.Text
                };
                IdentityResult result = manager.Create(user, Password.Text);

                if (result.Succeeded)
                {
                    // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                    //string code = manager.GenerateEmailConfirmationToken(user.Id);
                    //string callbackUrl = IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id, Request);
                    //manager.SendEmail(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>.");

                    if (!manager.IsInRole(user.Id, ddlRole.SelectedValue.ToString()))
                    {
                        manager.AddToRole(user.Id, ddlRole.SelectedValue.ToString());
                    }

                    signInManager.SignIn(user, isPersistent: false, rememberBrowser: false);
                    IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                }
                else
                {
                    ErrorMessage.Text = result.Errors.FirstOrDefault();
                }
            }
        }
예제 #15
0
 public static IEnumerable <IdentityResult> CreateAll(ApplicationDbContext context, ApplicationRoleManager roleManager)
 {
     if (roleManager != null && roleManager.RoleExists("ListManagers"))
     {
         roleManager.Delete(roleManager.Roles.First(r => r.Name == "ListManagers"));
     }
     return(CreateAll(context, roleManager, Administrators, Editors, ListManagers, Users, Public, Guests));
 }
예제 #16
0
        public void ApplicationRoleManager_RoleExists_Test()
        {
            string _name   = "Admin";
            var    _actual = _sut.RoleExists(_name);

            Console.WriteLine(_actual.ToString());
            Assert.IsTrue(_actual);
        }
예제 #17
0
        protected override void Seed(flutterwave_sub.Models.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.
            ApplicationRoleManager roleMgr = new ApplicationRoleManager(new RoleStore <IdentityRole>(context));
            ApplicationUserManager userMgr = new ApplicationUserManager(new UserStore <ApplicationUser>(context));

            if (!roleMgr.RoleExists("admin"))
            {
                roleMgr.Create(new IdentityRole("admin"));
            }
            if (!roleMgr.RoleExists("manager"))
            {
                roleMgr.Create(new IdentityRole("manager"));
            }
            if (!roleMgr.RoleExists("tenat"))
            {
                roleMgr.Create(new IdentityRole("tenat"));
            }

            ApplicationUser user = userMgr.FindByName("*****@*****.**");

            if (user == null)
            {
                userMgr.Create(new ApplicationUser()
                {
                    Email       = "*****@*****.**",
                    UserName    = "******",
                    FirstName   = "admin_firstname",
                    LastName    = "admin_lastname",
                    PhoneNumber = "080ADMIN",
                }, "adminstrongPassword");
                user = userMgr.FindByName("*****@*****.**");
            }

            if (!userMgr.IsInRole(user.Id, "admin"))
            {
                userMgr.AddToRole(user.Id, "admin");
            }

            context.SaveChanges();
        }
예제 #18
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.PTTID, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

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

                    // 如需如何進行帳戶確認及密碼重設的詳細資訊,請前往 https://go.microsoft.com/fwlink/?LinkID=320771
                    // 傳送包含此連結的電子郵件
                    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, "驗證您的Email帳戶", "請按一下此連結驗證您的帳戶 <a href=\"" + callbackUrl + "\">這裏</a>");

                    //角色名稱
                    var roleName = "Member"; // (model.PTTID != "某ID") ?  "Member" :

                    //判斷角色是否存在
                    if (RoleManager.RoleExists(roleName) == false)
                    {
                        //角色不存在,建立角色
                        var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(roleName);
                        await RoleManager.CreateAsync(role);
                    }
                    //將使用者加入該角色
                    await UserManager.AddToRoleAsync(user.Id, roleName);

                    string ipAddress = string.Empty;
                    if (!String.IsNullOrEmpty(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"]))
                    {
                        ipAddress = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"];
                    }
                    else
                    {
                        ipAddress = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                    }

                    //發送專屬序號
                    await Task.Run(() => SendBase5UserId(model.PTTID, user.Id, ipAddress));



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

            // 如果執行到這裡,發生某項失敗,則重新顯示表單
            return(View(model));
        }
예제 #19
0
        public ActionResult CreateRole(RoleViewModel model)
        {
            if (RoleManager.RoleExists(model.Name))
            {
                ModelState.AddModelError("RoleName", "Role already exist");
                return(View(model));
            }
            else
            {
                var newRole = new IdentityRole(model.Name);
                var result  = RoleManager.Create(newRole);
                if (result.Succeeded)
                {
                    return(RedirectToAction("Roles"));
                }

                return(View(model));
            }
        }
        public bool Get(string roleName, string userName)
        {
            if (!_roleManager.RoleExists(roleName))
            {
                return(false);
            }
            var user = _userManager.FindByName(userName);

            if (user == null)
            {
                return(false);
            }
            if (_userManager.IsInRole(user.Id, roleName))
            {
                return(false);
            }
            _userManager.AddToRole(user.Id, roleName);
            return(true);
        }
 public void AddOrUpdate(string roleName)
 {
     if (manager.RoleExists(roleName))
     {
         return;
     }
     else
     {
         Create(roleName);
     }
 }
        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 "无效的操作指令";
            }

        }
예제 #23
0
        private static void CreateRoleIfNotExists(ApplicationRoleManager roleManager, string roleName)
        {
            if (!roleManager.RoleExists(roleName))
            {
                var role = new RoleInfo {
                    Name = roleName
                };

                roleManager.Create(role);
            }
        }
        public async Task <string> Get(string roleName)
        {
            var context     = ApplicationDbContext.Create();
            var roleManager = new ApplicationRoleManager(new RoleStore <ApplicationRole>(context));

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

            return("新增角色成功");
        }
예제 #25
0
        public void AddRoles()
        {
            var SystemRoles = new string[] { "User", "Hotel", "Admin" };

            foreach (var r in SystemRoles)
            {
                if (!RoleManager.RoleExists(r))
                {
                    var role = new Role(r);
                    RoleManager.Create(role);
                }
            }
        }
        public HttpResponseMessage AddRole(String Role)
        {
            var            RoleManager = new ApplicationRoleManager(new CustomRoleStore(new ApplicationDbContext()));
            IdentityResult roleResult;

            // Check to see if Role Exists, if not create it
            if (!RoleManager.RoleExists(Role))
            {
                roleResult = RoleManager.Create(new CustomRole(Role));
                return(this.Request.CreateResponse(HttpStatusCode.OK, roleResult));
            }
            return(this.Request.CreateResponse(HttpStatusCode.OK, "role exist"));
        }
        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("删除角色成功");
        }
예제 #28
0
        public void PerformInitialSetup(ApplicationContext context)
        {
            // Context configuration settings will be specified here
            ApplicationUserManager userMgr = new ApplicationUserManager(new UserStore <ApplicationUser>(context));
            ApplicationRoleManager roleMgr = new ApplicationRoleManager(new RoleStore <ApplicationRole>(context));

            string roleNameA  = "Administrator";
            string userName   = "******";
            string password   = "******";
            string email      = "*****@*****.**";
            string roleNameUs = "User";

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

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

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

            if (!userMgr.IsInRole(user.Id, roleNameA))
            {
                userMgr.AddToRole(user.Id, roleNameA);
            }
        }
예제 #29
0
 private static IdentityResult CreateRole(string roleName, ApplicationRoleManager RoleManager)
 {
     if (!RoleManager.RoleExists(roleName))
     {
         var identresult = RoleManager.Create(new IdentityRole
         {
             Name = roleName
         });
         if (!identresult.Succeeded)
         {
             return(identresult);
         }
     }
     return(null);
 }
예제 #30
0
        protected override void Seed(Domen.infrastructure.Context context)
        {
            var roleManager = new ApplicationRoleManager(new RoleStore <ApplicationRole>(context)); //new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
            var userManager = new ApplicationUserManager(new UserStore <ApplicationUser>(context));

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

            const string userName = "******";
            const string pass     = "******";
            const string mail     = "*****@*****.**";

            var user = userManager.FindByName(userName);

            if (user != null)
            {
                return;
            }
            var result = userManager.Create(new ApplicationUser {
                Email = mail, UserName = userName, Nickname = "Manfice"
            }, pass);

            if (!result.Succeeded)
            {
                return;
            }
            user = userManager.FindByName(userName);
            using (var db = new Context())
            {
                var dbMember = db.Members.Where(member1 => member1.UserId.Equals(user.Id)).ToList();
                if (!dbMember.Any())
                {
                    var member = new Member
                    {
                        UserId     = user.Id,
                        PersonName = user.Nickname
                    };
                    db.Members.Add(member);
                    db.SaveChanges();
                }
            }
            if (!userManager.IsInRole(user.Id, "Admin"))
            {
                userManager.AddToRole(user.Id, "Admin");
            }
        }
예제 #31
0
 private void CreateDefaultRoles()
 {
     if (!ApplicationRoleManager.RoleExists("Admin"))
     {
         ApplicationRoleManager.Create(new IdentityRole()
         {
             Name = "Admin"
         });
     }
     if (!ApplicationRoleManager.RoleExists("User"))
     {
         ApplicationRoleManager.Create(new IdentityRole()
         {
             Name = "User"
         });
     }
 }
        public void Post(RoleUsersDto dto)
        {
            var context = ApplicationDbContext.Create();
            var userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(context));
            var roleManager = new ApplicationRoleManager(new RoleStore<ApplicationRole>(context));

            if (!roleManager.RoleExists(dto.RoleName)) return;
            foreach (
                var user in
                    dto.UserNames.Select(userName => userManager.FindByName(userName))
                        .Where(user => user != null)
                        .Where(user => !userManager.IsInRole(user.Id, dto.RoleName)))
            {
                userManager.AddToRole(user.Id, dto.RoleName);
            }
            foreach (
                var user in 
                    dto.UserNames.Select(userName => userManager.FindByName(userName))
                        .Where(user => user != null)
                        .Where(user => userManager.IsInRole(user.Id, dto.RoleName)))
            {
                userManager.RemoveFromRole(user.Id, dto.RoleName);
            }
        }
예제 #33
0
 public bool RoleExists(string name)
 {
     var rm = new ApplicationRoleManager(
         new RoleStore<IdentityRole>(context));
     return rm.RoleExists(name);
 }
예제 #34
0
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new User { UserName = model.Email, Email = model.Email, DisplayName = model.DisplayName, Time = DateTime.Now, IsDisabled = false, Profile = new Profile { Email = model.Email, Phone = "", Searchable = true, InformationPrivacy = false, Other = "" } };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
                    //为账户添加角色
                    var roleName = "student";
                    ApplicationRoleManager roleManager = new ApplicationRoleManager(new RoleStore<IdentityRole>(new BaseDbContext()));

                    //判断角色是否存在
                    if (!roleManager.RoleExists(roleName))
                    {
                        //角色不存在则建立角色
                        await roleManager.CreateAsync(new IdentityRole(roleName));
                    }
                    //将用户加入角色
                    await UserManager.AddToRoleAsync(user.Id, roleName);
                    
                    // 有关如何启用帐户确认和密码重置的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=320771
                    // 发送包含此链接的电子邮件
                    // 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, "确认你的帐户", "请通过单击 <a href=\"" + callbackUrl + "\">這裏</a>来确认你的帐户");

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

            // 如果我们进行到这一步时某个地方出错,则重新显示表单
            return View(model);
        }
        public async System.Threading.Tasks.Task<ActionResult> TutorCreate(CreateTutorViewModel model)
        {
            if (ModelState.IsValid)
            {
                if (Request.Files.Count != 1)//如果文件列表为空则返回
                {
                    ViewBag.Alert = "请检查上传文件!";

                    return View();
                }

                var file = Request.Files[0];//只上传第一个文件

                var user = Models.User.Create(model.Email, model.DisplayName);
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    //为账户添加角色
                    var roleName = "Tutor";
                    ApplicationRoleManager roleManager = new ApplicationRoleManager(new RoleStore<IdentityRole>(db));

                    //判断角色是否存在
                    if (!roleManager.RoleExists(roleName))
                    {
                        //角色不存在则建立角色
                        await roleManager.CreateAsync(new IdentityRole(roleName));
                    }
                    //将用户加入角色
                    await UserManager.AddToRoleAsync(user.Id, roleName);

                    // 有关如何启用帐户确认和密码重置的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=320771
                    // 发送包含此链接的电子邮件
                    // 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, "确认你的帐户", "请通过单击 <a href=\"" + callbackUrl + "\">這裏</a>来确认你的帐户");

                    var avatar = Material.Create(user.DisplayName, MaterialType.Avatar, file, db);
                    if (avatar == null)
                    {
                        TempData["ALert"] = "请检查上传文件!";
                        return View(model);
                    }
                    var tutor = new TutorInformation { Id = Guid.NewGuid(), Tutor = db.Users.Find(user.Id), Avatar = avatar, Position = model.Position, Introduction = model.Introduction };
                    db.TutorInformations.Add(tutor);
                    db.SaveChanges();
                    ViewBag.Alert = "操作成功!";

                    return View();
                }
            }
            ViewBag.Alert = "操作失败!";

            return View();
        }