public void OnModelPropertyValidated(object sender, OnPropertyValidatedEventArgs e)
        {
            // immediate throw
            // temporary solution due to multiple provision of the same model

            //if (!e.Result.IsValid)
            //{
            //    throw new ContainerValidationResultException
            //    {
            //        Args = e,
            //        Definition = e.Result.Tag as DefinitionBase
            //    };
            //}

            var existingModelResult = ModelValidations.FirstOrDefault(r => r.Model == e.Result.Tag);

            if (existingModelResult == null)
            {
                existingModelResult = new ModelValidationResult
                {
                    Model = e.Result.Tag as DefinitionBase
                };

                ModelValidations.Add(existingModelResult);
            }

            existingModelResult.Properties.Add(e.Result);
        }
Exemple #2
0
 public void ConfigureServices(IServiceCollection services)
 {
     Cors.AddCors(services);
     Identity.AddIdentity(services);
     Authentication.AddAuthentication(Configuration, services);
     Interfaces.AddInterfaces(services);
     ModelValidations.AddModelValidation(services);
     services.Configure <RazorViewEngineOptions>(options => options.ViewLocationExpanders.Add(new ViewLocationExpander()));
     services.AddAntiforgery(options => { options.Cookie.Name = "_af"; options.Cookie.HttpOnly = true; options.Cookie.SecurePolicy = CookieSecurePolicy.Always; options.HeaderName = "X-XSRF-TOKEN"; });
     services.AddAutoMapper(typeof(Startup));
     services.AddDbContext <AppDbContext>();
     services.AddScoped <ModelValidationAttribute>();
     services.AddControllersWithViews()
     .AddNewtonsoftJson(options => {
         options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
         options.SerializerSettings.NullValueHandling     = Newtonsoft.Json.NullValueHandling.Ignore;
     })
     .AddFluentValidation(options => options.RegisterValidatorsFromAssemblyContaining <Startup>());
     services.AddEmailSenders();
     services.Configure <CookiePolicyOptions>(options => { options.CheckConsentNeeded = _ => true; options.MinimumSameSitePolicy = SameSiteMode.None; });
     services.Configure <EmailSettings>(options => Configuration.GetSection("EmailSettings").Bind(options));
     services.Configure <TokenSettings>(options => Configuration.GetSection("TokenSettings").Bind(options));
     services.Configure <TestingEnvironment>(options => Configuration.GetSection("TestingEnvironment").Bind(options));
     services.Configure <DirectoryLocations>(options => Configuration.GetSection("DirectoryLocations").Bind(options));
 }
Exemple #3
0
 public ProductsController(ICategoriesRepository categoriesRepository, ICountriesRepository countriesRepository, IProductsRepository productsRepository, ModelValidations modelValidations, ImageUploader imageUploader)
 {
     _productsRepository   = productsRepository;
     _countriesRepository  = countriesRepository;
     _categoriesRepository = categoriesRepository;
     _modelValidations     = modelValidations;
     _imageUploader        = imageUploader;
 }
Exemple #4
0
        private void FillViewData(bool isMailing)
        {
            SelectList countries = new SelectList(_context.Country.OrderBy(a => a.EnglishName), "Code", "EnglishName");

            foreach (SelectListItem i in countries)
            {
                i.Text = ModelValidations.Capitilize(i.Text);
            }
            Input = new InputModel
            {
                CountryCode = null
            };
            ViewData["CountryCode"] = countries;
        }
        public void OnModelPropertyValidated(object sender, OnPropertyValidatedEventArgs e)
        {
            var existingModelResult = ModelValidations.FirstOrDefault(r => r.Model == e.Result.Tag);

            if (existingModelResult == null)
            {
                existingModelResult = new ModelValidationResult
                {
                    Model = e.Result.Tag as DefinitionBase
                };

                ModelValidations.Add(existingModelResult);
            }

            existingModelResult.Properties.Add(e.Result);
        }
