public IActionResult GetRoleKeys()
 {
     try
     {
         return(Ok(roleKeyMethods.GetRoleKeys().Select(k => new { Key = k.Key.ToString(), k.Value }).ToList()));
     }
     catch (ClientException ex)
     {
         return(BadRequest(new { message = ex.Message }));
     }
     catch (Exception ex)
     {
         return(StatusCode(500, new { message = ex.Message }));
     }
 }
Esempio n. 2
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            string roleKey = Input.RoleKey;

            if (string.IsNullOrWhiteSpace(roleKey))
            {
                ViewData["ErrorMessage"] = "role key is required";

                return(Page());
            }



            Dictionary <ApplicationUserRole, string> roleKeys = roleKeyMethods.GetRoleKeys();

            bool hasValue = roleKeyMethods.GetRoleKeys().ContainsValue(roleKey);

            ApplicationUserRole?role = hasValue ? roleKeys.First(k => k.Value == roleKey).Key : (ApplicationUserRole?)null;

            if (!role.HasValue)
            {
                ViewData["ErrorMessage"] = "your are not authorized to register";

                return(Page());
            }

            returnUrl = returnUrl ?? Url.Content("~/");

            if (ModelState.IsValid)
            {
                // Save today's date.
                var      today       = DateTime.Today;
                DateTime dateOfBirth = DateTime.Parse(Input.DateOfBirth);
                // Calculate the age.
                var age = today.Year - dateOfBirth.Year;

                if (age < 14)
                {
                    ViewData["ErrorMessage"] = "Age should be above 14 years old";
                    return(Page());
                }

                string password        = Input.Password;
                var    validator       = new PasswordValidator <ApplicationUser>();
                var    result_password = await validator.ValidateAsync(_userManager, null, password);

                if (!result_password.Succeeded)
                {
                    ViewData["ErrorMessage"] = "Password should be at least 6 characters and contain at least one upper-case and one digit";
                    return(Page());
                }

                if (_context.Users.Any(k => k.Email == Input.Email.ToLower()))
                {
                    ViewData["ErrorMessage"] = "Email already exist";
                    return(Page());
                }

                if (_context.Users.Any(k => k.UserName == Input.UserName.ToLower()))
                {
                    ViewData["ErrorMessage"] = "Username already exist";
                    return(Page());
                }

                var user = new ApplicationUser
                {
                    UserName           = Input.UserName.ToLower(),
                    NormalizedUserName = Input.UserName.ToUpper(),
                    Email           = Input.Email.ToLower(),
                    NormalizedEmail = Input.Email.ToUpper(),
                    EmailConfirmed  = false,
                    //CompanyID = Input.CompanyID,
                    //DepartmentID = Input.DepartmentID,
                    DateOfBirth      = dateOfBirth,
                    FirstName        = Input.FirstName,
                    LastName         = Input.LastName,
                    RoleCode         = (short)role.Value,
                    RoleAssignedDate = DateTime.Now
                };

                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    //_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 },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <br /> <a href=\"{HtmlEncoder.Default.Encode(callbackUrl)}\">clicking here</a>.");

                    ViewData["Message"] = "Thank you for registering! a confirmation link was sent to your email";

                    //await _signInManager.SignInAsync(user, isPersistent: false);

                    //var role = _context.Roles.FirstOrDefault(c => c.Name == "User");

                    //if (role != null)
                    //{
                    //    await _userManager.AddToRoleAsync(user, role.Name);
                    //}

                    //Using LocalRedirect ensures that the "return URL" is a route actually on your site,
                    //instead of some malicious third-party bad actor's.
                    return(Page());
                }

                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError("RegistrationError", error.Description);
                }
            }
            else
            {
                ViewData["ErrorMessage"] = "fill required fields";
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }