internal void AddUserAndRole() { ApplicationDbContext context = new ApplicationDbContext(); IdentityResult IdRoleResult; IdentityResult IdUserResult; RoleStore<IdentityRole> roleStore = new RoleStore<IdentityRole>(context); RoleManager<IdentityRole> roleMgr = new RoleManager<IdentityRole>(roleStore); //create admin role if(!roleMgr.RoleExists("admin")) { IdRoleResult = roleMgr.Create(new IdentityRole { Name = "admin" }); } //create master user UserManager<ApplicationUser> userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); ApplicationUser appUser = new ApplicationUser { UserName = "Adam", Email = "[email protected]" }; IdUserResult = userMgr.Create(appUser, "Baseball1!"); //add to admin role if(!userMgr.IsInRole(userMgr.FindByEmail("[email protected]").Id, "admin")) { IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("[email protected]").Id, "admin"); } }
/// <summary> /// Checks for the three roles - Admin, Employee and Complainant and /// creates them if not present /// </summary> public static void InitializeRoles() { // Access the application context and create result variables. ApplicationDbContext context = new ApplicationDbContext(); IdentityResult IdUserResult; // Create a RoleStore object by using the ApplicationDbContext object. // The RoleStore is only allowed to contain IdentityRole objects. var roleStore = new RoleStore<IdentityRole>(context); RoleManager roleMgr = new RoleManager(); if (!roleMgr.RoleExists("Administrator")) { roleMgr.Create(new ApplicationRole { Name = "Administrator" }); } if (!roleMgr.RoleExists("Employee")) { roleMgr.Create(new ApplicationRole { Name = "Employee" }); } if (!roleMgr.RoleExists("Complainant")) { roleMgr.Create(new ApplicationRole { Name = "Complainant" }); } if (!roleMgr.RoleExists("Auditor")) { roleMgr.Create(new ApplicationRole { Name = "Auditor" }); } // Create a UserManager object based on the UserStore object and the ApplicationDbContext // object. Note that you can create new objects and use them as parameters in // a single line of code, rather than using multiple lines of code, as you did // for the RoleManager object. var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var appUser = new ApplicationUser { UserName = "Administrator", Email = "[email protected]" }; IdUserResult = userMgr.Create(appUser, "Admin123"); // If the new "canEdit" user was successfully created, // add the "canEdit" user to the "canEdit" role. if (!userMgr.IsInRole(userMgr.FindByEmail("[email protected]").Id, "Administrator")) { IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("[email protected]").Id, "Administrator"); } appUser = new ApplicationUser { UserName = "Auditor", Email = "[email protected]" }; IdUserResult = userMgr.Create(appUser, "Auditor123"); // If the new "canEdit" user was successfully created, // add the "canEdit" user to the "canEdit" role. if (!userMgr.IsInRole(userMgr.FindByEmail("[email protected]").Id, "Auditor")) { IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("[email protected]").Id, "Auditor"); } }
internal void AddUserAndRole() { Models.ApplicationDbContext db = new ApplicationDbContext(); IdentityResult IdRoleResult; IdentityResult IdUserResult; var roleStore = new RoleStore<IdentityRole>(db); var roleMgr = new RoleManager<IdentityRole>(roleStore); if (!roleMgr.RoleExists("canEdit")) { IdRoleResult = roleMgr.Create(new IdentityRole { Name = "canEdit" }); } var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db)); var appUser = new ApplicationUser { UserName = "[email protected]", Email = "[email protected]" }; IdUserResult = userMgr.Create(appUser, "NhatSinh123*"); if (!userMgr.IsInRole(userMgr.FindByEmail("[email protected]").Id, "canEdit")) { IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("[email protected]").Id, "canEdit"); } }
internal void AddUserAndRole() { // Access the application context and create result variable. Models.ApplicationDbContext context = new ApplicationDbContext(); IdentityResult IdRoleResult; IdentityResult IdUserResult; // Create a RoleStore object by using the ApplicationDbContext object. // The RoleStore is only allowed to contain IdentityRole Objects. var roleStore = new RoleStore<IdentityRole>(context); // Create a RoleManager object that is only allowed to contain IdentityRole objects. // When creating the RoleManager object, you pass in (as a parameter) a new RoleStore object. var roleMgr = new RoleManager<IdentityRole>(roleStore); // Then, you create the "canEdit" role if it doesn't already exist. if (!roleMgr.RoleExists("canEdit")) IdRoleResult = roleMgr.Create(new IdentityRole { Name = "canEdit" }); // Create a UserManager object based on the UserStore objcet and the ApplicationDbContext objcet. // Note that you can create new objects and use them as parameters in a single line of code, rather than using multiple lines of code, as you did for the RoleManager object. var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var appUser = new ApplicationUser { UserName = "[email protected]", Email = "[email protected]" }; IdUserResult = userMgr.Create(appUser, "Pa$$word1"); // If the new "canEdit" user was successfully created, add the "canEdit" user to the "canEdit" role. if (!userMgr.IsInRole(userMgr.FindByEmail("[email protected]").Id, "canEdit")) IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("[email protected]").Id, "canEdit"); }
internal void AddUserAndRole() { // access the application context and create result variables. Models.ApplicationDbContext context = new ApplicationDbContext(); IdentityResult IdRoleResult; IdentityResult IdUserResult; // create roleStore object that can only contain IdentityRole objects by using the ApplicationDbContext object. var roleStore = new RoleStore<IdentityRole>(context); var roleMgr = new RoleManager<IdentityRole>(roleStore); // create admin role if it doesn't already exist if (!roleMgr.RoleExists("admin")) { IdRoleResult = roleMgr.Create(new IdentityRole { Name = "admin" }); } // create a UserManager object based on the UserStore object and the ApplicationDbContext object. // defines admin email account var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var appUser = new ApplicationUser { UserName = "[email protected]", Email = "[email protected]" }; IdUserResult = userMgr.Create(appUser, "Pa$$word1"); // If the new admin user was successfully created, add the new user to the "admin" role. if (!userMgr.IsInRole(userMgr.FindByEmail("[email protected]").Id, "admin")) { IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("[email protected]").Id, "admin"); } }
internal void AddUserAndRole() { ApplicationDbContext context = new ApplicationDbContext(); IdentityResult IdRoleResult; IdentityResult IdUserResult; var roleStore = new RoleStore<IdentityRole>(context); var roleMgr = new RoleManager<IdentityRole>(roleStore); if (!roleMgr.RoleExists("Admin")) { IdRoleResult = roleMgr.Create(new IdentityRole { Name = "Admin" }); } var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var appUser = new ApplicationUser { Email = "[email protected]" }; IdUserResult = userMgr.Create(appUser, "adminA123..."); if (!userMgr.IsInRole(userMgr.FindByEmail("[email protected]").Id, "Admin")) { IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("[email protected]").Id, "canEdit"); } }
internal void AddToNormalUserRole(ApplicationUser user) { Models.ApplicationDbContext context = new ApplicationDbContext(); var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); if (!userMgr.IsInRole(userMgr.FindByEmail(user.Email).Id, "Normal")) { userMgr.AddToRole(userMgr.FindByEmail(user.Email).Id, "Normal"); } }
protected override void Seed(Context context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. E.g. // // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "Andrew Peters" }, // new Person { FullName = "Brice Lambson" }, // new Person { FullName = "Rowan Miller" } // ); // var userStore = new UserStore<ApplicationUser>(context); var mngr = new UserManager<ApplicationUser>(userStore); context.Roles.AddOrUpdate(r => r.Name, new IdentityRole { Name = "Administrators" }); ApplicationUser adm = new ApplicationUser(); adm.Email = "[email protected]"; adm.UserName = "admin"; mngr.Create(adm, "Adm!n0"); context.SaveChanges(); IdentityRole adrol = context.Roles.First(x => x.Name == "Administrators"); adm = mngr.FindByEmail("[email protected]"); mngr.AddToRole(adm.Id, adrol.Name); context.SaveChanges(); }
public override void Validate(string userNameOrEmail, string password) { try { using (var context = new IdentityDbContext()) { using (var userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(context))) { string userName = userNameOrEmail; if (userNameOrEmail.Contains('@')) { var userForEmail = userManager.FindByEmail(userNameOrEmail); if (userForEmail != null) { userName = userForEmail.UserName; } } var user = userManager.Find(userName, password); if (user == null) { var msg = String.Format("Unknown Username {0} or incorrect password {1}", userNameOrEmail, password); Trace.TraceWarning(msg); throw new FaultException(msg); } } } } catch (Exception e) { var msg = e.Message; Trace.TraceWarning(msg); throw new FaultException(msg); } }
public string getUserId(string user_name) { Models.ApplicationDbContext context = new ApplicationDbContext(); var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var Id = userMgr.FindByEmail(user_name).Id; return Id; }
/// <summary> /// This will generate a new company from a view company /// </summary> /// <param name="comp">the company to be generated</param> /// <returns>the company that should be added to the database</returns> public Company GenerateCompany(ViewCompany comp, int _lenghtOfPassword, int _numberOfAlphabeticCharacters) { var result = new Company() {Active = true, Name = comp.Name, PhoneNr = comp.PhoneNr}; //Generates a random password, and makes a new user with the correct email var password = System.Web.Security.Membership.GeneratePassword(_lenghtOfPassword, _numberOfAlphabeticCharacters); var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new DAL.Context.Context())); var user = new ApplicationUser() { UserName = comp.Email, Email = comp.Email }; um.Create(user, password); //Generates the access string by encoding the email and the password into an array of bytes. var bytes = System.Text.Encoding.UTF8.GetBytes(comp.Email + ":" + password); result.AccessString = System.Convert.ToBase64String(bytes); result.Active = true; //This will be so that the database will make the relation between the two. var item = um.FindByEmail(comp.Email); result.IdentityId = item.Id; return result; }
/*This should be removed after the first admin gets made */ // GET: MakeMeAdmin/Create public ActionResult Create(string email) { using (var context = new ApplicationDbContext()) { var fadmin = context.KeyValueSettings.FirstOrDefault(s => s.Key == "FirstAdminSet"); if (fadmin == null || fadmin.Value == "false") { var roleStore = new RoleStore<IdentityRole>(context); var roleManager = new RoleManager<IdentityRole>(roleStore); roleManager.Create(new IdentityRole("Admin")); var userStore = new UserStore<ApplicationUser>(context); var userManager = new UserManager<ApplicationUser>(userStore); var user = userManager.FindByEmail(email); userManager.AddToRole(user.Id, "Admin"); if (fadmin == null) { context.KeyValueSettings.Add(new KeyValueSettings() { Key = "FirstAdminSet", Value = "true" }); } else { fadmin.Value = "true"; } context.SaveChanges(); return Json(true, JsonRequestBehavior.AllowGet); } } return Json(false, JsonRequestBehavior.AllowGet); }
internal void AddUserAndRole() { // Access the application context and create result variables. Models.ApplicationDbContext context = new ApplicationDbContext(); IdentityResult IdRoleResult; IdentityResult IdUserResult; // Create a RoleStore object by using the ApplicationDbContext object. // The RoleStore is only allowed to contain IdentityRole objects. var roleStore = new RoleStore<IdentityRole>(context); // Create a RoleManager object that is only allowed to contain IdentityRole objects. // When creating the RoleManager object, you pass in (as a parameter) a new RoleStore object. var roleMgr = new RoleManager<IdentityRole>(roleStore); // Then, you create the "canEdit" role if it doesn't already exist. if (!roleMgr.RoleExists("SuperAdmin")) { IdRoleResult = roleMgr.Create(new IdentityRole { Name = "SuperAdmin" }); } if (!roleMgr.RoleExists("RegUser")) { IdRoleResult = roleMgr.Create(new IdentityRole { Name = "RegUser" }); } // Create a UserManager object based on the UserStore object and the ApplicationDbContext // object. Note that you can create new objects and use them as parameters in // a single line of code, rather than using multiple lines of code, as you did // for the RoleManager object. var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); if (userMgr.FindByEmail("[email protected]") == null) { var appUser = new ApplicationUser { UserName = "AdminSw", Email = "[email protected]" }; IdUserResult = userMgr.Create(appUser, "Pantelic93."); } // If the new "canEdit" user was successfully created, // add the "canEdit" user to the "canEdit" role. if (!userMgr.IsInRole(userMgr.FindByEmail("[email protected]").Id, "SuperAdmin")) { IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("[email protected]").Id, "SuperAdmin"); } }
internal void AddUserAndRole() { // Access the application context and create result variables. GolddiggerDbContext context = new GolddiggerDbContext(); IdentityResult IdRoleResult; IdentityResult IdUserResult; // Create a RoleStore object by using the ApplicationDbContext object. // The RoleStore is only allowed to contain IdentityRole objects. var roleStore = new RoleStore<IdentityRole>(context); // Create a RoleManager object that is only allowed to contain IdentityRole objects. // When creating the RoleManager object, you pass in (as a parameter) a new RoleStore object. var roleMgr = new RoleManager<IdentityRole>(roleStore); // Then, you create the "admin" role if it doesn't already exist. if (!roleMgr.RoleExists("admin")) { IdRoleResult = roleMgr.Create(new IdentityRole { Name = "admin" }); } // Create a UserManager object based on the UserStore object and the ApplicationDbContext // object. Note that you can create new objects and use them as parameters in // a single line of code, rather than using multiple lines of code, as you did // for the RoleManager object. var userMgr = new UserManager<User>(new UserStore<User>(context)); var appUser = new User { UserName = "admin", Email = "[email protected]", IsFemale = true, ProfilePhoto = new byte[8] }; IdUserResult = userMgr.Create(appUser, "Pa$$word1"); // If the new "admin" user was successfully created, // add the "admin" user to the "admin" role. if (!userMgr.IsInRole(userMgr.FindByEmail("[email protected]").Id, "admin")) { IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("[email protected]").Id, "admin"); } }
public ActionResult Adminator(string email) { var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db)); roleManager.Create(new IdentityRole("Administrator")); var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db)); var user = userManager.FindByEmail(email); userManager.AddToRole(user.Id, "Administrator"); return View(); }
public string getUserRole(string user_name) { Models.ApplicationDbContext context = new ApplicationDbContext(); var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var roleStore = new RoleStore<IdentityRole>(context); var roleMgr = new RoleManager<IdentityRole>(roleStore); var userRoleId = userMgr.FindByEmail(user_name).Roles.First().RoleId; var rolename = roleMgr.Roles.Where(m => m.Id == userRoleId).First().Name; return rolename; }
internal void AddUserAndRole() { // Access the application context and create result variables. Models.ApplicationDbContext context = new ApplicationDbContext(); IdentityResult IdRoleResult; IdentityResult IdUserResult; // Create a RoleStore object by using the ApplicationDbContext object. // The RoleStore is only allowed to contain IdentityRole objects. var roleStore = new RoleStore<IdentityRole>(context); // Create a RoleManager object that is only allowed to contain IdentityRole objects. // When creating the RoleManager object, you pass in (as a parameter) a new RoleStore object. var roleMgr = new RoleManager<IdentityRole>(roleStore); // Create the admin role if (!roleMgr.RoleExists("Admin")) { IdRoleResult = roleMgr.Create(new IdentityRole { Name = "Admin" }); } // Create a UserManager object based on the UserStore object and the ApplicationDbContext // object. Note that you can create new objects and use them as parameters in // a single line of code, rather than using multiple lines of code, as you did // for the RoleManager object. var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var appUser = new ApplicationUser { UserName = "admin", Email = "[email protected]", FirstName = "admin", LastName = "admin" }; IdUserResult = userMgr.Create(appUser, "admin1234"); if (!userMgr.IsInRole(userMgr.FindByEmail("[email protected]").Id, "Admin")) { IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("[email protected]").Id, "Admin"); } }
public ActionResult ForgotPassword(string email) { var userStore = new UserStore<IdentityUser>(); UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore); var user = manager.FindByEmail(email); CreateTokenProvider(manager, PASSWORD_RESET); var code = manager.GeneratePasswordResetToken(user.Id); var callbackUrl = Url.Action("ResetPassword", "Home", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); ViewBag.FakeEmailMessage = "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>"; return View(); }
public ActionResult Index() { using (var context = new ApplicationDbContext()) { var roleStore = new RoleStore<IdentityRole>(context); var roleManager = new RoleManager<IdentityRole>(roleStore); roleManager.Create(new IdentityRole("Admin")); var userStore = new UserStore<ApplicationUser>(context); var userManager = new UserManager<ApplicationUser>(userStore); var user = userManager.FindByEmail("[email protected]"); userManager.AddToRole(user.Id, "Admin"); context.SaveChanges(); } return View(); }
public ActionResult AddRoleToUser(string Email, string RoleName) { var context = new ApplicationDbContext(); var userStore = new UserStore<ApplicationUser>(context); var userManager = new UserManager<ApplicationUser>(userStore); var roleStore = new RoleStore<IdentityRole>(context); var roleManager = new RoleManager<IdentityRole>(roleStore); var user = userManager.FindByEmail(Email); if (user != null) { var role = roleManager.FindByName(RoleName); if (role != null) { if (!userManager.IsInRole(user.Id, role.Name)) { userManager.AddToRole(user.Id, role.Name); context.SaveChanges(); } } } return RedirectToAction("RolesIndex", "Account"); }
public async Task<ActionResult> AddManagerTobuilding(ManagementBuilding model, ManagerVM model2) { try { if (!ModelState.IsValid) { return View("ManagementBuilding", model); } ApplicationDbContext context = new ApplicationDbContext(); var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); PasswordHasher hasher = new PasswordHasher(); var a = UserManager.FindByEmail(model2.Email); if (a != null) { return View("ManagementBuilding", model); } ApplicationUser AppUser = new ApplicationUser() { Id = Guid.NewGuid().ToString(), Email = model2.Email, UserName = model2.Username, SecurityStamp = Guid.NewGuid().ToString(), PhoneNumber = model2.Phone, LockoutEnabled = false, LockoutEndDateUtc= DateTime.Now.AddDays(365), AccessFailedCount = 0, PhoneNumberConfirmed = false, TwoFactorEnabled = false, EmailConfirmed = false, PasswordHash = hasher.HashPassword(model2.Password) }; string[] FullName = model2.FullName.Split(new string[] { " " }, StringSplitOptions.None); Manager mgr = new Manager() { ID = AppUser.Id, FirstName = FullName[0].ToString(), LastName = FullName[1].ToString(), Phone = model2.Phone, ClientID = model2.clientID }; db.Manager.Add(mgr); context.Users.Add(AppUser); await context.SaveChangesAsync(); await db.SaveChangesAsync(); RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); if (!RoleManager.RoleExists("Manager")) {var roleresult = RoleManager.Create(new IdentityRole("Manager"));} var Result = UserManager.AddToRole(AppUser.Id, "Manager"); ManagerBuilding ObjManagerBuilding = new ManagerBuilding() { BuildingID = model2.BuildingID, ManagerID = mgr.ID , UserID =mgr.ID }; db.ManagerBuilding.Add(ObjManagerBuilding); await db.SaveChangesAsync(); } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } throw; } return RedirectToAction("ManagementBuilding", new { BuildingID=model2.BuildingID}); }
public ActionResult Create(CreateAccountModel account) { try { var userManager = new UserManager<Account>(new UserStore<Account>(DbContext)); var accountDb = userManager.FindByName(account.UserName); if (accountDb != null) { ModelState.AddModelError("UserName", "Tên tài khoản đã được sử dụng."); } accountDb = userManager.FindByEmail(account.Email); if (accountDb != null) { ModelState.AddModelError("Email", "Email đã được sử dụng."); } accountDb = DbContext.Accounts.FirstOrDefault(s => s.Profile.Identity == account.Identity); if (accountDb != null) { ModelState.AddModelError("Identity", "Mã số này đã được sử dụng."); } if (ModelState.IsValid) { Account newAccount = new Account() { UserName = account.UserName.Trim(), PhoneNumber = string.IsNullOrEmpty(account.PhoneNumber)? account.PhoneNumber:account.PhoneNumber.Trim(), Email = account.Email.Trim(), Profile = new UserProfile() { Identity = account.Identity.Trim(), LastName = account.LastName.Trim(), FirstName = account.FirstName.Trim(), Notes = account.Notes, BirthDate = account.BirthDate, Actived = account.Actived } }; var result = userManager.Create(newAccount, account.Password); if (result.Succeeded) { if (account.Role == "Admin") { userManager.AddToRole(newAccount.Id, "Admin"); userManager.AddToRole(newAccount.Id, "Teacher"); } else if (account.Role == "Teacher") { userManager.AddToRole(newAccount.Id, "Teacher"); } else { userManager.AddToRole(newAccount.Id, "Student"); } return Redirect(null); } ModelState.AddModelError("", "Đã có lỗi xảy ra. Vui lòng thử lại sau."); } } catch (Exception ex) { ModelState.AddModelError("", ex.Message); } InitFormData(account); ViewBag.IsEdit = false; return View(account); }
public void Seed(SiteDbContext context, int sampleSize) { // If users exist, return if (context.Users.Any()) return; // Wire up user services var userStore = new UserStore<ApplicationUser>(context); var userManager = new UserManager<ApplicationUser>(userStore); // Generate A Hashed password var hashedPassword = new PasswordHasher().HashPassword(DefaultPassword); // Create The administrator if (userManager.FindByEmail("[email protected]") == null) { // Populate the user object var user = CreateAdminUser("admin", "[email protected]", hashedPassword, EmployeeUtils.GetNewEmployeeId(context)); // Set the GUID for the admin user to prevent issues with Identity between refreshes user.Id = ConfigurationManager.AppSettings["AdminGuid"]; // Create the User userManager.Create(user, DefaultPassword); // Add the administrative role to the user userManager.AddToRole(user.Id, UserRoles.Administrator); } // If there is more then 1 user, return if (context.Users.Count() >= 2) return; // Create a random number generator var rand = new Random(); // Create some Dummy users with account create view models var hydrator = new Hydrator<AccountCreateViewModel>() .Ignoring(u => u.ReportsToId) .Ignoring(u => u.ReportsTo) .Ignoring(u => u.Suboridnates) .Ignoring(u => u.CreatedCustomers) .WithAmericanAddress(u => u.Address) .WithAmericanCity(u => u.City) .WithAmericanState(u => u.Region) .WithCustomGenerator(u => u.Country, new CountryGenerator()) .WithFirstName(u => u.FirstName) .WithLastName(u => u.LastName) .WithDate(u => u.HireDate, DateTime.Now.AddYears(-25), DateTime.Now) .WithDate(u => u.BirthDate, DateTime.Now.AddYears(-19), DateTime.Now.AddYears(50)) .WithAmericanPostalCode(u => u.PostalCode, 1) .GetList(sampleSize) .ToList(); // Map them to a Application User List var models = Mapper.Map<List<AccountCreateViewModel>, List<ApplicationUser>>(hydrator); // Fill in some missing fields and create the user models.ForEach(e => { e.Title = "Employee"; e.EmployeeId = EmployeeUtils.GetNewEmployeeId(context); e.UserName = (e.LastName + e.FirstName.First() + e.EmployeeId.Substring(3)).ToLower(); e.Email = $"{e.UserName}@{DomainName}"; e.PasswordHash = hashedPassword; // Title of salutation var values = Enum.GetValues(typeof(TitleOfCourtesyEnumeration)); e.TitleOfCourtesy = (TitleOfCourtesyEnumeration)values.GetValue(rand.Next(values.Length)); // All Seeded users report to admin e.ReportsToId = ConfigurationManager.AppSettings["AdminGuid"]; // Create the user userManager.Create(e, DefaultPassword); // Add the user to the user role userManager.AddToRole(e.Id, UserRoles.User); }); }
public ActionResult ForgotPassword(string email, RegisteredUser userRecovery) { var userStore = new UserStore<IdentityUser>(); UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore); var user = manager.FindByEmail(email); CreateTokenProvider(manager, PASSWORD_RESET); var code = manager.GeneratePasswordResetToken(user.Id); var callbackUrl = Url.Action("ResetPassword", "Accounts", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); var body = "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>"; MailHelper mailer = new MailHelper(); string response = mailer.EmailFromArvixe( new RegisteredUser(userRecovery.Email = email, userRecovery.Subject = "Password Recovery Email", userRecovery.Body = body)); return View("PasswordEmail"); }
public IHttpActionResult PostTravel(ShareDTO infos) { string username = infos.username; int travelId = infos.travelid; Travel trav = db.Travels.Find(travelId); UserStore<ApplicationUser> userStore = new UserStore<ApplicationUser>(db); UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(userStore); ApplicationUser user = userManager.FindByEmail(username); if(!trav.ApplicationUsers.Contains(user)) { if(user.Travels == null) { user.Travels = new List<Travel>(); } user.Travels.Add(trav); } db.SaveChanges(); TravelDTO dto = new TravelDTO(trav); return Ok(dto); }
public JsonResult GetRolesForAUser(string userName) { //userName = Request.Params["Email"]; if(string.IsNullOrWhiteSpace(userName)) return Json("userul nu a fost gasit/ nu are roluri: "+userName); var context = new ApplicationDbContext(); var userStore = new UserStore<ApplicationUser>(context); var userManager = new UserManager<ApplicationUser>(userStore); var roleStore = new RoleStore<IdentityRole>(context); var roleManager = new RoleManager<IdentityRole>(roleStore); var user = userManager.FindByEmail(userName); List<String> rolesName = (from role in roleManager.Roles select role.Name).ToList(); List<String> userNames = (from us in userManager.Users select us.Email).ToList(); if (user != null) { var userRolesIds = (from role in user.Roles select role.RoleId).ToList(); var userRoles = (from roleId in userRolesIds let role = roleManager.FindById(roleId) select role.Name).ToList(); return Json(userRoles); } else { return Json("userul nu a fost gasit/ nu are roluri"); } }
public ActionResult DeleteRoleFromUser(string userName, string roleName) { var context = new ApplicationDbContext(); var userStore = new UserStore<ApplicationUser>(context); var userManager = new UserManager<ApplicationUser>(userStore); var roleStore = new RoleStore<IdentityRole>(context); var roleManager = new RoleManager<IdentityRole>(roleStore); var user = userManager.FindByEmail(userName); if (user != null) { var role = roleManager.FindByName(roleName); if (role != null) { if (userManager.IsInRole(user.Id, role.Name)) { userManager.RemoveFromRole(user.Id, role.Name); context.SaveChanges(); } } } return RedirectToAction("RolesIndex", "Account"); }
private IdentityUser CreateIdentityObject(UserManager<IdentityUser, Guid> manager) { var user = ObjectHelpers.CreateIdentityUser("[email protected]"); var result = manager.Create(user); if (result.Succeeded) { return manager.FindByEmail(user.Email); } return null; }
public ActionResult OnOffAdministrator(int id) { var user = db.Users.Find(id); if (user != null) { //cuando siepre quiero buscar los usuarios en las tabla ASP.net: de roles y usuarios: var userContext = new ApplicationDbContext(); var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(userContext)); //Buscamos el role primero: var userASP = userManager.FindByEmail(user.userName); //Si es diferente de null podemos proceder con el role del ese usuario: if (userASP != null) { if (userManager.IsInRole(userASP.Id, "Admin")) { userManager.RemoveFromRole(userASP.Id, "Admin"); } else { userManager.AddToRole(userASP.Id, "Admin"); } } } return RedirectToAction("Index"); }
// GET: Users public ActionResult Index() { var userContext = new ApplicationDbContext(); var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(userContext)); var users = db.Users.ToList(); var usersView = new List<UserIndexView>(); //por cada usuario que hay en la coleccion users: foreach (var user in users) { var userASP = userManager.FindByEmail(user.userName); usersView.Add(new UserIndexView { Address = user.Address, Candidates = user.Candidates, FirstName = user.FirstName, Grade = user.Grade, Group = user.Group, GroupMembers = user.GroupMembers, IsAdmin = userASP != null && userManager.IsInRole(userASP.Id, "Admin"), LastName = user.LastName, Phone = user.Phone, Photo = user.Photo, UserId = user.UserId, userName = user.userName, }); } return View(usersView); }