public async Task <IActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid && !_context.Users.Any(x => x.UserName == model.Username)) { var user = new User { UserName = model.Username, Email = model.Username }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { var userInformation = new UserInformation { Role = UserRole.Candidate, UserId = user.Id, DayOfLastActivity = DateTime.Now, }; _context.UserInformation.Add(userInformation); _context.SaveChanges(); return(RedirectToAction("CandidateList", "CandidateManagement")); } } model.RegisterErrors(_context); return(View(model)); }
public async System.Threading.Tasks.Task <IActionResult> Register(Models.IdentityUser vm) { if (!ModelState.IsValid) { var user = new Microsoft.AspNetCore.Identity.IdentityUser { UserName = vm.Email, Email = vm.Email }; var result = await _userManager.CreateAsync(user, vm.Password); if (result.Succeeded) { await _signInManager.SignInAsync(user, false); return(RedirectToAction("Index", "Home")); } else { foreach (var error in result.Errors) { ModelState.AddModelError("", error.Description); } } } return(View(vm)); }
public async Task <IActionResult> Register(RegisterViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { var user = new IdentityUser { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713 // Send an email with this link //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); //await _emailSender.SendEmailAsync(model.Email, "Confirm your account", // $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>"); await _signInManager.SignInAsync(user, isPersistent : false); _logger.LogInformation(3, "User created a new account with password."); return(RedirectToLocal(returnUrl)); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null) { if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { return(View("ExternalLoginFailure")); } var user = new IdentityUser { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent : false); _logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider); return(RedirectToLocal(returnUrl)); } } AddErrors(result); } ViewData["ReturnUrl"] = returnUrl; return(View(model)); }
public async Task <IActionResult> Register(RegisterViewModel vm) { if (!ModelState.IsValid) { return(View(vm)); } var user = new IdentityUser { UserName = vm.Email, Email = vm.Email }; var result = await _userManager.CreateAsync(user, "password"); if (result.Succeeded) { await _signInManager.SignInAsync(user, false); return(RedirectToAction("Index", "Home")); } return(View()); }
public async Task <Microsoft.AspNetCore.Identity.IdentityUser> GetUserByIdAsync(string id) { QueryDefinition queryDefinition = new QueryDefinition("SELECT * FROM c WHERE c.id = \"" + id + "\""); FeedIterator <Mobsites.AspNetCore.Identity.Cosmos.IdentityUser> queryResultSetIterator = containerUsers.GetItemQueryIterator <Mobsites.AspNetCore.Identity.Cosmos.IdentityUser>(queryDefinition); Microsoft.AspNetCore.Identity.IdentityUser output = null; while (queryResultSetIterator.HasMoreResults) { FeedResponse <Mobsites.AspNetCore.Identity.Cosmos.IdentityUser> currentResultSet = await queryResultSetIterator.ReadNextAsync(); foreach (Microsoft.AspNetCore.Identity.IdentityUser user in currentResultSet) { output = user; } } if (output == null) { throw new Exception($"There is no user with id: {id}."); } return(output); }
public static async System.Threading.Tasks.Task EnsurePopulated(UserManager <IdentityUser> userManager) { Microsoft.AspNetCore.Identity.IdentityUser user = await userManager.FindByIdAsync(adminUser); if (user == null) { user = new Microsoft.AspNetCore.Identity.IdentityUser("Admin"); await userManager.CreateAsync(user, adminPassword); } }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); if (ModelState.IsValid) { // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, set lockoutOnFailure: true var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure : true); if (result.Succeeded) { Microsoft.AspNetCore.Identity.IdentityUser MANCIIU = await _signInManager.UserManager.FindByEmailAsync(Input.Email); // Create generic principal. IList <String> RolesList = await _signInManager.UserManager.GetRolesAsync(MANCIIU); System.Security.Claims.Claim claim = new System.Security.Claims.Claim("Role", "Admin"); User.Claims.Append(claim); GenericPrincipal genericPrincipal = new GenericPrincipal(User.Identity, RolesList.ToArray <string>()); System.Security.Claims.ClaimsPrincipal cp = new System.Security.Claims.ClaimsPrincipal(); this.HttpContext.User = genericPrincipal; _logger.LogInformation("User logged in."); return(LocalRedirect(returnUrl)); } if (result.RequiresTwoFactor) { return(RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe })); } if (result.IsLockedOut) { _logger.LogWarning("User account locked out."); return(RedirectToPage("./Lockout")); } else { ModelState.AddModelError(string.Empty, "Invalid login attempt."); return(Page()); } } // If we got this far, something failed, redisplay form return(Page()); }
public async Task <IdentityResult> Register([FromBody] RegisterModel model) { var user = await _userStore.FindByNameAsync(model.Email); if (user == null) { user = new IdentityUser { UserName = model.Email, Email = model.Email }; return(await _userManager.CreateAsync(user, model.Password)); } else { await _userManager.RemovePasswordAsync(user); return(await _userManager.AddPasswordAsync(user, model.Password)); } }
public async Task <IActionResult> Register(LoginViewModel loginViewModel) { if (ModelState.IsValid) { var user = new IdentityUser() { UserName = loginViewModel.UserName }; var result = await _userManager.CreateAsync(user, loginViewModel.Password); if (result.Succeeded) { return(RedirectToAction("Index", "Home")); } } ModelState.AddModelError("", "Password is not of the correct format!"); return(View(loginViewModel)); }
private void AddDefaultAdminIfDoesNotExists(UserManager <Microsoft.AspNetCore.Identity.IdentityUser> userManager) { var adminInDBQuery = userManager.FindByEmailAsync(Configuration.GetValue <string>("DefaultAdmin:Login", "*****@*****.**")); adminInDBQuery.Wait(); if (adminInDBQuery.Result == null) { var admin = new Microsoft.AspNetCore.Identity.IdentityUser(Configuration.GetValue <string>("DefaultAdmin:Login", "*****@*****.**")) { Email = Configuration.GetValue <string>("DefaultAdmin:Login", "*****@*****.**") }; var result = userManager.CreateAsync(admin, Configuration.GetValue <string>("DefaultAdmin:Password", "123456Abc!")); result.Wait(); userManager.AddToRoleAsync(admin, "Admin").Wait(); } }
public async Task <IActionResult> CreatePersonalTrainerView(CreatePersonalTrainerViewModel model, IdentityUser identityUser) { if (ModelState.IsValid) { Guid guid = Guid.NewGuid(); var hasher = new PasswordHasher <IdentityUser>(); var role = _context.Roles.Where(r => r.Name == "Personal Trainer").FirstOrDefault(); identityUser = new Microsoft.AspNetCore.Identity.IdentityUser { Id = guid.ToString(), Email = model.IdentityUser.Email, UserName = model.IdentityUser.Email, NormalizedEmail = model.IdentityUser.Email.ToUpper(), NormalizedUserName = model.IdentityUser.Email.ToUpper(), PasswordHash = hasher.HashPassword(null, model.IdentityUser.PasswordHash) }; PersonalTrainer personalTrainer = new PersonalTrainer { UserId = guid.ToString(), FirstName = model.PersonalTrainer.FirstName, LastName = model.PersonalTrainer.LastName }; IdentityUserRole <string> identityUserRole = new Microsoft.AspNetCore.Identity.IdentityUserRole <string> { UserId = guid.ToString(), RoleId = role.Id }; _context.Add(identityUserRole); _context.Add(identityUser); _context.Add(personalTrainer); await _context.SaveChangesAsync(); return(View("Home")); } ; ViewData["UserId"] = new SelectList(_context.PersonalTrainers, "Id", "Id", model.PersonalTrainer.UserId); return(View()); }
public async Task <IActionResult> Register(RegisterViewModel model, string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/Account/CheckYour"); if (ModelState.IsValid) { var user = new Microsoft.AspNetCore.Identity.IdentityUser { UserName = model.UserName, Email = model.Email, PhoneNumber = model.PhoneNumber }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { _logger.LogInformation("User created a new account with password."); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.Action( "ConfirmEmail", "Account", new { userId = user.Id, userEmail = user.Email, Code = code }, protocol: Request.Scheme); await _emailSender.SendEmailAsync(model.Email, "Verify Your Email Address", $"Thanks for signing up<br>" + $"Your account has been created,<br>" + $"You can login with the following credentials after you have activated your account by pressing the link below.<br>" + $"-------------------------------<br>" + $"User Name = " + user.UserName + " <br> " + $"E-Mail = " + user.Email + "<br> " + $"-------------------------------<br>" + $"Please click this link to activate your account:<br>" + $"<a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>Click Here</a>."); await _signInManager.SignInAsync(user, isPersistent : false); return(LocalRedirect(returnUrl)); } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } return(View(model)); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { using (var scope = app.ApplicationServices.CreateScope()) { var userMgr = scope.ServiceProvider.GetRequiredService <UserManager <IdentityUser> >(); var alice = userMgr.FindByNameAsync("alice").Result; if (alice == null) { alice = new IdentityUser { UserName = "******", Email = "*****@*****.**" }; var result = userMgr.CreateAsync(alice, "Pass123$").Result; if (!result.Succeeded) { throw new Exception(result.Errors.First().Description); } result = userMgr.AddClaimsAsync(alice, new Claim[] { new Claim(JwtClaimTypes.Name, "Alice Smith"), new Claim(JwtClaimTypes.GivenName, "Alice"), new Claim(JwtClaimTypes.FamilyName, "Smith"), new Claim(JwtClaimTypes.Email, "*****@*****.**"), new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean), new Claim(JwtClaimTypes.WebSite, "http://alice.com"), new Claim(JwtClaimTypes.Address, @"{ 'street_address': 'One Hacker Way', 'locality': 'Heidelberg', 'postal_code': 69118, 'country': 'Germany' }", IdentityServer4.IdentityServerConstants.ClaimValueTypes.Json) }).Result; if (!result.Succeeded) { throw new Exception(result.Errors.First().Description); } Console.WriteLine("alice created"); } else { Console.WriteLine("alice already exists"); } var bob = userMgr.FindByNameAsync("bob").Result; if (bob == null) { bob = new IdentityUser { UserName = "******", Email = "*****@*****.**" }; var result = userMgr.CreateAsync(bob, "Pass123$").Result; if (!result.Succeeded) { throw new Exception(result.Errors.First().Description); } result = userMgr.AddClaimsAsync(bob, new Claim[] { new Claim(JwtClaimTypes.Name, "Bob Smith"), new Claim(JwtClaimTypes.GivenName, "Bob"), new Claim(JwtClaimTypes.FamilyName, "Smith"), new Claim(JwtClaimTypes.Email, "*****@*****.**"), new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean), new Claim(JwtClaimTypes.WebSite, "http://bob.com"), new Claim(JwtClaimTypes.Address, @"{ 'street_address': 'One Hacker Way', 'locality': 'Heidelberg', 'postal_code': 69118, 'country': 'Germany' }", IdentityServer4.IdentityServerConstants.ClaimValueTypes.Json), new Claim("location", "somewhere") }).Result; if (!result.Succeeded) { throw new Exception(result.Errors.First().Description); } Console.WriteLine("bob created"); } } if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } //app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); //app.UseAuthentication(); app.UseIdentityServer(); app.UseMvcWithDefaultRoute(); }
public async Task <Microsoft.AspNetCore.Identity.IdentityUser> UpdateUserAsync(Microsoft.AspNetCore.Identity.IdentityUser user) { var responce = await containerUsers.ReplaceItemAsync(user, user.Id, new PartitionKey((user as Mobsites.AspNetCore.Identity.Cosmos.IdentityUser).PartitionKey)); return(responce.Resource); }
public async Task <Microsoft.AspNetCore.Identity.IdentityUser> RemoveUserFromRoleAsync(Microsoft.AspNetCore.Identity.IdentityUser user, string roleName) { Microsoft.AspNetCore.Identity.IdentityRole role = await GetRoleByNameAsync(roleName); IdentityUserRole identityUserRole = await GetIdentityUserRoleAsync(user as Mobsites.AspNetCore.Identity.Cosmos.IdentityUser, role as Mobsites.AspNetCore.Identity.Cosmos.IdentityRole); await DeleteIdentityUserRoleAsync(identityUserRole); List <string> roles = (user as Mobsites.AspNetCore.Identity.Cosmos.IdentityUser).FlattenRoleNames.Split(',').Where(r => !string.IsNullOrEmpty(r) && r != role.Name).ToList(); (user as Mobsites.AspNetCore.Identity.Cosmos.IdentityUser).FlattenRoleNames = string.Join(',', roles); List <string> roleIds = (user as Mobsites.AspNetCore.Identity.Cosmos.IdentityUser).FlattenRoleIds.Split(',').Where(r => !string.IsNullOrEmpty(r) && r != role.Id).ToList(); (user as Mobsites.AspNetCore.Identity.Cosmos.IdentityUser).FlattenRoleIds = string.Join(',', roleIds); user = await UpdateUserAsync(user); return(user); }