// GET: Home public async Task<ActionResult> Index() { var context = new ApplicationDbContext(); // DefaultConnection var store = new UserStore<CustomUser>(context); var manager = new UserManager<CustomUser>(store); var email = "[email protected]"; var password = "Passw0rd"; var user = await manager.FindByEmailAsync(email); if (user == null) { user = new CustomUser { UserName = email, Email = email, FirstName = "Super", LastName = "Admin" }; await manager.CreateAsync(user, password); } else { user.FirstName = "Super"; user.LastName = "Admin"; await manager.UpdateAsync(user); } return Content("Hello, Index"); }
// GET: Home public async Task<ActionResult> Index() { var context = new ApplicationDbContext(); // DefaultConnection var store = new UserStore<CustomUser>(context); var manager = new UserManager<CustomUser>(store); var signInManager = new SignInManager<CustomUser, string>(manager, HttpContext.GetOwinContext().Authentication); var email = "[email protected]"; var password = "Passw0rd"; var user = await manager.FindByEmailAsync(email); if (user == null) { user = new CustomUser { UserName = email, Email = email, FirstName = "Super", LastName = "Admin" }; await manager.CreateAsync(user, password); } else { var result = await signInManager.PasswordSignInAsync(user.UserName, password, true, false); if (result == SignInStatus.Success) { return Content("Hello, " + user.FirstName + " " + user.LastName); } //user.FirstName = "Super"; //user.LastName = "Admin"; //await manager.UpdateAsync(user); } return Content("Hello, Index"); }
public async Task SetupAsync() { _evnt = new EventViewModel { Title = "Title event", Description = "Test event", Start = "11:00", End = "14:27", Date = "2016-02-01" }; var userViewModel = new LoginViewModel { Email = "[email protected]", Password = "useruser", RememberMe = false }; var context = new DataContext(); var manager = new UserManager(new UserStore(context)); var user = await manager.FindAsync(userViewModel.Email, userViewModel.Password); if (user == null) { await manager.CreateAsync(new User { Email = userViewModel.Email, UserName = userViewModel.Email }, userViewModel.Password); } _calendarController = new CalendarController(context); var mockCp = new Mock<IClaimsPrincipal>(); if (user != null) mockCp.SetupGet(cp => cp.UserId).Returns(user.Id); _calendarController.CurrentUser = mockCp.Object; var mockAuthenticationManager = new Mock<IAuthenticationManager>(); mockAuthenticationManager.Setup(am => am.SignOut()); mockAuthenticationManager.Setup(am => am.SignIn()); _calendarController.AuthenticationManager = mockAuthenticationManager.Object; }
public async Task<ActionResult> Default(RegisterViewModel model) { var context = new MyDbContext(); var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); // The default Validators that the UserManager uses are UserValidator and MinimumLengthValidator // You can tweak some of the settings as follows // This example sets the Password length to be 3 characters UserManager.UserValidator = new UserValidator<ApplicationUser>(UserManager) { AllowOnlyAlphanumericUserNames = false }; UserManager.PasswordValidator = new MinimumLengthValidator(3); if (ModelState.IsValid) { var user = new ApplicationUser() { UserName = model.UserName }; user.HomeTown = model.HomeTown; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { var authManager = HttpContext.GetOwinContext().Authentication; var claimsIdentity = UserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); authManager.SignIn(claimsIdentity); return RedirectToAction("Index", "Home"); } else { foreach (var error in result.Errors) { ModelState.AddModelError("", error); } } } // If we got this far, something failed, redisplay form return View(model); }
public async Task<ActionResult> Create(DoctorViewModel DoctorViewModel) { if (ModelState.IsValid) { var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); var user = new ApplicationUser() { UserName = DoctorViewModel.Email }; var result = await UserManager.CreateAsync(user, DoctorViewModel.Password); string roleName = "Doctor"; IdentityResult roleResult; if (!RoleManager.RoleExists(roleName)) { roleResult = RoleManager.Create(new IdentityRole(roleName)); } try { var findUser = UserManager.FindByName(DoctorViewModel.Email); UserManager.AddToRole(findUser.Id, "Doctor"); context.SaveChanges(); } catch { throw; } Doctor_Detail doctor = MapDoctor(DoctorViewModel); db.Doctor_Details.Add(doctor); await db.SaveChangesAsync(); return RedirectToAction("Index"); } return View(DoctorViewModel); }
public static async void ConfigureUsers(IEnumerable<InMemoryUser> users, EntityFrameworkServiceOptions options, UserManager userManager) { using(var db = new Contexto(options.ConnectionString)) { if(!db.Users.Any()) { foreach(var u in users) { var entity = new Usuario { Email = u.Claims.First(x=>x.Type==Constants.ClaimTypes.Email).Value , UserName = u.Username }; var response = await userManager.CreateAsync(entity, u.Password); if(!response.Succeeded) { throw new Exception("Não foi possÃvel criar o usuario" + u.Username + response.Errors.ToString()); } else { var user = await userManager.FindAsync(u.Username,u.Password); foreach(var c in u.Claims) { await userManager.AddClaimAsync(user.Id,c); } await userManager.UpdateAsync(user); } } db.SaveChanges(); } } }
public async Task Add_Should_Add_New_Login_Just_After_UserManager_CreateAsync_Get_Called() { const string userName = "Tugberk"; const string loginProvider = "Twitter"; const string providerKey = "12345678"; using (IDocumentStore store = CreateEmbeddableStore()) { using (IAsyncDocumentSession ses = store.OpenAsyncSession()) { ses.Advanced.UseOptimisticConcurrency = true; RavenUserStore<RavenUser> userStore = new RavenUserStore<RavenUser>(ses); UserManager<RavenUser> userManager = new UserManager<RavenUser>(userStore); RavenUser user = new RavenUser(userName); UserLoginInfo loginToAdd = new UserLoginInfo(loginProvider, providerKey); await userManager.CreateAsync(user); await userManager.AddLoginAsync(user.Id, loginToAdd); await ses.SaveChangesAsync(); } using (IAsyncDocumentSession ses = store.OpenAsyncSession()) { ses.Advanced.UseOptimisticConcurrency = true; IUserLoginStore<RavenUser, string> userLoginStore = new RavenUserStore<RavenUser>(ses); RavenUser user = await ses.LoadAsync<RavenUser>(RavenUser.GenerateKey(userName)); RavenUserLogin foundLogin = await ses.LoadAsync<RavenUserLogin>(RavenUserLogin.GenerateKey(loginProvider, providerKey)); // Assert Assert.Equal(1, user.Logins.Count()); Assert.NotNull(foundLogin); } } }
public async Task GetUserClaimTest() { var db = UnitTestHelper.CreateDefaultDb(); var manager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db)); var user = new IdentityUser("u1"); var result = await manager.CreateAsync(user); UnitTestHelper.IsSuccess(result); Assert.NotNull(user); var claims = new[] { new Claim("c1", "v1"), new Claim("c2", "v2"), new Claim("c3", "v3") }; foreach (Claim c in claims) { UnitTestHelper.IsSuccess(await manager.AddClaimAsync(user.Id, c)); } var userClaims = new List<Claim>(await manager.GetClaimsAsync(user.Id)); Assert.Equal(3, userClaims.Count); foreach (Claim c in claims) { Assert.True(userClaims.Exists(u => u.Type == c.Type && u.Value == c.Value)); } }
protected void btnRegistrar_Click(object sender, EventArgs e) { var manager = new UserManager(); var user = new ApplicationUser(); user.UserName = txtUserName.Text; user.Direccion = txtDireccion.Text; manager.CreateAsync(user); }
public async Task AddLoginNullLoginFailsTest() { var db = UnitTestHelper.CreateDefaultDb(); var manager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db)); var user = new IdentityUser("Hao"); UnitTestHelper.IsSuccess(await manager.CreateAsync(user)); ExceptionHelper.ThrowsArgumentNull(() => AsyncHelper.RunSync(() => manager.AddLoginAsync(user.Id, null)), "login"); }
public async Task AddDuplicateLoginFailsTest() { var db = UnitTestHelper.CreateDefaultDb(); var mgr = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db)); var user = new IdentityUser("dupeLogintest"); UnitTestHelper.IsSuccess(await mgr.CreateAsync(user)); var userLogin1 = new UserLoginInfo("provider1", "p1-1"); UnitTestHelper.IsSuccess(await mgr.AddLoginAsync(user.Id, userLogin1)); UnitTestHelper.IsFailure(await mgr.AddLoginAsync(user.Id, userLogin1)); }
public static async Task<IdentityResult> CreateUser(PlatformUser user, string password) { var userManager = new UserManager<PlatformUser>( new UserStore<PlatformUser>(new PlatformUserIdentityDbContext())); //Allows for use of email address as username: userManager.UserValidator = new UserValidator<PlatformUser>(userManager) { AllowOnlyAlphanumericUserNames = false }; var idResult = await userManager.CreateAsync(user, password); return idResult; }
public void WhenCeateUserAsync() { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_session)); var user = new ApplicationUser() { UserName = "RealUserName" }; using (var transaction = new TransactionScope()) { var result = userManager.CreateAsync(user, "RealPassword"); transaction.Complete(); Assert.IsNull(result.Exception); } var actual = _session.Query<ApplicationUser>().FirstOrDefault(x => x.UserName == user.UserName); Assert.IsNotNull(actual); Assert.AreEqual(user.UserName, actual.UserName); }
/// <summary> /// Invoked after the LTI request has been authenticated so the application can sign in the application user. /// </summary> /// <param name="context">Contains information about the login session as well as the LTI request.</param> /// <param name="claims">Optional set of claims to add to the identity.</param> /// <returns>A <see cref="Task"/> representing the completed operation.</returns> public static async Task OnAuthenticated(LtiAuthenticatedContext context, IEnumerable<Claim> claims = null) { // Find existing pairing between LTI user and application user var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new LtiDb())); var loginProvider = string.Join(":", new[] { context.Options.AuthenticationType, context.LtiRequest.ConsumerKey }); var providerKey = context.LtiRequest.UserId; var login = new UserLoginInfo(loginProvider, providerKey); var user = await userManager.FindAsync(login); if (user == null) { var usernameContext = new LtiGenerateUserNameContext(context.OwinContext, context.LtiRequest); await context.Options.Provider.GenerateUserName(usernameContext); if (string.IsNullOrEmpty(usernameContext.UserName)) { return; } user = await userManager.FindByNameAsync(usernameContext.UserName); if (user == null) { user = new ApplicationUser { UserName = usernameContext.UserName }; var result = await userManager.CreateAsync(user); if (!result.Succeeded) { return; } } // Save the pairing between LTI user and application user await userManager.AddLoginAsync(user.Id, login); } // Create the application identity, add the LTI request as a claim, and sign in var identity = await userManager.CreateIdentityAsync(user, context.Options.SignInAsAuthenticationType); identity.AddClaim(new Claim(context.Options.ClaimType, JsonConvert.SerializeObject(context.LtiRequest, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }), ClaimValueTypes.String, context.Options.AuthenticationType)); if (claims != null) { foreach (var claim in claims) { identity.AddClaim(claim); } } context.OwinContext.Authentication.SignIn(new AuthenticationProperties { IsPersistent = false }, identity); // Redirect to original URL so the new identity takes affect context.RedirectUrl = context.LtiRequest.Url.ToString(); }
private static async System.Threading.Tasks.Task CreateUserIfNotExist(UserManager<ApplicationUser> userManager, string email, string password, string role, string loginProvider = null, string providerKey = null) { var user = await userManager.FindByEmailAsync(email); if (user == null) { user = new ApplicationUser { UserName = email, Email = email }; var result = await userManager.CreateAsync(user, password); if (!result.Succeeded) { throw new ApplicationException(string.Join("\n", result.Errors.Select(a => a.Description).ToArray())); } await userManager.AddToRoleAsync(user, role); if (loginProvider != null && providerKey != null) { await userManager.AddLoginAsync(user, new UserLoginInfo(loginProvider, providerKey, "")); } } }
private static void AddAppointments(SMDbContext context, UserManager<ApplicationUser> userManager) { var esth = context.Estheticians.Single(x => x.Id == 1); var services = context.SpaServices.Take(3).ToList(); var clientUser = new ApplicationUser { UserName = "[email protected]", Email = "[email protected]", FirstName = "Claire", LastName = "Smith", PhoneNumber = "5625551212" }; Task.FromResult(userManager.CreateAsync(clientUser, "client11").Result); var client = new Client { ApplicationUserId = userManager.FindByEmailAsync("[email protected]").Result.Id, AppointmentRemindersViaText = true, Appointments = new List<Appointment>() }; context.Clients.Add(client); context.SaveChanges(); var appt = new Appointment { ClientId = client.Id, FirstName = clientUser.FirstName, LastName = clientUser.LastName, Email = clientUser.Email, PhoneNumber = clientUser.PhoneNumber, Services = services, Esthetician = esth, StartTime = DateTime.Parse("10/21/2016 17:15"), LocationId = 1, EndTime = DateTime.Parse("10/21/2016 18:30"), RemindViaEmail = client.AppointmentRemindersViaEmail, RemindViaText = client.AppointmentRemindersViaText, Gender = Gender.Male }; context.Appointments.Add(appt); context.SaveChanges(); }
public async Task<ActionResult> Create(PatientViewModel PatientViewModel) { if (ModelState.IsValid) { var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); var user = new ApplicationUser() { UserName = PatientViewModel.Email }; var result = await UserManager.CreateAsync(user, PatientViewModel.Password); string roleName = "Patient"; IdentityResult roleResult; if (!RoleManager.RoleExists(roleName)) { roleResult = RoleManager.Create(new IdentityRole(roleName)); } try { var findUser = UserManager.FindByName(PatientViewModel.Email); UserManager.AddToRole(findUser.Id, "Patient"); context.SaveChanges(); } catch { throw; } var patient = new Patient_Detail(); patient.address = PatientViewModel.address; patient.cellno = PatientViewModel.cellno; patient.first_name = PatientViewModel.first_name; patient.med_aid_dep_no = PatientViewModel.med_aid_dep_no; patient.med_aid_no = PatientViewModel.med_aid_no; patient.post_code = PatientViewModel.post_code; patient.surname = PatientViewModel.surname; patient.telno = PatientViewModel.telno; db.Patient_Details.Add(patient); await db.SaveChangesAsync(); return RedirectToAction("Index"); } return View(PatientViewModel); }
public async Task<WikiDownUser> Save(IPrincipal principal, UserManager<WikiDownUser> userManager) { var user = await userManager.FindByNameAsync(this.UserName); var roles = this.GetRoles(principal, user); if (user != null) { if (user.UserName == principal.Identity.Name) { var userAccessLevel = ArticleAccessHelper.GetAccessLevel(user.Roles); if (userAccessLevel < ArticleAccessLevel.Admin) { throw new HttpResponseException(HttpStatusCode.BadRequest); } } user.SetRoles(roles); user.SetDisplayName(this.DisplayName); user.SetEmail(this.Email); if (!string.IsNullOrWhiteSpace(this.Password)) { await userManager.RemovePasswordAsync(user.Id); await userManager.AddPasswordAsync(user.Id, this.Password); } await userManager.UpdateAsync(user); WikiDownUserCacheHelper.Clear(user.UserName); } else { user = new WikiDownUser(this.UserName) { Roles = roles }; user.SetDisplayName(this.DisplayName); user.SetEmail(this.Email); await userManager.CreateAsync(user, this.Password); } return user; }
private static async Task<ApplicationUser> CreateUserIfNotExist(UserManager<ApplicationUser> userManager, ApplicationUser user, string password, string role, string loginProvider = null, string providerKey = null) { //Debugger.Launch(); user.EmailConfirmed = true; user.Email = user.Email ?? user.UserName; if (await userManager.FindByEmailAsync(user.Email) == null) { var result = await userManager.CreateAsync(user, password); if (!result.Succeeded) { throw new ApplicationException(string.Join("\n", result.Errors.Select(a => a.Description).ToArray())); } await userManager.AddToRoleAsync(user, role); if (loginProvider != null && providerKey != null) { await userManager.AddLoginAsync(user, new UserLoginInfo(loginProvider, providerKey, "")); } } return user; }
private async void Seed() { const string roleName = "administrator"; const string userName = "[email protected]"; var userContext = new ApplicationDbContext(); var roleStore = new RoleStore<IdentityRole>(userContext); var roleManager = new RoleManager<IdentityRole>(roleStore); if (roleManager.RoleExists(roleName)) return; await roleManager.CreateAsync(new IdentityRole(roleName)); var userStore = new UserStore<ApplicationUser>(userContext); var userManager = new UserManager<ApplicationUser>(userStore); var admin = new ApplicationUser() {UserName = userName}; await userManager.CreateAsync(admin, "Koekoek!IsNummer1"); await userManager.AddToRoleAsync(admin.Id, roleName); var pandContext = new ExclimmoContext(); pandContext.SeedPanden(); }
public async Task ClaimsIdentityTest() { var db = UnitTestHelper.CreateDefaultDb(); var manager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db)); var role = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db)); var user = new IdentityUser("Hao"); UnitTestHelper.IsSuccess(await manager.CreateAsync(user)); UnitTestHelper.IsSuccess(await role.CreateAsync(new IdentityRole("Admin"))); UnitTestHelper.IsSuccess(await role.CreateAsync(new IdentityRole("Local"))); UnitTestHelper.IsSuccess(await manager.AddToRoleAsync(user.Id, "Admin")); UnitTestHelper.IsSuccess(await manager.AddToRoleAsync(user.Id, "Local")); Claim[] userClaims = { new Claim("Whatever", "Value"), new Claim("Whatever2", "Value2") }; foreach (var c in userClaims) { UnitTestHelper.IsSuccess(await manager.AddClaimAsync(user.Id, c)); } var identity = await manager.CreateIdentityAsync(user, "test"); var claimsFactory = manager.ClaimsIdentityFactory as ClaimsIdentityFactory<IdentityUser, string>; Assert.NotNull(claimsFactory); var claims = identity.Claims; Assert.NotNull(claims); Assert.True( claims.Any(c => c.Type == claimsFactory.UserNameClaimType && c.Value == user.UserName)); Assert.True(claims.Any(c => c.Type == claimsFactory.UserIdClaimType && c.Value == user.Id)); Assert.True(claims.Any(c => c.Type == claimsFactory.RoleClaimType && c.Value == "Admin")); Assert.True(claims.Any(c => c.Type == claimsFactory.RoleClaimType && c.Value == "Local")); Assert.True( claims.Any( c => c.Type == ClaimsIdentityFactory<IdentityUser>.IdentityProviderClaimType && c.Value == ClaimsIdentityFactory<IdentityUser>.DefaultIdentityProviderClaimValue)); foreach (var cl in userClaims) { Assert.True(claims.Any(c => c.Type == cl.Type && c.Value == cl.Value)); } }
public async Task<ActionResult> Create(NurseViewModel NurseViewModel) { if (ModelState.IsValid) { var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); var user = new ApplicationUser() { UserName = NurseViewModel.Email }; var result = await UserManager.CreateAsync(user, NurseViewModel.Password); string roleName = "Nurse"; IdentityResult roleResult; if (!RoleManager.RoleExists(roleName)) { roleResult = RoleManager.Create(new IdentityRole(roleName)); } try { var findUser = UserManager.FindByName(NurseViewModel.Email); UserManager.AddToRole(findUser.Id, "Nurse"); context.SaveChanges(); } catch { throw; } var nurse = new Nurse_Detail(); nurse.address = NurseViewModel.address; nurse.cellno = NurseViewModel.cellno; nurse.first_name = NurseViewModel.first_name; nurse.med_practice_no = NurseViewModel.med_practice_no; nurse.post_code = NurseViewModel.post_code; nurse.surname = NurseViewModel.surname; nurse.telno = NurseViewModel.telno; db.Nurse_Details.Add(nurse); await db.SaveChangesAsync(); return RedirectToAction("Index"); } return View(NurseViewModel); }
public async Task LinkUnlinkDeletesTest() { var db = UnitTestHelper.CreateDefaultDb(); var mgr = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db)); var user = new IdentityUser("linkunlinktest"); UnitTestHelper.IsSuccess(await mgr.CreateAsync(user)); var userLogin1 = new UserLoginInfo("provider1", "p1-1"); var userLogin2 = new UserLoginInfo("provider2", "p2-1"); Assert.Equal(0, (await mgr.GetLoginsAsync(user.Id)).Count); UnitTestHelper.IsSuccess(await mgr.AddLoginAsync(user.Id, userLogin1)); Assert.Equal(1, user.Logins.Count(l => l.ProviderKey == "p1-1")); Assert.Equal(1, (await mgr.GetLoginsAsync(user.Id)).Count); UnitTestHelper.IsSuccess(await mgr.AddLoginAsync(user.Id, userLogin2)); Assert.Equal(1, user.Logins.Count(l => l.ProviderKey == "p2-1")); Assert.Equal(2, (await mgr.GetLoginsAsync(user.Id)).Count); UnitTestHelper.IsSuccess(await mgr.RemoveLoginAsync(user.Id, userLogin1)); Assert.Equal(0, user.Logins.Count(l => l.ProviderKey == "p1-1")); Assert.Equal(1, user.Logins.Count(l => l.ProviderKey == "p2-1")); Assert.Equal(1, (await mgr.GetLoginsAsync(user.Id)).Count()); UnitTestHelper.IsSuccess(await mgr.RemoveLoginAsync(user.Id, userLogin2)); Assert.Equal(0, (await mgr.GetLoginsAsync(user.Id)).Count); Assert.Equal(0, db.Set<IdentityUserLogin>().Count()); }
// GET: Home public async Task<ActionResult> Index() { var context = new IdentityDbContext<IdentityUser>(); // DefaultConnection var store = new UserStore<IdentityUser>(context); var manager = new UserManager<IdentityUser>(store); var email = "[email protected]"; var password = "Passw0rd"; var user = await manager.FindByEmailAsync(email); if (user == null) { user = new IdentityUser { UserName = email, Email = email }; await manager.CreateAsync(user, password); } return Content("Hello, Index"); }
public async Task<ActionResult> Register(RegisterViewModel model) { var dbmgtm = new ApplicationDbContext(); IdentityResult result; using (var securitytrans = dbmgtm.Database.BeginTransaction()) { try { if (ModelState.IsValid) { var user = new ApplicationUser() { UserName = model.UserName, FirstName = model.FirstName, LastName = model.LastName, Email = model.Email }; var um = new UserManager<ApplicationUser>( new UserStore<ApplicationUser>(dbmgtm)); result = await um.CreateAsync(user, model.Password); if (result.Succeeded) { UserPreference userpref = new UserPreference() { UserID = user.Id, UserName = model.UserName, SchoolRefID = model.SchoolID, AcademicYearRefID = model.AcademicYearID }; dbmgtm.UserPreferences.Add(userpref); await dbmgtm.SaveChangesAsync(); securitytrans.Commit(); //await SignInAsync(user, isPersistent: false); return RedirectToAction("Index", "Account"); } } } catch (Exception e) { securitytrans.Rollback(); ModelState.AddModelError("", e.Message); ViewBag.SchoolID = new SelectList(dbmgtm.Schools.AsNoTracking().Select(x => new { x.SchoolID, x.SchoolName }), "SchoolID", "SchoolName", model.SchoolID); ViewBag.AcademicYearID = new SelectList(dbmgtm.AcademicYears.AsNoTracking().Select(x => new { x.AcademicYearID, x.DisplayYear }), "AcademicYearID", "DisplayYear", model.AcademicYearID); return View(model); } } ViewBag.SchoolID = new SelectList(dbmgtm.Schools.AsNoTracking().Select(x => new { x.SchoolID, x.SchoolName }), "SchoolID", "SchoolName", model.SchoolID); ViewBag.AcademicYearID = new SelectList(dbmgtm.AcademicYears.AsNoTracking().Select(x => new { x.AcademicYearID, x.DisplayYear }), "AcademicYearID", "DisplayYear", model.AcademicYearID); return View(model); }
public void LoginTest() { var userManager = new UserManager<ApplicationUser>(new TestUserStore()); AccountController controller = new AccountController(userService, userProfileService, goalService, updateService, commentService, followRequestService, followUserService, securityTokenService, userManager); var mockAuthenticationManager = new Mock<IAuthenticationManager>(); mockAuthenticationManager.Setup(am => am.SignOut()); mockAuthenticationManager.Setup(am => am.SignIn()); controller.AuthenticationManager = mockAuthenticationManager.Object; ApplicationUser user=new ApplicationUser() { UserName="adarsh" }; userManager.CreateAsync(user, "123456"); var result = controller.Login(new LoginViewModel { Email = "adarsh", Password = "123456", RememberMe = false }, "abcd").Result; Assert.IsNotNull(result); var addedUser = userManager.FindByName("adarsh"); Assert.IsNotNull(addedUser); Assert.AreEqual("adarsh", addedUser.UserName); }
public async Task DupeUserClaimTest() { var db = UnitTestHelper.CreateDefaultDb(); var manager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db)); var user = new IdentityUser("u1"); var result = await manager.CreateAsync(user); Assert.NotNull(user); var claims = new[] { new Claim("c1", "v1"), new Claim("c2", "v2"), new Claim("c3", "v3") }; foreach (Claim c in claims) { // Add dupes UnitTestHelper.IsSuccess(await manager.AddClaimAsync(user.Id, c)); UnitTestHelper.IsSuccess(await manager.AddClaimAsync(user.Id, c)); } var userClaims = new List<Claim>(await manager.GetClaimsAsync(user.Id)); Assert.Equal(6, userClaims.Count); var currentExpected = 6; foreach (Claim c in claims) { Assert.True(userClaims.Exists(u => u.Type == c.Type && u.Value == c.Value)); UnitTestHelper.IsSuccess(await manager.RemoveClaimAsync(user.Id, c)); var cs = await manager.GetClaimsAsync(user.Id); currentExpected -= 2; Assert.Equal(currentExpected, cs.Count()); Assert.Equal(currentExpected, db.Set<IdentityUserClaim>().Count()); } }
public async Task<ActionResult> Customize(RegisterViewModel model) { var context = new MyDbContext(); var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); // The default Validators that the UserManager uses are UserValidator and MinimumLengthValidator // If you want to have complete control over validation then you can write your own validators. UserManager.UserValidator = new MyUserValidation(); UserManager.PasswordValidator = new MyPasswordValidation(); UserManager.PasswordHasher = new PasswordHasher(); if (ModelState.IsValid) { var user = new ApplicationUser() { UserName = model.UserName }; user.HomeTown = model.HomeTown; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { var authManager = HttpContext.GetOwinContext().Authentication; var claimsIdentity = UserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); authManager.SignIn(claimsIdentity); return RedirectToAction("Index", "Home"); } else { foreach (var error in result.Errors) { ModelState.AddModelError("", error); } } } // If we got this far, something failed, redisplay form return View("Index",model); }
private async static void InitializeUserAdmin(ApplicationDbContext context, UserManager<ApplicationUser> userManager) { ApplicationUser admin = new ApplicationUser { UserName = "[email protected]", Email = "[email protected]", DateOfBirth = new DateTime(1990, 1, 1), EmailConfirmed = true }; Thread.Sleep(2000); await userManager.CreateAsync(admin, "[email protected]"); //password must match constraints of 6 char min, case-change, min 1 number and non-letter character Thread.Sleep(2000); await userManager.AddToRoleAsync(admin, "admin"); context.SaveChanges(); }
public async Task SetupAsync() { _userViewModel = new LoginViewModel { Email = "[email protected]", Password = "useruser", RememberMe = false }; var context = new DataContext(); _manager = new UserManager(new UserStore(context)); _controller = new AccountController(_manager); var user = await _manager.FindAsync(_userViewModel.Email, _userViewModel.Password); if (user == null) { await _manager.CreateAsync(new User { Email = _userViewModel.Email, UserName = _userViewModel.Email }, _userViewModel.Password); } var mockCp = new Mock<IClaimsPrincipal>(); if (user != null) mockCp.SetupGet(cp => cp.UserId).Returns(user.Id); _controller.CurrentUser = mockCp.Object; var mockAuthenticationManager = new Mock<IAuthenticationManager>(); mockAuthenticationManager.Setup(am => am.SignOut()); mockAuthenticationManager.Setup(am => am.SignIn()); _controller.AuthenticationManager = mockAuthenticationManager.Object; }