Exemple #6
0
        private void FillViewData()
        {
            SelectList countries = new SelectList(_context.Country.OrderBy(a => a.EnglishName), "Code", "EnglishName");

            foreach (SelectListItem i in countries)
            {
                i.Text = ModelValidations.Capitilize(i.Text);
            }
            SelectList provinces = new SelectList(_context.Province.Where(a => a.CountryCode == Input.CountryCode).OrderBy(a => a.EnglishName), "Code", "EnglishName");

            foreach (SelectListItem i in provinces)
            {
                i.Text = ModelValidations.Capitilize(i.Text);
            }
            ViewData["Countries"] = countries;
            ViewData["Provinces"] = provinces;
        }
Exemple #7
0
 public CategoriesController(ICategoriesRepository categoriesRepository, ModelValidations modelValidations, ImageUploader imageUploader)
 {
     _categoriesRepository = categoriesRepository;
     _modelValidations     = modelValidations;
     _imageUploader        = imageUploader;
 }
Exemple #8
0
 public AuthController(IUsersRepository usersRepository, ModelValidations modelValidations, ImageUploader imageUploader)
 {
     _usersRepository  = usersRepository;
     _modelValidations = modelValidations;
     _imageUploader    = imageUploader;
 }
Exemple #9
0
        public async Task <IActionResult> OnPostAsync()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."));
            }
            //AddressMailingSelected
            if (String.IsNullOrWhiteSpace(Input.mailingSelected))
            {
                ModelState.AddModelError("Input.addressMailings", "Mailing Address is required.");
            }
            //AddressShippingSelected
            if (String.IsNullOrWhiteSpace(Input.shipppingSelected))
            {
                ModelState.AddModelError("Input.addressShippings", "Shipping Address is required.");
            }
            //creditCardNumber
            if (String.IsNullOrWhiteSpace(Input.creditCardNumber))
            {
                ModelState.AddModelError("Input.creditCardNumber", "Credit Card Number is required.");
            }
            else if (!ModelValidations.IsStringNumeric(Input.creditCardNumber))
            {
                ModelState.AddModelError("Input.creditCardNumber", "Credit Card Number is not numeric.");
            }
            else if (Input.creditCardNumber.Length != 16)
            {
                ModelState.AddModelError("Input.creditCardNumber", "Credit Card Number must be 16 digits.");
            }
            //securityCode
            if (String.IsNullOrWhiteSpace(Input.securityCode))
            {
                ModelState.AddModelError("Input.securityCode", "Security Code is required.");
            }
            else if (!ModelValidations.IsStringNumeric(Input.securityCode))
            {
                ModelState.AddModelError("Input.securityCode", "Security Code is not numeric.");
            }
            else if (Input.securityCode.Length != 3)
            {
                ModelState.AddModelError("Input.securityCode", "Security Code must be 3 digits.");
            }
            //month
            int monthRes = 13;

            if (String.IsNullOrWhiteSpace(Input.month))
            {
                ModelState.AddModelError("Input.month", "Month is required.");
            }
            else if (!int.TryParse(Input.month, out monthRes))
            {
                ModelState.AddModelError("Input.month", "Month is not a valid number.");
            }
            else if (Input.month.Length != 2)
            {
                ModelState.AddModelError("Input.month", "Month must be 2 digits. Ex. 03, 12");
            }
            else if (monthRes < 1 || monthRes > 12)
            {
                ModelState.AddModelError("Input.month", "Month is out of range, must be between 1-12.");
            }
            //year
            if (String.IsNullOrWhiteSpace(Input.year))
            {
                ModelState.AddModelError("Input.year", "Year is required.");
            }
            else if (!int.TryParse(Input.year, out int yearRes))
            {
                ModelState.AddModelError("Input.year", "Year is not a valid number.");
            }
            else if (Input.year.Length != 2)
            {
                ModelState.AddModelError("Input.year", "Year must be 2 digits.");
            }
            else if (yearRes == (DateTime.Now.Year - 2000))
            {
                if (monthRes < DateTime.Now.Month)
                {
                    ModelState.AddModelError("Input.year", "Date is in the past.");
                }
            }
            else if (yearRes < (DateTime.Now.Year - 2000) || yearRes > 99)
            {
                ModelState.AddModelError("Input.year", $"Year is out of range, must be between {String.Format("{0:00}", (DateTime.Now.Year - 2000))}-99.");
            }
            if (!ModelState.IsValid)
            {
                FillInputModel(user);
                return(Page());
            }
            //Add new order to db
            await AddGamesToAccount(Input.cartItems, user);

            TempData["successMessage"] = "Order succesfully placed!";
            return(RedirectToAction("Index", "Home"));
        }
Exemple #10
0
        public async Task <IActionResult> OnPostAsync()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."));
            }
            //Email
            if (!ModelValidations.ValidEmail(Input.Email))
            {
                ModelState.AddModelError("Input.Email", "Invalid Email. Ex. [email protected]");
            }
            //Phone Number
            if (!ModelValidations.ValidPhoneNumber(Input.PhoneNumber))
            {
                ModelState.AddModelError("Input.PhoneNumber", "Invalid Phone Number. Ex. 000-000-0000");
            }
            //Bio
            user.Bio = Input.Bio;
            if (String.IsNullOrEmpty(user.Bio))
            {
                user.Bio = "";
            }
            //First Name
            if (String.IsNullOrEmpty(Input.FirstName))
            {
                user.FirstName = "";
            }
            else if (Input.FirstName.Length > 25)
            {
                ModelState.AddModelError("Input.FirstName", "First Name must be less than 25 characters");
            }
            else
            {
                user.FirstName = Input.FirstName;
            }
            //Last Name
            if (String.IsNullOrEmpty(Input.LastName))
            {
                user.LastName = "";
            }
            else if (Input.LastName.Length > 25)
            {
                ModelState.AddModelError("Input.LastName", "Last Name must be less than 25 characters");
            }
            else
            {
                user.LastName = Input.LastName;
            }
            //City
            if (String.IsNullOrEmpty(Input.City))
            {
                user.City = "";
            }
            else if (Input.City.Length > 25)
            {
                ModelState.AddModelError("Input.City", "City must be less than 25 characters");
            }
            else
            {
                user.City = Input.City;
            }
            //Gender
            if (String.IsNullOrEmpty(Input.Gender))
            {
                user.Gender = "";
            }
            else if (Input.Gender.Length > 25)
            {
                ModelState.AddModelError("Input.Gender", "Gender must be less than 25 characters");
            }
            else
            {
                user.Gender = Input.Gender;
            }
            //GamerTag
            if (String.IsNullOrEmpty(Input.GamerTag))
            {
                user.GamerTag = "";
            }
            else if (Input.GamerTag.Length > 25)
            {
                ModelState.AddModelError("Input.GamerTag", "GamerTag must be less than 25 characters");
            }
            else
            {
                user.GamerTag = Input.GamerTag;
            }
            //Date of Birth
            if (Input.DateOfBirth > DateTime.Now)
            {
                ModelState.AddModelError("Input.DateOfBirth", "Date of Birth can not be past current date.");
            }
            else
            {
                user.DateOfBirth = Input.DateOfBirth;
            }
            //CountryCode
            bool hideStatusMessage = false;

            if (Input.CountryCode != user.CountryCode)
            {
                hideStatusMessage = true;
            }
            user.CountryCode = Input.CountryCode;
            //ProvinceCode
            if (!ValidCountry(Input.CountryCode))
            {
                user.ProvinceCode = null;
            }
            else
            {
                user.ProvinceCode = Input.ProvinceCode;
            }
            if (!ModelState.IsValid)
            {
                FillViewData();
                return(Page());
            }
            var email = await _userManager.GetEmailAsync(user);

            if (Input.Email != email)
            {
                var setEmailResult = await _userManager.SetEmailAsync(user, Input.Email);

                if (!setEmailResult.Succeeded)
                {
                    var userId = await _userManager.GetUserIdAsync(user);

                    throw new InvalidOperationException($"Unexpected error occurred setting email for user with ID '{userId}'.");
                }
            }

            var phoneNumber = await _userManager.GetPhoneNumberAsync(user);

            if (Input.PhoneNumber != phoneNumber)
            {
                var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, Input.PhoneNumber);

                if (!setPhoneResult.Succeeded)
                {
                    var userId = await _userManager.GetUserIdAsync(user);

                    throw new InvalidOperationException($"Unexpected error occurred setting phone number for user with ID '{userId}'.");
                }
            }

            var promotionalEmail = user.PromoEmailEnabled;

            if (Input.PromotionalEmail != promotionalEmail)
            {
                user.PromoEmailEnabled = Input.PromotionalEmail;
            }


            await _userManager.UpdateAsync(user);

            await _signInManager.RefreshSignInAsync(user);

            if (User.IsInRole("administrators"))
            {
                TempData["message"] = "Profile updated.";
            }
            if (!hideStatusMessage)
            {
                StatusMessage = "Your profile has been updated";
            }
            return(RedirectToPage());
        }
Exemple #11
0
        public async Task <IActionResult> OnPostAsync(bool isMailing)
        {
            _isMailing = isMailing;
            //Street
            if (String.IsNullOrEmpty(Input.Street))
            {
                ModelState.AddModelError("Input.Street", "Street is required.");
            }
            else if (Input.Street.Length > 20)
            {
                ModelState.AddModelError("Input.Street", "Street must be 20 or less characters");
            }
            else if (Input.Street.Length < 2)
            {
                ModelState.AddModelError("Input.Street", "Street must be 2 or more characters");
            }
            //Postal Code
            if (String.IsNullOrWhiteSpace(Input.PostalCode))
            {
                ModelState.AddModelError("Input.PostalCode", "Postal Code required.");
            }
            else if (!ModelValidations.PostalCodeValidation(Input.PostalCode))
            {
                ModelState.AddModelError("Input.PostalCode", "Invalid Postal Code. Ex. N2N2N2");
            }
            //City
            if (String.IsNullOrEmpty(Input.City))
            {
                ModelState.AddModelError("Input.City", "City is required.");
            }
            else if (Input.City.Length > 20)
            {
                ModelState.AddModelError("Input.City", "City must be 20 or less characters");
            }
            else if (Input.City.Length < 2)
            {
                ModelState.AddModelError("Input.City", "City must be 2 or more characters");
            }
            //Apartment Number
            if (!String.IsNullOrEmpty(Input.ApartmentNumber))
            {
                if (Input.ApartmentNumber.Length > 20)
                {
                    ModelState.AddModelError("Input.ApartmentNumber", "Apartment Number must be 20 or less characters");
                }
            }
            //First Name
            if (String.IsNullOrEmpty(Input.FirstName))
            {
                ModelState.AddModelError("Input.FirstName", "First Name is required.");
            }
            else if (Input.FirstName.Length > 20)
            {
                ModelState.AddModelError("Input.FirstName", "First Name must be 20 or less characters");
            }
            else if (Input.FirstName.Length < 2)
            {
                ModelState.AddModelError("Input.FirstName", "First Name must be 2 or more characters");
            }
            //Last Name
            if (String.IsNullOrEmpty(Input.LastName))
            {
                ModelState.AddModelError("Input.LastName", "LastName is required.");
            }
            else if (Input.LastName.Length > 20)
            {
                ModelState.AddModelError("Input.LastName", "LastName must be 20 or less characters");
            }
            else if (Input.LastName.Length < 2)
            {
                ModelState.AddModelError("Input.LastName", "LastName must be 2 or more characters");
            }
            if (!ModelState.IsValid)
            {
                FillViewData(isMailing);
                return(Page());
            }
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."));
            }
            if (_isMailing)
            {
                AddressMailing newAddress = new AddressMailing
                {
                    MailingId       = Guid.NewGuid(),
                    FirstName       = Input.FirstName,
                    LastName        = Input.LastName,
                    City            = Input.City,
                    ApartmentNumber = Input.ApartmentNumber,
                    PostalCode      = Input.PostalCode,
                    ProvinceCode    = null,
                    Street          = Input.Street,
                    CountryCode     = Input.CountryCode,
                    LastModified    = DateTime.Now,
                    Archived        = false,
                    UserId          = user.Id
                };
                if (!ValidCountry(Input.CountryCode))
                {
                    newAddress.ProvinceCode = null;
                }
                if (newAddress.ApartmentNumber == null)
                {
                    newAddress.ApartmentNumber = "";
                }
                _context.Add(newAddress);
                StatusMessage = "New Mailing Address added.";
            }
            else
            {
                AddressShipping newAddress = new AddressShipping
                {
                    ShippingId      = Guid.NewGuid(),
                    FirstName       = Input.FirstName,
                    LastName        = Input.LastName,
                    City            = Input.City,
                    ApartmentNumber = Input.ApartmentNumber,
                    PostalCode      = Input.PostalCode,
                    ProvinceCode    = null,
                    Street          = Input.Street,
                    CountryCode     = Input.CountryCode,
                    LastModified    = DateTime.Now,
                    Archived        = false,
                    UserId          = user.Id
                };
                if (!ValidCountry(Input.CountryCode))
                {
                    newAddress.ProvinceCode = null;
                }
                if (newAddress.ApartmentNumber == null)
                {
                    newAddress.ApartmentNumber = "";
                }
                _context.Add(newAddress);
                StatusMessage = "New Shipping Address added.";
            }
            await _context.SaveChangesAsync();

            return(RedirectToPage("Addresses"));
        }
Exemple #12
0
        public async Task <IActionResult> OnGet(bool isMailing, string id)
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."));
            }
            _isMailing = isMailing;
            if (_isMailing)
            {
                var address = _context.AddressMailing.Include(a => a.ProvinceCodeNavigation).Where(a => a.MailingId.ToString() == id).FirstOrDefault();
                if (address == null)
                {
                    StatusMessage = "Address not found.";
                    return(RedirectToPage("Addresses"));
                }
                if (address.UserId != user.Id)
                {
                    StatusMessage = "Unauthorized to delete this address.";
                    return(RedirectToPage("Addresses"));
                }
                Input = new InputModel
                {
                    Id              = address.MailingId.ToString(),
                    FirstName       = address.FirstName,
                    LastName        = address.LastName,
                    City            = address.City,
                    ApartmentNumber = address.ApartmentNumber,
                    PostalCode      = address.PostalCode,
                    Street          = address.Street,
                    CountryCode     = address.CountryCode
                };
                if (String.IsNullOrWhiteSpace(address.ApartmentNumber))
                {
                    Input.ApartmentNumber = "N/A";
                }
                if (!String.IsNullOrEmpty(address.ProvinceCode))
                {
                    Input.Province = ModelValidations.Capitilize(address.ProvinceCodeNavigation.EnglishName);
                }
                else
                {
                    Input.Province = "N/A";
                }
                Input.CountryCode = ModelValidations.Capitilize(_context.Country.Where(a => a.Code == address.CountryCode).FirstOrDefault().EnglishName);
            }
            else
            {
                var address = _context.AddressShipping.Include(a => a.ProvinceCodeNavigation).Where(a => a.ShippingId.ToString() == id).FirstOrDefault();
                if (address == null)
                {
                    StatusMessage = "Address not found.";
                    return(RedirectToPage("Addresses"));
                }
                if (address.UserId != user.Id)
                {
                    StatusMessage = "Unauthorized to delete this address.";
                    return(RedirectToPage("Addresses"));
                }
                Input = new InputModel
                {
                    Id              = address.ShippingId.ToString(),
                    FirstName       = address.FirstName,
                    LastName        = address.LastName,
                    City            = address.City,
                    ApartmentNumber = address.ApartmentNumber,
                    PostalCode      = address.PostalCode,
                    Street          = address.Street,
                    CountryCode     = address.CountryCode
                };
                if (String.IsNullOrWhiteSpace(address.ApartmentNumber))
                {
                    Input.ApartmentNumber = "N/A";
                }
                if (!String.IsNullOrWhiteSpace(address.ProvinceCode))
                {
                    Input.Province = ModelValidations.Capitilize(address.ProvinceCodeNavigation.EnglishName);
                }
                else
                {
                    Input.Province = "N/A";
                }
                Input.CountryCode = ModelValidations.Capitilize(_context.Country.Where(a => a.Code == address.CountryCode).FirstOrDefault().EnglishName);
            }
            return(Page());
        }
