private async void AddRoles(MySchoolUser user) { if (!await RoleManager.RoleExistsAsync("Student")) { await RoleManager.CreateAsync(new IdentityRole("Student")); } if (!await RoleManager.RoleExistsAsync("Teacher")) { await RoleManager.CreateAsync(new IdentityRole("Teacher")); } if (!await RoleManager.RoleExistsAsync("Parent")) { await RoleManager.CreateAsync(new IdentityRole("Parent")); } if (!await RoleManager.RoleExistsAsync("Director")) { await RoleManager.CreateAsync(new IdentityRole("Director")); } if (Input.RegisterAs == "Student") { await _userManager.AddToRoleAsync(user, "Student"); } else if (Input.RegisterAs == "Teacher") { await _userManager.AddToRoleAsync(user, "Teacher"); } else if (Input.RegisterAs == "Parent") { await _userManager.AddToRoleAsync(user, "Parent"); } else if (Input.RegisterAs == "Director") { await _userManager.AddToRoleAsync(user, "Director"); } }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); if (ModelState.IsValid) { var user = new MySchoolUser { UserName = Input.UserName, Email = Input.Email }; var result = await _userManager.CreateAsync(user, Input.Password); AddRoles(user); if (result.Succeeded) { Context.SaveChanges(); _logger.LogInformation("User created a new account with password."); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { userId = user.Id, code = code }, protocol: Request.Scheme); await _emailSender.SendEmailAsync(Input.Email, "Confirm your email", $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); EmailSender emailSender = new EmailSender(Configuration); emailSender.Send(user.Email, "You successfully registered", callbackUrl); await _signInManager.SignInAsync(user, isPersistent : false); TempData["registered"] = "registered"; return(LocalRedirect(returnUrl)); } foreach (var error in result.Errors) { if (error.Code == "DuplicateEmail") { ModelState.AddModelError(error.Code, "Този имейл вече съществува."); } else if (error.Code == "DuplicateUserName") { ModelState.AddModelError(error.Code, "Това патребителско име вече съществува."); } } } // If we got this far, something failed, redisplay form return(Page()); }