// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #nullable disable using System.ComponentModel.DataAnnotations; using System.Text; using System.Text.Encodings.Web; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.WebUtilities; using ODCWeb.DataAccess.Data; using ODCWeb.Models; using ODCWeb.Utility; namespace ODCWeb.Areas.Identity.Pages.Account { public class RegisterModel : PageModel { private readonly SignInManager _signInManager; private readonly UserManager _userManager; private readonly IUserStore _userStore; private readonly IUserEmailStore _emailStore; private readonly ILogger _logger; private readonly IEmailSender _emailSender; private readonly ApplicationDbContext _db; private readonly RoleManager _roleManager; public RegisterModel( UserManager userManager, IUserStore userStore, SignInManager signInManager, ILogger logger, RoleManager roleManager, IEmailSender emailSender, ApplicationDbContext applicationDbContext) { _userManager = userManager; _userStore = userStore; _emailStore = GetEmailStore(); _signInManager = signInManager; _logger = logger; _emailSender = emailSender; _roleManager = roleManager; _db = applicationDbContext; } /// /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// [BindProperty] public InputModel Input { get; set; } /// /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// public string ReturnUrl { get; set; } /// /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// public IList ExternalLogins { get; set; } /// /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// public class InputModel { /// /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } /// /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } /// /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } [Required] [Display(Name="Name")] public string Name { get; set; } [Required] [Display(Name = "City")] public string City { get; set; } /* public string? Role { get; set; } [ValidateNever] public IEnumerable RoleList { get; set; }*/ } public async Task OnGetAsync(string returnUrl = null) { /*if (!_roleManager.RoleExistsAsync(SD.Role_Customer).GetAwaiter().GetResult()) { _roleManager.CreateAsync(new IdentityRole(SD.Role_Customer)).GetAwaiter().GetResult(); _roleManager.CreateAsync(new IdentityRole(SD.Role_Admin)).GetAwaiter().GetResult(); _roleManager.CreateAsync(new IdentityRole(SD.Role_Employee)).GetAwaiter().GetResult(); }*/ Input = new() { /*RoleList = _roleManager.Roles.Select(x => x.Name).Select(i => new SelectListItem { Text = i, Value = i })*/ }; ReturnUrl = returnUrl; ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); } public async Task OnPostAsync(string returnUrl = null) { returnUrl ??= Url.Content("~/"); ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); if (ModelState.IsValid) { var user = CreateUser(); await _userStore.SetUserNameAsync(user, Input.Email, CancellationToken.None); await _emailStore.SetEmailAsync(user, Input.Email, CancellationToken.None); user.City = Input.City; user.Name = Input.Name; if (Input.Password == "" && Input.Email == "") { user.RoleName = SD.Role_Admin; user.Approved = true; } else if (Input.Password == "" && Input.Email == "") { user.RoleName = SD.Role_Admin; user.Approved = true; } else { user.RoleName = SD.Role_Customer; user.Approved = false; } /////////////////roles checking//////// Task hasAdminRole = _roleManager.RoleExistsAsync("Admin"); hasAdminRole.Wait(); Task roleResult; if (!hasAdminRole.Result) { roleResult = _roleManager.CreateAsync(new IdentityRole("Admin")); roleResult.Wait(); } /////////////////////////// Task hasCustomerRole = _roleManager.RoleExistsAsync("Customer"); hasAdminRole.Wait(); Task roleCResult; if (!hasCustomerRole.Result) { roleCResult = _roleManager.CreateAsync(new IdentityRole("Customer")); roleCResult.Wait(); } /////////////////////////// Task hasEmployeeRole = _roleManager.RoleExistsAsync("Employee"); hasAdminRole.Wait(); Task roleEResult; if (!hasEmployeeRole.Result) { roleEResult = _roleManager.CreateAsync(new IdentityRole("Employee")); roleEResult.Wait(); } /////////////////////////////////////// user.RoleId = _roleManager.Roles.FirstOrDefault(c => c.Name == user.RoleName).Id; user.SubscriptionStatus = true; user.ExpiryDate = DateTime.Today.AddDays(30); user.SubscriptionDaysLeft = ((int)(user.ExpiryDate - DateTime.Today).TotalDays); /*foreach (ApplicationUser person in _userManager.Users) { person.ExpiryDate = DateTime.Today.AddDays(30); person.SubscriptionDaysLeft = ((int)(person.ExpiryDate - DateTime.Today).TotalDays); }*/ var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { _logger.LogInformation("User created a new account with password."); if (Input.Password == "Odlan@895" && Input.Email == "odlandevelopment@gmail.com") { await _userManager.AddToRoleAsync(user, SD.Role_Admin); } else if (Input.Password == "Odlan@895" && Input.Email == "zeeshan17junezeeshi@gmail.com") { await _userManager.AddToRoleAsync(user, SD.Role_Admin); } else { await _userManager.AddToRoleAsync(user, SD.Role_Customer); } var userId = await _userManager.GetUserIdAsync(user); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = userId, code = code, returnUrl = returnUrl }, protocol: Request.Scheme); await _emailSender.SendEmailAsync(Input.Email, "Confirm your email", $"Please confirm your account by clicking here."); if (_userManager.Options.SignIn.RequireConfirmedAccount) { return RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }); } else { await _signInManager.SignInAsync(user, isPersistent: false); return LocalRedirect(returnUrl); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return Page(); } private ApplicationUser CreateUser() { try { return Activator.CreateInstance(); } catch { throw new InvalidOperationException($"Can't create an instance of '{nameof(IdentityUser)}'. " + $"Ensure that '{nameof(ApplicationUser)}' is not an abstract class and has a parameterless constructor, or alternatively " + $"override the register page in /Areas/Identity/Pages/Account/Register.cshtml"); } } private IUserEmailStore GetEmailStore() { if (!_userManager.SupportsUserEmail) { throw new NotSupportedException("The default UI requires a user store with email support."); } return (IUserEmailStore)_userStore; } } }