Exemple #13
0
        public async Task <IActionResult> OnGet(bool isMailing, string id)
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."));
            }
            _isMailing = isMailing;
            if (_isMailing)
            {
                var address = _context.AddressMailing.Where(a => a.MailingId.ToString() == id).FirstOrDefault();
                if (address == null)
                {
                    StatusMessage = "Address not found.";
                    return(RedirectToPage("Addresses"));
                }
                if (address.UserId != user.Id)
                {
                    StatusMessage = "Unauthorized to edit this address.";
                    return(RedirectToPage("Addresses"));
                }
                Input = new InputModel
                {
                    Id              = address.MailingId.ToString(),
                    FirstName       = address.FirstName,
                    LastName        = address.LastName,
                    City            = address.City,
                    ApartmentNumber = address.ApartmentNumber,
                    PostalCode      = address.PostalCode,
                    ProvinceCode    = address.ProvinceCode,
                    Street          = address.Street,
                    CountryCode     = address.CountryCode
                };
            }
            else
            {
                var address = _context.AddressShipping.Where(a => a.ShippingId.ToString() == id).FirstOrDefault();
                if (address == null)
                {
                    StatusMessage = "Address not found.";
                    return(RedirectToPage("Addresses"));
                }
                if (address.UserId != user.Id)
                {
                    StatusMessage = "Unauthorized to edit this address.";
                    return(RedirectToPage("Addresses"));
                }
                Input = new InputModel
                {
                    Id              = address.ShippingId.ToString(),
                    FirstName       = address.FirstName,
                    LastName        = address.LastName,
                    City            = address.City,
                    ApartmentNumber = address.ApartmentNumber,
                    PostalCode      = address.PostalCode,
                    ProvinceCode    = address.ProvinceCode,
                    Street          = address.Street,
                    CountryCode     = address.CountryCode
                };
            }
            SelectList countries = new SelectList(_context.Country.OrderBy(a => a.EnglishName), "Code", "EnglishName");

            foreach (SelectListItem i in countries)
            {
                i.Text = ModelValidations.Capitilize(i.Text);
            }
            SelectList provinces = new SelectList(_context.Province.Where(a => a.CountryCode == Input.CountryCode).OrderBy(a => a.EnglishName), "Code", "EnglishName");

            foreach (SelectListItem i in provinces)
            {
                i.Text = ModelValidations.Capitilize(i.Text);
            }
            ViewData["CountryCode"]  = countries;
            ViewData["ProvinceCode"] = provinces;
            return(Page());
        }
Exemple #14
0
 public CountriesController(ICountriesRepository countriesRepository, ModelValidations modelValidations)
 {
     _countriesRepository = countriesRepository;
     _modelValidations    = modelValidations;
 }
