public async Task <IActionResult> AuthorizationCode(AuthorizationCodeViewModel viewmodel) { if (!AuthUser.Identity.IsAuthenticated) { // not logged in, redirect to login page return(RedirectToRoute(new { area = string.Empty, controller = "SignIn", ReturnUrl = "/MissionControl" })); } if (ModelState.IsValid) { string sanitized = _codeSanitizer.Sanitize(viewmodel.AuthorizationCode, 255); try { string role = await _userService.ActivateAuthorizationCode(sanitized); if (!string.IsNullOrEmpty(role)) { var auth = await _authenticationService .RevalidateUserAsync(GetId(ClaimType.UserId)); auth.AuthenticationMessage = $"Code applied, you are now a member of the role: <strong>{role}</strong>."; await LoginUserAsync(auth); return(RedirectToRoute(new { area = "MissionControl", controller = "Home", action = "Index" })); } else { ShowAlertDanger("Invalid code. This request was logged."); } } catch (GraException gex) { ShowAlertDanger("Unable to activate code: ", gex); } } var site = await GetCurrentSiteAsync(); string siteLogoUrl = site.SiteLogoUrl ?? Url.Content(Defaults.SiteLogoPath); return(View(new AuthorizationCodeViewModel { SiteLogoUrl = siteLogoUrl })); }
public async Task <IActionResult> AuthorizationCode(AuthorizationCodeViewModel viewmodel) { if (!AuthUser.Identity.IsAuthenticated) { return(RedirectToSignIn()); } if (ModelState.IsValid) { string sanitized = _codeSanitizer.Sanitize(viewmodel.AuthorizationCode, 255); try { string role = await _userService.ActivateAuthorizationCode(sanitized); if (!string.IsNullOrEmpty(role)) { var auth = await _authenticationService .RevalidateUserAsync(GetId(ClaimType.UserId)); // TODO globalize auth.Message = $"Code applied, you are a member of the role: {role}."; await LoginUserAsync(auth); return(RedirectToRoute(new { area = "MissionControl", controller = "Home", action = "Index" })); } else { ShowAlertDanger("Invalid code. This request was logged."); } } catch (GraException gex) { ShowAlertDanger("Unable to activate code: ", gex); } } return(View()); }
public async Task <IActionResult> Index(SinglePageViewModel model) { var site = await GetCurrentSiteAsync(); if (!site.SinglePageSignUp) { return(RedirectToAction("Step1")); } if (site.RequirePostalCode && string.IsNullOrWhiteSpace(model.PostalCode)) { ModelState.AddModelError("PostalCode", "The Zip Code field is required."); } var askIfFirstTime = await GetSiteSettingBoolAsync(SiteSettingKey.Users.AskIfFirstTime); if (!askIfFirstTime) { ModelState.Remove(nameof(model.IsFirstTime)); } model.AskEmailReminder = GetSiteStage() == SiteStage.RegistrationOpen && await GetSiteSettingBoolAsync(SiteSettingKey.Users.AskPreregistrationReminder); if (model.AskEmailReminder && model.PreregistrationReminderRequested && string.IsNullOrWhiteSpace(model.Email)) { ModelState.AddModelError(nameof(model.Email), "Please enter an email address to send the reminder to."); } var(askActivityGoal, defaultDailyGoal) = await GetSiteSettingIntAsync( SiteSettingKey.Users.DefaultDailyPersonalGoal); bool askAge = false; bool askSchool = false; if (model.ProgramId.HasValue) { var program = await _siteService.GetProgramByIdAsync(model.ProgramId.Value); askAge = program.AskAge; askSchool = program.AskSchool; if (program.AgeRequired && !model.Age.HasValue) { ModelState.AddModelError("Age", "The Age field is required."); } if (program.SchoolRequired && !model.SchoolId.HasValue && !model.SchoolNotListed && !model.IsHomeschooled) { ModelState.AddModelError("SchoolId", "The School field is required."); } } if (ModelState.IsValid) { if (!askAge) { model.Age = null; } if (!askSchool) { model.SchoolId = null; model.SchoolNotListed = false; model.IsHomeschooled = false; } else if (model.IsHomeschooled) { model.SchoolId = null; model.SchoolNotListed = false; } else if (model.SchoolNotListed) { model.SchoolId = null; } User user = _mapper.Map <User>(model); user.SiteId = site.Id; if (askIfFirstTime) { user.IsFirstTime = model.IsFirstTime.Equals(DropDownTrueValue, System.StringComparison.OrdinalIgnoreCase); } if (!model.AskEmailReminder) { user.PreregistrationReminderRequested = false; } if (askActivityGoal && user.DailyPersonalGoal > 0) { if (user.DailyPersonalGoal > Defaults.MaxDailyActivityGoal) { user.DailyPersonalGoal = Defaults.MaxDailyActivityGoal; } } else { user.DailyPersonalGoal = null; } try { bool useAuthCode = false; string sanitized = null; if (!string.IsNullOrWhiteSpace(model.AuthorizationCode)) { sanitized = _codeSanitizer.Sanitize(model.AuthorizationCode, 255); useAuthCode = await _userService.ValidateAuthorizationCode(sanitized); if (useAuthCode == false) { _logger.LogError($"Invalid auth code used on join: {model.AuthorizationCode}"); } } await _userService.RegisterUserAsync(user, model.Password, allowDuringCloseProgram : useAuthCode); var loginAttempt = await _authenticationService .AuthenticateUserAsync(user.Username, model.Password, useAuthCode); await LoginUserAsync(loginAttempt); if (useAuthCode) { string role = await _userService.ActivateAuthorizationCode(sanitized, loginAttempt.User.Id); if (!string.IsNullOrEmpty(role)) { var auth = await _authenticationService .RevalidateUserAsync(loginAttempt.User.Id); auth.AuthenticationMessage = $"Code applied, you are a member of the role: <strong>{role}</strong>."; await LoginUserAsync(auth); } } await _mailService.SendUserBroadcastsAsync(loginAttempt.User.Id, false, true, true); var questionnaireId = await _questionnaireService .GetRequiredQuestionnaire(loginAttempt.User.Id, loginAttempt.User.Age); if (questionnaireId.HasValue) { HttpContext.Session.SetInt32(SessionKey.PendingQuestionnaire, questionnaireId.Value); } return(RedirectToAction("Index", "Home")); } catch (GraException gex) { ShowAlertDanger("Could not create your account: ", gex); if (gex.Message.Contains("password")) { ModelState.AddModelError("Password", "Please correct the issues with your password."); } } } PageTitle = $"{site.Name} - Join Now!"; if (model.SystemId.HasValue) { var branchList = await _siteService.GetBranches(model.SystemId.Value); if (model.BranchId < 1) { branchList = branchList.Prepend(new Branch() { Id = -1 }); } model.BranchList = new SelectList(branchList.ToList(), "Id", "Name"); } var systemList = await _siteService.GetSystemList(); var programList = await _siteService.GetProgramList(); var programViewObject = _mapper.Map <List <ProgramViewModel> >(programList); model.SystemList = new SelectList(systemList.ToList(), "Id", "Name"); model.ProgramList = new SelectList(programList.ToList(), "Id", "Name"); model.ProgramJson = Newtonsoft.Json.JsonConvert.SerializeObject(programViewObject); model.RequirePostalCode = site.RequirePostalCode; model.ShowAge = askAge; model.ShowSchool = askSchool; model.CategorySelectionAction = nameof(SchoolCategory); var districtList = await _schoolService.GetDistrictsAsync(true); if (model.PrivateSelected) { model.PublicSelected = false; model.CharterSelected = false; model.IsHomeschooled = false; model.SchoolDistrictList = new SelectList(districtList.ToList(), "Id", "Name"); model.SchoolList = new SelectList( await _schoolService.GetPrivateSchoolListAsync(), "Id", "Name"); } else if (model.CharterSelected) { model.PublicSelected = false; model.PrivateSelected = false; model.IsHomeschooled = false; model.SchoolDistrictList = new SelectList(districtList.ToList(), "Id", "Name"); model.SchoolList = new SelectList( await _schoolService.GetCharterSchoolListAsync(), "Id", "Name"); } else if (model.IsHomeschooled) { model.PublicSelected = false; model.PrivateSelected = false; model.CharterSelected = false; model.SchoolDistrictList = new SelectList(districtList.ToList(), "Id", "Name"); } else { model.PublicSelected = true; model.PrivateSelected = false; model.CharterSelected = false; model.IsHomeschooled = false; if (model.SchoolId.HasValue) { var schoolDetails = await _schoolService.GetSchoolDetailsAsync(model.SchoolId.Value); var typeList = await _schoolService.GetTypesAsync(schoolDetails.SchoolDistrictId); model.SchoolDistrictList = new SelectList(districtList.ToList(), "Id", "Name", schoolDetails.SchoolDistrictId); model.SchoolTypeList = new SelectList(typeList.ToList(), "Id", "Name", schoolDetails.SchoolTypeId); model.SchoolList = new SelectList(schoolDetails.Schools.ToList(), "Id", "Name"); ModelState.Remove(nameof(model.SchoolTypeId)); } else { model.SchoolDistrictList = new SelectList(districtList.ToList(), "Id", "Name"); if (model.SchoolDistrictId.HasValue) { var typeList = await _schoolService.GetTypesAsync(model.SchoolDistrictId); model.SchoolTypeList = new SelectList(typeList.ToList(), "Id", "Name", model.SchoolTypeId); var schoolList = await _schoolService.GetSchoolsAsync(model.SchoolDistrictId, model.SchoolTypeId); model.SchoolList = new SelectList(schoolList.ToList(), "Id", "Name"); } } } if (askIfFirstTime) { model.AskFirstTime = EmptyNoYes(); } if (askActivityGoal) { var pointTranslation = programList.First().PointTranslation; model.TranslationDescriptionPastTense = pointTranslation.TranslationDescriptionPastTense.Replace("{0}", "").Trim(); model.ActivityDescriptionPlural = pointTranslation.ActivityDescriptionPlural; } return(View(model)); }
public async Task <IActionResult> Index(SinglePageViewModel model) { var site = await GetCurrentSiteAsync(); if (!site.SinglePageSignUp) { return(RedirectToAction(nameof(Step1))); } if (site.RequirePostalCode && string.IsNullOrWhiteSpace(model.PostalCode)) { ModelState.AddModelError(nameof(model.PostalCode), _sharedLocalizer[ErrorMessages.Field, _sharedLocalizer[DisplayNames.ZipCode]]); } var askIfFirstTime = await GetSiteSettingBoolAsync(SiteSettingKey.Users.AskIfFirstTime); if (!askIfFirstTime) { ModelState.Remove(nameof(model.IsFirstTime)); } var(askEmailSubscription, askEmailSubscriptionText) = await GetSiteSettingStringAsync( SiteSettingKey.Users.AskEmailSubPermission); if (!askEmailSubscription) { ModelState.Remove(nameof(model.EmailSubscriptionRequested)); } else { var subscriptionRequested = model.EmailSubscriptionRequested.Equals( DropDownTrueValue, StringComparison.OrdinalIgnoreCase); if (subscriptionRequested && string.IsNullOrWhiteSpace(model.Email)) { ModelState.AddModelError(nameof(model.Email), " "); ModelState.AddModelError(nameof(model.EmailSubscriptionRequested), _sharedLocalizer[Annotations.Required.EmailForSubscription]); } } var(askActivityGoal, defaultDailyGoal) = await GetSiteSettingIntAsync( SiteSettingKey.Users.DefaultDailyPersonalGoal); bool askAge = false; bool askSchool = false; if (model.ProgramId.HasValue) { var program = await _siteService.GetProgramByIdAsync(model.ProgramId.Value); askAge = program.AskAge; askSchool = program.AskSchool; if (program.AgeRequired && !model.Age.HasValue) { ModelState.AddModelError(DisplayNames.Age, _sharedLocalizer[ErrorMessages.Field, _sharedLocalizer[DisplayNames.Age]]); } if (program.SchoolRequired && !model.SchoolId.HasValue && !model.SchoolNotListed && !model.IsHomeschooled) { ModelState.AddModelError(nameof(model.SchoolId), _sharedLocalizer[ErrorMessages.Field, _sharedLocalizer[DisplayNames.School]]); } } if (ModelState.IsValid) { if (!askAge) { model.Age = null; } if (!askSchool) { model.SchoolId = null; model.SchoolNotListed = false; model.IsHomeschooled = false; } else if (model.IsHomeschooled) { model.SchoolId = null; model.SchoolNotListed = false; } else if (model.SchoolNotListed) { model.SchoolId = null; } User user = _mapper.Map <User>(model); user.SiteId = site.Id; if (askIfFirstTime) { user.IsFirstTime = model.IsFirstTime.Equals(DropDownTrueValue, StringComparison.OrdinalIgnoreCase); } if (askEmailSubscription) { user.IsEmailSubscribed = model.EmailSubscriptionRequested.Equals( DropDownTrueValue, StringComparison.OrdinalIgnoreCase); } if (askActivityGoal && user.DailyPersonalGoal > 0) { if (user.DailyPersonalGoal > Defaults.MaxDailyActivityGoal) { user.DailyPersonalGoal = Defaults.MaxDailyActivityGoal; } } else { user.DailyPersonalGoal = null; } try { bool useAuthCode = false; string sanitized = null; if (!string.IsNullOrWhiteSpace(model.AuthorizationCode)) { sanitized = _codeSanitizer.Sanitize(model.AuthorizationCode, 255); useAuthCode = await _authorizationCodeService .ValidateAuthorizationCode(sanitized); if (!useAuthCode) { _logger.LogError($"Invalid auth code used on join: {model.AuthorizationCode}"); } } await _userService.RegisterUserAsync(user, model.Password, allowDuringCloseProgram : useAuthCode); var loginAttempt = await _authenticationService .AuthenticateUserAsync(user.Username, model.Password, useAuthCode); await LoginUserAsync(loginAttempt); if (useAuthCode) { string role = await _userService.ActivateAuthorizationCode(sanitized, loginAttempt.User.Id); if (!string.IsNullOrEmpty(role)) { var auth = await _authenticationService .RevalidateUserAsync(loginAttempt.User.Id); auth.Message = $"Code applied, you are a member of the role: {role}."; await LoginUserAsync(auth); } } await _mailService.SendUserBroadcastsAsync(loginAttempt.User.Id, false, true, true); var questionnaireId = await _questionnaireService .GetRequiredQuestionnaire(loginAttempt.User.Id, loginAttempt.User.Age); if (questionnaireId.HasValue) { HttpContext.Session.SetInt32(SessionKey.PendingQuestionnaire, questionnaireId.Value); } if (!TempData.ContainsKey(TempDataKey.UserJoined)) { TempData.Add(TempDataKey.UserJoined, true); } return(RedirectToAction(nameof(HomeController.Index), HomeController.Name)); } catch (GraException gex) { ShowAlertDanger(_sharedLocalizer[Annotations.Validate.CouldNotCreate, _sharedLocalizer[gex.Message]]); if (gex.GetType() == typeof(GraPasswordValidationException)) { ModelState.AddModelError(nameof(model.Password), _sharedLocalizer[Annotations.Validate.PasswordIssue]); } } } PageTitle = _sharedLocalizer[Annotations.Title.JoinNow, site.Name]; if (model.SystemId.HasValue) { var branchList = await _siteService.GetBranches(model.SystemId.Value); if (model.BranchId < 1) { branchList = branchList.Prepend(new Branch() { Id = -1 }); } model.BranchList = NameIdSelectList(branchList.ToList()); } var systemList = await _siteService.GetSystemList(); var programList = await _siteService.GetProgramList(); var programViewObject = _mapper.Map <List <ProgramSettingsViewModel> >(programList); model.SystemList = NameIdSelectList(systemList.ToList()); model.ProgramList = NameIdSelectList(programList.ToList()); model.SchoolList = NameIdSelectList(await _schoolService.GetSchoolsAsync()); model.ProgramJson = JsonConvert.SerializeObject(programViewObject); model.RequirePostalCode = site.RequirePostalCode; model.ShowAge = askAge; model.ShowSchool = askSchool; if (askIfFirstTime) { model.AskFirstTime = EmptyNoYes(); } if (askEmailSubscription) { model.AskEmailSubscription = EmptyNoYes(); model.AskEmailSubscriptionText = askEmailSubscriptionText; } if (askActivityGoal) { var pointTranslation = programList.First().PointTranslation; model.TranslationDescriptionPastTense = pointTranslation.TranslationDescriptionPastTense.Replace("{0}", "").Trim(); model.ActivityDescriptionPlural = pointTranslation.ActivityDescriptionPlural; } return(View(model)); }
public async Task <bool> LogSecretCodeAsync(int userIdToLog, string secretCode, bool householdLogging = false) { VerifyCanLog(); if (string.IsNullOrWhiteSpace(secretCode)) { throw new GraException("You must enter a code!"); } secretCode = _codeSanitizer.Sanitize(secretCode); int activeUserId = GetActiveUserId(); int authUserId = GetClaimId(ClaimType.UserId); var userToLog = await _userRepository.GetByIdAsync(userIdToLog); bool loggingAsAdminUser = HasPermission(Permission.LogActivityForAny); if (activeUserId != userIdToLog && authUserId != userToLog.HouseholdHeadUserId && !loggingAsAdminUser) { string error = $"User id {activeUserId} cannot log a code for user id {userIdToLog}"; _logger.LogError(error); throw new GraException("You do not have permission to apply that code."); } if ((await _requiredQuestionnaireRepository.GetForUser(GetCurrentSiteId(), userToLog.Id, userToLog.Age)).Any()) { string error = $"User id {activeUserId} cannot log secret code for user {userToLog} who has a pending questionnaire."; _logger.LogError(error); throw new GraException("Secret codes cannot be entered while there is a pending questionnaire to be taken."); } var trigger = await _triggerRepository.GetByCodeAsync(GetCurrentSiteId(), secretCode); if (trigger == null) { throw new GraException($"<strong>{secretCode}</strong> is not a valid code."); } // check if this user's gotten this code var alreadyDone = await _triggerRepository.CheckTriggerActivationAsync(userIdToLog, trigger.Id); if (alreadyDone != null) { if (householdLogging) { return(false); } else { throw new GraException($"You already entered the code <strong>{secretCode}</strong> on <strong>{alreadyDone:d}</strong>!"); } } // add that we've processed this trigger for this user await _triggerRepository.AddTriggerActivationAsync(userIdToLog, trigger.Id); // every trigger awards a badge var badge = await AwardBadgeAsync(userIdToLog, trigger.AwardBadgeId); // log the notification await _notificationRepository.AddSaveAsync(authUserId, new Notification { PointsEarned = trigger.AwardPoints, UserId = userIdToLog, Text = trigger.AwardMessage, BadgeId = trigger.AwardBadgeId, BadgeFilename = badge.Filename }); // add the award to the user's history var userLog = new UserLog { UserId = userIdToLog, PointsEarned = trigger.AwardPoints, IsDeleted = false, BadgeId = trigger.AwardBadgeId, Description = trigger.AwardMessage }; if (activeUserId != userToLog.Id) { userLog.AwardedBy = activeUserId; } await _userLogRepository.AddSaveAsync(authUserId, userLog); // award any vendor code that is necessary await AwardVendorCodeAsync(userIdToLog, trigger.AwardVendorCodeTypeId); // send mail if applicable int?mailId = await SendMailAsync(activeUserId, trigger); // award prize if applicable await AwardPrizeAsync(activeUserId, trigger, mailId); // if there are points to be awarded, do that now, also check for other triggers if (trigger.AwardPoints > 0) { await AddPointsSaveAsync(authUserId, activeUserId, userIdToLog, trigger.AwardPoints); } else { await AwardTriggersAsync(userIdToLog); } return(true); }