// In this method we will create default User roles and Admin user for login private void createRolesandUsers() { ApplicationDbContext context = new ApplicationDbContext(); var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); // In Startup iam creating first Admin Role and creating a default Admin User if (!roleManager.RoleExists("Admin")) { // first we create Admin rool var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(); role.Name = "Admin"; roleManager.Create(role); //Here we create a Admin super user who will maintain the website var user = new ApplicationUser(); user.Email = "Gaving30gmail.com"; string userPWD = "testPassword1."; var chkUser = UserManager.Create(user, userPWD); //Add default User to Role Admin if (chkUser.Succeeded) { var result1 = UserManager.AddToRole(user.Id, "Admin"); } } }
internal void CreateUserAndRole() { using (var context = new WebDeveloperDbContext()) { var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); var userManager = new UserManager<WebDeveloperUser>(new UserStore<WebDeveloperUser>(context)); // In Startup iam creating first Admin Role and creating a default Admin User if (!roleManager.RoleExists("Admin")) { // first we create Admin rool var role = new IdentityRole(); role.Name = "Admin"; roleManager.Create(role); //Here we create a Admin super user who will maintain the website var user = new WebDeveloperUser { UserName = "******", Email = "*****@*****.**" }; string userPassword = "******"; var userCreation = userManager.Create(user, userPassword); //Add default User to Role Admin if (userCreation.Succeeded) userManager.AddToRole(user.Id, "Admin"); } // creating Creating Manager role if (!roleManager.RoleExists("Manager")) { var role = new IdentityRole { Name = "Manager" }; roleManager.Create(role); } // creating Creating Employee role if (!roleManager.RoleExists("Employee")) { var role = new IdentityRole { Name = "Employee" }; roleManager.Create(role); } } }
public void Configuration(IAppBuilder app) { ConfigureAuth(app); var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext())); if (!roleManager.RoleExists("manager")) { var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(); role.Name = "manager"; roleManager.Create(role); } if (!roleManager.RoleExists("agent")) { var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(); role.Name = "agent"; roleManager.Create(role); } if (!roleManager.RoleExists("doctor")) { var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(); role.Name = "doctor"; roleManager.Create(role); } using (var rm = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()))) using (var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()))) { var user = um.FindByEmail("*****@*****.**"); um.AddToRole(user.Id, "agent"); user = um.FindByEmail("*****@*****.**"); um.AddToRole(user.Id, "manager"); user = um.FindByEmail("*****@*****.**"); um.AddToRole(user.Id, "doctor"); } }
// In this method we will create default User roles and Admin user for login private void createRolesandUsers() { ApplicationDbContext context = new ApplicationDbContext(); var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); // In Startup iam creating first Admin Role and creating a default Admin User if (!roleManager.RoleExists("Admin")) { // first we create Admin rool var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(); role.Name = "Admin"; roleManager.Create(role); //Creacion del superadmin var user = new ApplicationUser(); user.UserName = "******"; user.Email = "*****@*****.**"; string userPWD = "123456"; var chkUser = UserManager.Create(user, userPWD); //Rol por defecto que es Admin if (chkUser.Succeeded) { var result1 = UserManager.AddToRole(user.Id, "Admin"); } } // Creacion de nuevos roles if (!roleManager.RoleExists("Cliente")) { var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(); role.Name = "Cliente"; roleManager.Create(role); } }
private void createRolesandUsers() { ApplicationDbContext context = new ApplicationDbContext(); var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); if (!roleManager.RoleExists("Admin")) { var role = new IdentityRole(); role.Name = "Admin"; roleManager.Create(role); var user = new ApplicationUser(); user.UserName = "******"; user.Email = "*****@*****.**"; string userPWD = "Test#1"; var chkUser = UserManager.Create(user, userPWD); if (chkUser.Succeeded) { var result1 = UserManager.AddToRole(user.Id, "Admin"); } } if (!roleManager.RoleExists("Educator")) { var role = new IdentityRole(); role.Name = "Educator"; roleManager.Create(role); } if (!roleManager.RoleExists("Student")) { var role = new IdentityRole(); role.Name = "Student"; roleManager.Create(role); } }
public async Task<ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser() { Email = model.Email, UserName = model.UserName,BirthDate = model.birthDate, Country = model.country, City = model.city, Address = model.address}; IdentityResult result = await UserManager.CreateAsync(user, model.Password); var store = new UserStore<ApplicationUser>(db); var manager = new UserManager<ApplicationUser>(store); if (result.Succeeded) { await SignInAsync(user, isPersistent: false); manager.AddToRole(user.Id, "Users"); // 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"); } else { AddErrors(result); } } // If we got this far, something failed, redisplay form return View(model); }
private static void CreateAdminUser(UserManager<ApplicationUser> userManager) { var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ContosoWebContext(StaticConfig.DbContext.WebConnectionStringName))); if (!roleManager.RoleExists(AdminConstants.Role)) { roleManager.Create(new IdentityRole(AdminConstants.Role)); } var username = ConfigurationHelpers.GetString("Authentication.Administrator.UserName"); var password = ConfigurationHelpers.GetString("Authentication.Administrator.Password"); var user = userManager.FindByName(username); if (user == null) { user = new ApplicationUser { UserName = username, Email = username }; var result = userManager.Create(user, password); if (!result.Succeeded) throw new Exception(string.Format("Failed to create admin user: {0}", string.Join(",", result.Errors))); user = userManager.FindByName(username); userManager.AddToRole(user.Id, AdminConstants.Role); userManager.AddClaim(user.Id, new Claim(AdminConstants.ManageStore.Name, AdminConstants.ManageStore.Allowed)); } }
public ActionResult RoleAddToUser(string roleName, string userName) { List<string> roles; List<string> users; using (var context = new ApplicationDbContext()) { var roleStore = new RoleStore<IdentityRole>(context); var roleManager = new RoleManager<IdentityRole>(roleStore); var userStore = new UserStore<ApplicationUser>(context); var userManager = new UserManager<ApplicationUser>(userStore); users = (from u in userManager.Users select u.UserName).ToList(); var user = userManager.FindByName(userName); if (user == null) throw new Exception("User not found!"); var role = roleManager.FindByName(roleName); if (role == null) throw new Exception("Role not found!"); if (userManager.IsInRole(user.Id, role.Name)) { ViewBag.ResultMessage = "This user already has the role specified !"; } else { userManager.AddToRole(user.Id, role.Name); context.SaveChanges(); ViewBag.ResultMessage = "Username added to the role succesfully !"; } roles = (from r in roleManager.Roles select r.Name).ToList(); } ViewBag.Roles = new SelectList(roles); ViewBag.Users = new SelectList(users); return View(); }
public async Task<ActionResult> Register(RegisterViewModel model) { using (var context = new ApplicationDbContext()) { if (ModelState.IsValid) { var user = new ApplicationUser() { UserName = model.Email, Email = model.Email }; IdentityResult result = await UserManager.CreateAsync(user, model.Password); var roleStore = new RoleStore<IdentityRole>(context); var roleManager = new RoleManager<IdentityRole>(roleStore); var userStore = new UserStore<ApplicationUser>(context); var userManager = new UserManager<ApplicationUser>(userStore); if (model.idRoles == 1) { userManager.AddToRole(user.Id, "Entreprise"); } if (model.idRoles == 2) { userManager.AddToRole(user.Id, "Developer"); } if (result.Succeeded) { await SignInAsync(user, isPersistent: false); if (model.idRoles == 1) return RedirectToAction("Add", "Company"); if (model.idRoles == 2) return RedirectToAction("Add", " Developer"); } else { AddErrors(result); } } // If we got this far, something failed, redisplay form return View(model); } }
public void Configuration(IAppBuilder app) { ConfigureAuth(app); #region Add Admin and Role for Admin using (var context = new ApplicationDbContext()) { var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); var aspUser = UserManager.FindByName(Constant.USER_USERNAME); if (aspUser != null) { UserManager.RemovePassword(aspUser.Id); UserManager.AddPassword(aspUser.Id, Constant.USER_PASS); } else { aspUser = new ApplicationUser() { UserName = Constant.USER_USERNAME }; var result = UserManager.Create(aspUser, Constant.USER_PASS); if (result.Succeeded) { var user = new User { UserName = Constant.USER_USERNAME, Email = Constant.USER_EMAIL, Phone = Constant.USER_PHONE, Address = Constant.USER_ADDRESS, AspnetId = aspUser.Id }; using (var db = new TShirtEntities()) { db.User.Add(user); db.SaveChanges(); } } } // Create Role IdentityResult roleResult = null; if (!RoleManager.RoleExists(Constant.ROLES_ADMIN)) { roleResult = RoleManager.Create(new IdentityRole(Constant.ROLES_ADMIN)); } // Add role to admin if (roleResult != null && roleResult.Succeeded) UserManager.AddToRole(aspUser.Id, Constant.ROLES_ADMIN); } #endregion #region Add Constants Config var lstConfig = new List<Config>(); using (var db = new TShirtEntities()) { var fb = db.Config.FirstOrDefaultAsync(m => m.Code == Constant.CODE_MESS_FACEBOOK); var price = db.Config.FirstOrDefaultAsync(m => m.Code == Constant.CODE_PRICE_DESIGN); if (fb == null) { lstConfig.Add(new Config() { Code = Constant.CODE_MESS_FACEBOOK, Value = "Website thiết kế áo chuyên nghiệp", Description = "Nội dung khi chia sẻ trên facebook" }); } if (price == null) { lstConfig.Add(new Config() { Code = Constant.CODE_PRICE_DESIGN, Value = "15000", Description = "Giá một icon design" }); } if (lstConfig.Count > 0) { db.Config.AddRange(lstConfig); db.SaveChanges(); } } #endregion }
protected void CreateUser_Click(object sender, EventArgs e) { Models.ApplicationDbContext context = new ApplicationDbContext(); IdentityResult IdUserResult; var roleStore = new RoleStore<IdentityRole>(context); var roleMgr = new RoleManager<IdentityRole>(roleStore); var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>(); DateTime dateValue; bool noDate = false; if (!DateTime.TryParse(BirthdayRegister.Text, out dateValue)) noDate = true; ApplicationUser user; if (noDate) { user = new ApplicationUser() { UserName = EmailRegister.Text, Email = EmailRegister.Text, NIF = NIFRegister.Text, FullName = FullNameRegister.Text }; } else { user = new ApplicationUser() { UserName = EmailRegister.Text, Email = EmailRegister.Text, BirthDate = dateValue, NIF = NIFRegister.Text, FullName = FullNameRegister.Text }; } try { IdentityResult result = manager.Create(user, PasswordRegister.Text); if (result.Succeeded) { if (ReferralRegister.Text != null && ReferralRegister.Text != "") { string constring = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; SqlConnection con = new SqlConnection(constring); using (SqlCommand cmd = new SqlCommand("sp_incrementPoints", con)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@referrer", ReferralRegister.Text); cmd.Parameters.AddWithValue("@points", 10); con.Open(); cmd.ExecuteNonQuery(); } } if (!userMgr.IsInRole(user.Id, "member")) IdUserResult = userMgr.AddToRole(user.Id, "member"); signInManager.SignIn(user, isPersistent: false, rememberBrowser: false); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { ErrorRegister.Text = result.Errors.FirstOrDefault(); } } catch (Exception) { } }
public async Task<ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser() { UserName = model.UserName, Email = model.Email }; IdentityResult result = await UserManager.CreateAsync(user, model.Password); // user.EmailConfirmed = true; if (result.Succeeded) { await SignInAsync(user, isPersistent: 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", "Hello " +user.UserName +"<br> Your password:"******"<br>Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); Models.ApplicationDbContext context = new ApplicationDbContext(); var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); userMgr.AddToRole(user.Id, "RegUser"); var userInfo = new UserInfo(); userInfo.Firstname = model.FirstName; userInfo.Lastname = model.LastName; userInfo.UserId = user.Id; db.UserInfoes.Add(userInfo); db.SaveChanges(); return RedirectToAction("Login", "Account"); } else { AddErrors(result); } } // If we got this far, something failed, redisplay form return View(model); }
private void CreateAndLoginUser() { Models.ApplicationDbContext context = new ApplicationDbContext(); IdentityResult IdUserResult; var roleStore = new RoleStore<IdentityRole>(context); var roleMgr = new RoleManager<IdentityRole>(roleStore); var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); if (!IsValid) { return; } var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); var signInManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>(); DateTime dateValue; bool noDate = false; if (!DateTime.TryParse(BirthdayRegister.Text, out dateValue)) noDate = true; ApplicationUser user; if (noDate) { user = new ApplicationUser() { UserName = email.Text, Email = email.Text, NIF = NIFRegister.Text, FullName = FullNameRegister.Text }; } else { user = new ApplicationUser() { UserName = email.Text, Email = email.Text, BirthDate = dateValue, NIF = NIFRegister.Text, FullName = FullNameRegister.Text }; } IdentityResult result = manager.Create(user); if (result.Succeeded) { if (!userMgr.IsInRole(user.Id, "member")) IdUserResult = userMgr.AddToRole(user.Id, "member"); var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(); if (loginInfo == null) { RedirectOnFail(); return; } result = manager.AddLogin(user.Id, loginInfo.Login); if (result.Succeeded) { signInManager.SignIn(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 // var code = manager.GenerateEmailConfirmationToken(user.Id); // Send this link via email: IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id) Response.Redirect("~"); return; } } AddErrors(result); }
private static void SetupUsers(ApplicationDbContext db) { using (var rm = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()))) using (var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()))) { // Creating roles foreach (var role in Enum.GetValues(typeof(Constants.UserRole))) { if (rm.RoleExists(role.ToString())) continue; var result = rm.Create(new IdentityRole(role.ToString())); if (!result.Succeeded) throw new ApplicationException("Creating role " + role + " failed with error(s):\n" + GetAllErrors(result)); } // Creating users foreach (var newUser in UsersToSetup) { var existingUser = um.FindByEmail(newUser.Email); if (existingUser == null) { var result = um.Create(new ApplicationUser { Email = newUser.Email, EmailConfirmed = true, UserName = newUser.Email, LockoutEnabled = newUser.LockoutEnabled }, newUser.Password); if (!result.Succeeded) throw new ApplicationException("Creating user " + newUser.Email + " failed with error(s):\n" + GetAllErrors(result)); } existingUser = um.FindByEmail(newUser.Email); if (!um.IsInRole(existingUser.Id, Constants.UserRole.Admin.ToString())) { var result = um.AddToRole(existingUser.Id, Constants.UserRole.Admin.ToString()); if (!result.Succeeded) throw new ApplicationException("Adding role " + Constants.UserRole.Admin + " for " + newUser.Email + " failed with error(s):\n" + GetAllErrors(result)); } } db.SaveChanges(); } }
public ActionResult AddRoleToUser(string roleName, string userName) { List<string> roles; using (var context = new ApplicationDbContext()) { var roleStore = new RoleStore<IdentityRole>(context); var roleManager = new RoleManager<IdentityRole>(roleStore); var userStore = new UserStore<ApplicationUser>(context); var userManager = new UserManager<ApplicationUser>(userStore); var user = userManager.FindByName(userName); if (user == null) { throw new Exception("User not found!"); } if (roleManager == null) { throw new Exception("Roles not found!"); } var role = roleManager.FindByName(roleName); if (userManager.IsInRole(user.Id, role.Name)) { ViewBag.ErrorMessage = "This user already has the role specified!"; roles = (from r in roleManager.Roles select r.Name).ToList(); ViewBag.Roles = new SelectList(roles); ViewBag.UserName = userName; return View(); } else { userManager.AddToRole(user.Id, role.Name); context.SaveChanges(); List<string> userRoles; var userRoleIds = (from r in user.Roles select r.RoleId); userRoles = (from id in userRoleIds let r = roleManager.FindById(id) select r.Name).ToList(); ViewBag.UserName = userName; ViewBag.RolesForUser = userRoles; return View("ViewUserRoles"); } } }
private static void AddUser(ApplicationDbContext context, string userName, string role) { var userStore = new UserStore<ApplicationUser>(context); var userManager = new UserManager<ApplicationUser>(userStore); if (!context.Users.Any(u => u.UserName == userName)) { var user = new ApplicationUser { UserName = userName, Email = userName }; IdentityResult result = userManager.Create(user, "Passw0rd!"); userManager.AddToRole(user.Id, role); context.SaveChanges(); } }
//Create default User roles and Admin user for login private void CreateRolesandUsers() { ApplicationDbContext context = new ApplicationDbContext(); var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); // Creating first Admin Role and creating a default Admin User if (!roleManager.RoleExists("Admin")) { // Create Admin roll var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(); role.Name = "Admin"; roleManager.Create(role); // Create an Admin super user who will maintain the website var user = new ApplicationUser(); user.UserName = "******"; user.FirstName = "Admin"; user.LastName = "RDCC"; user.EmailAddress = "*****@*****.**"; string userPWD = "Rdcc1234!"; var chkUser = userManager.Create(user, userPWD); var adminRole = roleManager.FindByName("Admin"); //Add default User to Role Admin if (chkUser.Succeeded) { var result1 = userManager.AddToRole(user.Id, "Admin"); } } // creating Creating Member role if (!roleManager.RoleExists("Member")) { var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(); role.Name = "Member"; roleManager.Create(role); } // creating Creating Chairman role if (!roleManager.RoleExists("Chairman")) { var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(); role.Name = "Chairman"; roleManager.Create(role); } // creating Creating Secretary role if (!roleManager.RoleExists("Secretary")) { var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(); role.Name = "Secretary"; roleManager.Create(role); } // creating Creating Programme Secretary role if (!roleManager.RoleExists("Programme Secretary")) { var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(); role.Name = "Programme Secretary"; roleManager.Create(role); } // creating Creating Treasurer role if (!roleManager.RoleExists("Treasurer")) { var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(); role.Name = "Treasurer"; roleManager.Create(role); } // creating Creating Committee Member role if (!roleManager.RoleExists("Committee Member")) { var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(); role.Name = "Committee Member"; roleManager.Create(role); } // creating Creating Webmaster role if (!roleManager.RoleExists("Webmaster")) { var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(); role.Name = "Webmaster"; roleManager.Create(role); } if (!roleManager.RoleExists("Publicity Officer")) { var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(); role.Name = "Publicity Officer"; roleManager.Create(role); } }