Exemple #15
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            //UserName
            if (String.IsNullOrEmpty(Input.UserName))
            {
                ModelState.AddModelError("Input.UserName", "User Name is required.");
            }
            else if (Input.UserName.Length > 25)
            {
                ModelState.AddModelError("Input.UserName", "User Name must be 25 or less characters");
            }
            else if (Input.UserName.Length < 3)
            {
                ModelState.AddModelError("Input.UserName", "User Name must be 3 or more characters");
            }
            //Email
            if (String.IsNullOrEmpty(Input.Email))
            {
                ModelState.AddModelError("Input.Email", "Email is required.");
            }
            else if (!ModelValidations.ValidEmail(Input.Email))
            {
                ModelState.AddModelError("Input.Email", "Invalid Email. Ex. [email protected]");
            }
            //Phone Number
            if (String.IsNullOrEmpty(Input.PhoneNumber))
            {
                ModelState.AddModelError("Input.PhoneNumber", "Phone Number is required.");
            }
            else if (!ModelValidations.ValidPhoneNumber(Input.PhoneNumber))
            {
                ModelState.AddModelError("Input.PhoneNumber", "Invalid Phone Number. Ex. 000-000-0000");
            }
            //Password
            if (String.IsNullOrEmpty(Input.Password))
            {
                ModelState.AddModelError("Input.Password", "Password is required.");
            }
            else if (Input.Password.Length > 100)
            {
                ModelState.AddModelError("Input.Password", "Password must be 100 or less characters");
            }
            else if (Input.Password.Length < 6)
            {
                ModelState.AddModelError("Input.Password", "Password must be 6 or more characters");
            }
            //Confirm Password
            if (Input.ConfirmPassword != Input.Password)
            {
                ModelState.AddModelError("Input.ConfirmPassword", "The password and confirmation password do not match.");
            }
            //GamerTag
            if (String.IsNullOrEmpty(Input.GamerTag))
            {
                ModelState.AddModelError("Input.GamerTag", "Gamer Tag is required.");
            }
            else if (Input.GamerTag.Length > 25)
            {
                ModelState.AddModelError("Input.GamerTag", "Gamer Tag must be 25 or less characters");
            }
            else if (Input.GamerTag.Length < 3)
            {
                ModelState.AddModelError("Input.GamerTag", "Gamer Tag must be 3 or more characters");
            }
            if (ModelState.IsValid)
            {
                var user = new User {
                    UserName          = Input.UserName,
                    Email             = Input.Email,
                    PhoneNumber       = Input.PhoneNumber,
                    GamerTag          = Input.GamerTag,
                    Bio               = "",
                    PromoEmailEnabled = Input.PromoEmailEnabled
                };
                if (user.GamerTag == null)
                {
                    user.GamerTag = "";
                }
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    result = await _userManager.AddToRoleAsync(user, "members");
                }
                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");
                    TempData["message"] = $"Account: {Input.UserName} created.";

                    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>.");

                    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());
        }
Exemple #16
0
        public static bool ResolveModelValidation(ModelNode modelNode, string start)
        {
            Trace.WriteLine(string.Format(""));

            var hasMissedOrInvalidProps = false;

            var model = modelNode.Value;

            Trace.WriteLine(string.Format("[INF] {2}MODEL CHECK [{0}] - ( {1} )", model.GetType(), model.ToString(), start));

            //if (model.RequireSelfProcessing || modelNode.Options.RequireSelfProcessing)
            if (modelNode.Options.RequireSelfProcessing)
            {
                var shouldProcessFlag = !modelNode.RegIsExcludedFromValidation();

                if (RegExcludedDefinitionTypes.Contains(modelNode.Value.GetType()))
                {
                    shouldProcessFlag = false;
                }

                if (shouldProcessFlag)
                {
                    var modelValidationResult = ModelValidations.FirstOrDefault(r => r.Model == model);

                    var shouldBeValidatedProperties = model.GetType()
                                                      .GetProperties()
                                                      .Where(
                        p =>
                        p.GetCustomAttributes <SPMeta2.Attributes.Regression.ExpectValidationAttribute>().Count() >
                        0)
                                                      .ToList();


                    if (modelValidationResult == null)
                    {
                        Trace.WriteLine(string.Format("[ERR]{2} Missing validation for model [{0}] - ( {1} )",
                                                      model.GetType(), model.ToString(), start));

                        hasMissedOrInvalidProps = true;
                        return(hasMissedOrInvalidProps);
                    }

                    foreach (
                        var property in
                        modelValidationResult.Properties.OrderBy(p => p.Src != null ? p.Src.Name : p.ToString()))
                    {
                        if ((!property.IsValid) ||
                            (property.IsValid && !ShowOnlyFalseResults))
                        {
                            Trace.WriteLine(
                                string.Format(
                                    "[INF]{6} [{4}] - Src prop: [{0}] Src value: [{1}] Dst prop: [{2}] Dst value: [{3}] Message:[{5}]",
                                    new object[]
                            {
                                property.Src != null ? property.Src.Name : string.Empty,
                                property.Src != null ? property.Src.Value : string.Empty,

                                property.Dst != null ? property.Dst.Name : string.Empty,
                                property.Dst != null ? property.Dst.Value : string.Empty,

                                property.IsValid,
                                property.Message,
                                start
                            }));
                        }

                        if (!property.IsValid)
                        {
                            hasMissedOrInvalidProps = true;
                        }
                    }

                    Trace.WriteLine(string.Format("[INF] {0}PROPERTY CHECK", start));

                    if (EnablePropertyValidation)
                    {
                        Trace.WriteLine(string.Format("[INF] {0}EnablePropertyValidation == true. Checking...", start));

                        foreach (var shouldBeValidatedProp in shouldBeValidatedProperties.OrderBy(p => p.Name))
                        {
                            var hasValidation    = false;
                            var validationResult =
                                modelValidationResult.Properties.FirstOrDefault(
                                    r => r.Src != null && r.Src.Name == shouldBeValidatedProp.Name);

                            // convert stuff
                            if (validationResult == null)
                            {
                                validationResult = modelValidationResult.Properties.FirstOrDefault(
                                    r => r.Src != null && r.Src.Name.Contains("." + shouldBeValidatedProp.Name + ")"));
                            }

                            // nullables
                            if (validationResult == null)
                            {
                                validationResult = modelValidationResult.Properties.FirstOrDefault(
                                    r => r.Src != null &&
                                    (r.Src.Name.Contains("System.Nullable`1") &&
                                     r.Src.Name.Contains(shouldBeValidatedProp.Name)));
                            }

                            if (validationResult != null)
                            {
                                hasValidation = true;
                            }
                            else
                            {
                                hasMissedOrInvalidProps = true;
                                hasValidation           = false;
                            }

                            if (hasValidation)
                            {
                                if (!ShowOnlyFalseResults)
                                {
                                    Trace.WriteLine(string.Format("[INF]{2} [{0}] - [{1}]",
                                                                  "VALIDATED",
                                                                  shouldBeValidatedProp.Name,
                                                                  start));
                                }
                            }
                            else
                            {
                                Trace.WriteLine(string.Format("[ERR]{2} [{0}] - [{1}]",
                                                              "MISSED",
                                                              shouldBeValidatedProp.Name,
                                                              start));
                            }
                        }
                    }
                    else
                    {
                        Trace.WriteLine(string.Format("[INF]{0}EnablePropertyValidation == false. Skipping...", start));
                    }
                }
                else
                {
                    Trace.WriteLine(string.Format("[INF]{0} Skipping due .RegIsExcludedFromValidation ==  TRUE", start));
                }
            }
            else
            {
                Trace.WriteLine(string.Format("[INF]{0} Skipping due RequireSelfProcessing ==  FALSE", start));
            }

            foreach (var childModel in modelNode.ChildModels)
            {
                var tmp = ResolveModelValidation(childModel, start + start);

                if (tmp == true)
                {
                    hasMissedOrInvalidProps = true;
                }
            }

            return(hasMissedOrInvalidProps);
        }