Ejemplo n.º 1
0
        /// <summary>
        /// Sends an email for the given <see cref="Account.EmailPurpose"/> to the <see cref="ApplicationUser"/>
        /// </summary>
        /// <param name="user">The <see cref="ApplicationUser"/> as the recipient of the email.</param>
        /// <param name="purpose">The <see cref="Account.EmailPurpose"/> of the email.</param>
        /// <param name="model">The model parameter for the view.</param>
        private async Task SendEmail(ApplicationUser user, EmailPurpose purpose, string model)
        {
            _userEmailTask1.Timeout          = _userEmailTask2.Timeout = TimeSpan.FromMinutes(1);
            _userEmailTask1.EmailCultureInfo = _userEmailTask2.EmailCultureInfo = CultureInfo.CurrentUICulture;

            switch (purpose)
            {
            case EmailPurpose.NotifyCurrentPrimaryEmail:
                _userEmailTask1.ToEmail    = user.Email;
                _userEmailTask1.Subject    = _localizer["Your primary email is about to be changed"].Value;
                _userEmailTask1.ViewNames  = new[] { ViewNames.Emails.NotifyCurrentPrimaryEmail, ViewNames.Emails.NotifyCurrentPrimaryEmailTxt };
                _userEmailTask1.LogMessage = "Notify current primary email about the requested change";
                _userEmailTask1.Model      = (Email : model, CallbackUrl : string.Empty, OrganizationContext : _siteContext);
                _queue.QueueTask(_userEmailTask1);
                break;

            case EmailPurpose.ConfirmNewPrimaryEmail:
                var newEmail = model;
                _userEmailTask2.ToEmail    = newEmail;
                _userEmailTask2.Subject    = _localizer["Please confirm your new primary email"].Value;
                _userEmailTask2.ViewNames  = new [] { ViewNames.Emails.ConfirmNewPrimaryEmail, ViewNames.Emails.ConfirmNewPrimaryEmailTxt };
                _userEmailTask2.LogMessage = "Email to confirm the new primary email";
                var code = (await _userManager.GenerateChangeEmailTokenAsync(user, newEmail)).Base64UrlEncode();
                _userEmailTask2.Model = (Email : newEmail, CallbackUrl : Url.Action(nameof(ConfirmNewPrimaryEmail), nameof(Manage), new { Organization = _siteContext.UrlSegmentValue, id = user.Id, code, e = newEmail.Base64UrlEncode() }, protocol : HttpContext.Request.Scheme), OrganizationContext : _siteContext);
                _queue.QueueTask(_userEmailTask2);
                break;

            default:
                _logger.LogError($"Illegal enum type for {nameof(EmailPurpose)}");
                break;
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Sends an email for the given <see cref="EmailPurpose"/> to the <see cref="ApplicationUser"/>
        /// </summary>
        /// <param name="user">The <see cref="ApplicationUser"/> as the recipient of the email.</param>
        /// <param name="purpose">The <see cref="EmailPurpose"/> of the email.</param>
        private async Task SendCodeByEmail(ApplicationUser user, EmailPurpose purpose)
        {
            string code;

            _userEmailTask.Timeout          = TimeSpan.FromMinutes(1);
            _userEmailTask.EmailCultureInfo = CultureInfo.CurrentUICulture;
            _userEmailTask.ToEmail          = user.Email;

            switch (purpose)
            {
            case EmailPurpose.ConfirmYourEmail:
                _userEmailTask.Subject    = _localizer["Please confirm your email address"].Value;
                _userEmailTask.ViewNames  = new [] { ViewNames.Emails.EmailPleaseConfirmEmail, ViewNames.Emails.EmailPleaseConfirmEmailTxt };
                _userEmailTask.LogMessage = "Send email confirmation mail";
                code = _dataProtector.Encrypt(user.Email, DateTimeOffset.UtcNow.Add(_dataProtectionTokenProviderOptions.Value.TokenLifespan)).Base64UrlEncode();
                _userEmailTask.Model = (Email : user.Email, CallbackUrl : Url.Action(nameof(Register), nameof(Account), new { Organization = _siteContext.UrlSegmentValue, code }, protocol : HttpContext.Request.Scheme), _siteContext);
                break;

            case EmailPurpose.ForgotPassword:
                _userEmailTask.Subject    = _localizer["This is your password recovery key"].Value;
                _userEmailTask.ViewNames  = new [] { ViewNames.Emails.EmailPasswordReset, ViewNames.Emails.EmailPasswordResetTxt };
                _userEmailTask.LogMessage = "Password recovery email";
                code = (await _signInManager.UserManager.GeneratePasswordResetTokenAsync(user)).Base64UrlEncode();
                _userEmailTask.Model = (Email : user.Email, CallbackUrl : Url.Action(nameof(ResetPassword), nameof(Account), new { Organization = _siteContext.UrlSegmentValue, id = user.Id, code }, protocol : HttpContext.Request.Scheme), _siteContext);
                break;

            default:
                _logger.LogError($"Illegal enum type for {nameof(EmailPurpose)}");
                break;
            }

            _queue.QueueTask(_userEmailTask);
        }
Ejemplo n.º 3
0
        private void SendEmail(ContactViewModel model)
        {
            _contactEmailTask.Timeout          = TimeSpan.FromMinutes(1);
            _contactEmailTask.EmailCultureInfo = CultureInfo.DefaultThreadCurrentUICulture;

            _contactEmailTask.ViewNames  = new[] { null, ViewNames.Emails.ContactEmailTxt };
            _contactEmailTask.LogMessage = "Send contact form as email";
            _contactEmailTask.Model      = (Form : model, SiteContext : _siteContext);
            _queue.QueueTask(_contactEmailTask);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Sends an email for the given <see cref="EmailPurpose"/> to the <see cref="ApplicationUser"/>
        /// </summary>
        /// <param name="user">The <see cref="ApplicationUser"/> as the recipient of the email.</param>
        /// <param name="purpose">The <see cref="EmailPurpose"/> of the email.</param>
        private async Task SendCodeByEmail(ApplicationUser user, EmailPurpose purpose)
        {
            string code;
            var    deadline = DateTime.UtcNow.Add(_dataProtectionTokenProviderOptions.Value.TokenLifespan);

            // round down to full hours
            deadline = new DateTime(deadline.Year, deadline.Month, deadline.Day, deadline.Hour, 0, 0);

            switch (purpose)
            {
            case EmailPurpose.PleaseConfirmEmail:
                code = _dataProtector.Encrypt(user.Email, DateTimeOffset.UtcNow.Add(_dataProtectionTokenProviderOptions.Value.TokenLifespan)).Base64UrlEncode();
                _sendEmailTask.SetMessageCreator(new ChangeUserAccountCreator
                {
                    Parameters =
                    {
                        Email       = user.Email,
                        Subject     = _localizer["Please confirm your email address"].Value,
                        CallbackUrl = Url.Action(nameof(Register),                          nameof(Account),
                                                 new { Organization= _tenantContext.SiteContext.UrlSegmentValue,           code },
                                                 protocol: HttpContext.Request.Scheme),
                        DeadlineUtc      = deadline,
                        CultureInfo      = CultureInfo.CurrentUICulture,
                        TemplateNameTxt  = TemplateName.PleaseConfirmEmailTxt,
                        TemplateNameHtml = TemplateName.PleaseConfirmEmailHtml
                    }
                });
                break;

            case EmailPurpose.PasswordReset:
                code = (await _signInManager.UserManager.GeneratePasswordResetTokenAsync(user)).Base64UrlEncode();
                _sendEmailTask.SetMessageCreator(new ChangeUserAccountCreator
                {
                    Parameters =
                    {
                        Email       = user.Email,
                        Subject     = _localizer["Please confirm your email address"].Value,
                        CallbackUrl = Url.Action(nameof(ResetPassword),                     nameof(Account),
                                                 new { Organization= _tenantContext.SiteContext.UrlSegmentValue,           id = user.Id,code                            },
                                                 protocol: HttpContext.Request.Scheme),
                        DeadlineUtc      = deadline,
                        CultureInfo      = CultureInfo.CurrentUICulture,
                        TemplateNameTxt  = TemplateName.PasswordResetTxt,
                        TemplateNameHtml = TemplateName.PasswordResetHtml
                    }
                });
                break;

            default:
                _logger.LogError($"Illegal enum type for {nameof(EmailPurpose)}");
                break;
            }

            _queue.QueueTask(_sendEmailTask);
        }
Ejemplo n.º 5
0
        private void SendEmail(ContactViewModel model)
        {
            _sendEmailTask.SetMessageCreator(new Emailing.Creators.ContactFormCreator
            {
                Parameters =
                {
                    ContactForm = model,
                    CultureInfo = CultureInfo.DefaultThreadCurrentUICulture ?? CultureInfo.CurrentCulture
                }
            });

            _queue.QueueTask(_sendEmailTask);
        }
Ejemplo n.º 6
0
        private void SendFixtureNotification(long matchId)
        {
            _sendMailTask.SetMessageCreator(new ChangeFixtureCreator
            {
                Parameters =
                {
                    CultureInfo     = CultureInfo.DefaultThreadCurrentUICulture ?? CultureInfo.CurrentCulture,
                    ChangedByUserId = GetCurrentUserId(),
                    MatchId         = matchId,
                }
            });

            _queue.QueueTask(_sendMailTask);
        }
Ejemplo n.º 7
0
        private void SendFixtureNotification(long matchId)
        {
            // Change culture, so that the language of the subject equals the language of the notification
            var(currentCulture, currentUiCulture) = (Thread.CurrentThread.CurrentCulture, Thread.CurrentThread.CurrentUICulture);

            // Change culture, so that the language of the subject equals the language of the notification
            (Thread.CurrentThread.CurrentCulture, Thread.CurrentThread.CurrentUICulture) = (CultureInfo.DefaultThreadCurrentCulture, CultureInfo.DefaultThreadCurrentUICulture);
            _fixtureEmailTask.Timeout          = TimeSpan.FromMinutes(1);
            _fixtureEmailTask.EmailCultureInfo = CultureInfo.DefaultThreadCurrentUICulture;
            _fixtureEmailTask.Subject          = _localizer["Change of fixture {0}"].Value;
            _fixtureEmailTask.ViewNames        = new[] { null, ViewNames.Emails.FixtureChangedEmailTxt };
            _fixtureEmailTask.LogMessage       = "Send fixture notification";
            _fixtureEmailTask.Model            = (User, matchId, _siteContext, null);
            _queue.QueueTask(_fixtureEmailTask);
            // Restore the culture
            (Thread.CurrentThread.CurrentCulture, Thread.CurrentThread.CurrentUICulture) = (currentCulture, currentUiCulture);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Sends mail messages to current and new email address
        /// </summary>
        /// <param name="user">The <see cref="ApplicationUser"/> as the recipient of the notification email.</param>
        /// <param name="newEmail">The new email address for the user that must be confirmed.</param>
        private async Task SendEmail(ApplicationUser user, string newEmail)
        {
            var deadline = DateTime.UtcNow.Add(_dataProtectionTokenProviderOptions.Value.TokenLifespan);

            // round down to full hours
            deadline = new DateTime(deadline.Year, deadline.Month, deadline.Day, deadline.Hour, 0, 0);
            var code = (await _userManager.GenerateChangeEmailTokenAsync(user, newEmail)).Base64UrlEncode();

            _sendEmailTask.SetMessageCreator(new ChangePrimaryUserEmailCreator
            {
                Parameters =
                {
                    Email       = user.Email,
                    NewEmail    = newEmail,
                    CallbackUrl = Url.Action(nameof(ConfirmNewPrimaryEmail),nameof(Manage),  new { Organization = _tenantContext.SiteContext.UrlSegmentValue, id = user.Id, code, e = newEmail.Base64UrlEncode() }, protocol: HttpContext.Request.Scheme),
                    DeadlineUtc = deadline,
                    CultureInfo = CultureInfo.CurrentUICulture,
                }
            });

            _queue.QueueTask(_sendEmailTask);
        }
Ejemplo n.º 9
0
        public async Task <IActionResult> Confirm(bool done, CancellationToken cancellationToken)
        {
            var sessionModel = await GetModelFromSession(cancellationToken);

            if (!sessionModel.IsFromSession)
            {
                return(RedirectToAction(nameof(SelectTeam), new { Organization = _tenantContext.SiteContext.UrlSegmentValue }));
            }
            try
            {
                var teamInRoundEntity = new TeamInRoundEntity();
                try
                {
                    // If the team had already been registered for another round, we have get the existing entity
                    if (!sessionModel.TeamInRound.IsNew)
                    {
                        teamInRoundEntity =
                            (await _appDb.TeamInRoundRepository.GetTeamInRoundAsync(
                                 new PredicateExpression(TeamInRoundFields.Id == sessionModel.TeamInRound.Id),
                                 cancellationToken)).First();
                    }
                }
                catch (Exception e)
                {
                    _logger.LogCritical(e, $"{nameof(TeamInRoundEntity)} with ID {sessionModel.TeamInRound.Id} for team ID {sessionModel.TeamInRound.TeamId} not found");
                    throw;
                }

                var isNewApplication = teamInRoundEntity.IsNew;
                sessionModel.TeamInRound.MapFormFieldsToEntity(teamInRoundEntity);
                teamInRoundEntity.Team = new TeamEntity();
                sessionModel.Team.MapFormFieldsToEntity(teamInRoundEntity.Team);
                teamInRoundEntity.Team.Venue = new VenueEntity();
                sessionModel.Venue.MapFormFieldsToEntity(teamInRoundEntity.Team.Venue);



                // Adds the current user as team manager, unless she already is team manager
                await AddManagerToTeamEntity(teamInRoundEntity.Team, cancellationToken);

                if (await _appDb.GenericRepository.SaveEntityAsync(teamInRoundEntity, true, true, cancellationToken))
                {
                    HttpContext.Session.Remove(TeamApplicationSessionName);
                    TempData.Put <TeamApplicationMessageModel.TeamApplicationMessage>(
                        nameof(TeamApplicationMessageModel.TeamApplicationMessage),
                        new TeamApplicationMessageModel.TeamApplicationMessage
                    {
                        AlertType = SiteAlertTagHelper.AlertType.Success,
                        MessageId = TeamApplicationMessageModel.MessageId.ApplicationSuccess
                    });

                    _sendEmailTask.SetMessageCreator(new ConfirmTeamApplicationCreator
                    {
                        Parameters =
                        {
                            CultureInfo          = CultureInfo.DefaultThreadCurrentUICulture,
                            TeamId               = teamInRoundEntity.TeamId,
                            IsNewApplication     = isNewApplication,
                            RoundId              = teamInRoundEntity.RoundId,
                            RegisteredByUserId   = GetCurrentUserId(),
                            UrlToEditApplication = Url.Action(nameof(EditTeam),              nameof(TeamApplication),new { Organization = _tenantContext.SiteContext.UrlSegmentValue, teamId = teamInRoundEntity.TeamId }, Request.Scheme, Request.Host.ToString())
                        }
                    });

                    _queue.QueueTask(_sendEmailTask);

                    return(RedirectToAction(nameof(List), new { Organization = _tenantContext.SiteContext.UrlSegmentValue }));
                }

                throw new Exception($"Saving the {nameof(TeamInRoundEntity)} failed.");
            }
            catch (Exception e)
            {
                _logger.LogCritical(e, "Team application could not be saved.");
                HttpContext.Session.Remove(TeamApplicationSessionName);
                TempData.Put <TeamApplicationMessageModel.TeamApplicationMessage>(
                    nameof(TeamApplicationMessageModel.TeamApplicationMessage),
                    new TeamApplicationMessageModel.TeamApplicationMessage
                {
                    AlertType = SiteAlertTagHelper.AlertType.Danger,
                    MessageId = TeamApplicationMessageModel.MessageId.ApplicationFailure
                });
                return(RedirectToAction(nameof(List), new { Organization = _tenantContext.SiteContext.UrlSegmentValue }));
            }
        }
        public async Task <IActionResult> Confirm(bool done, CancellationToken cancellationToken)
        {
            var sessionModel = await GetModelFromSession(cancellationToken);

            if (!sessionModel.IsFromSession)
            {
                return(RedirectToAction(nameof(SelectTeam), new { Organization = _siteContext.UrlSegmentValue }));
            }

            var teamInRoundEntity = new TeamInRoundEntity();

            sessionModel.TeamInRound.MapFormFieldsToEntity(teamInRoundEntity);
            teamInRoundEntity.Team = new TeamEntity();
            sessionModel.Team.MapFormFieldsToEntity(teamInRoundEntity.Team);
            teamInRoundEntity.Team.Venue = new VenueEntity();
            sessionModel.Venue.MapFormFieldsToEntity(teamInRoundEntity.Team.Venue);

            try
            {
                var isNewApplication = teamInRoundEntity.IsNew;

                // Adds the current user as team manager, unless she already is team manager
                await AddManagerToTeamEntity(teamInRoundEntity.Team, cancellationToken);

                if (await _appDb.GenericRepository.SaveEntityAsync(teamInRoundEntity, true, true, cancellationToken))
                {
                    HttpContext.Session.Remove(TeamApplicationSessionName);
                    TempData.Put <TeamApplicationMessageModel.TeamApplicationMessage>(
                        nameof(TeamApplicationMessageModel.TeamApplicationMessage),
                        new TeamApplicationMessageModel.TeamApplicationMessage
                    {
                        AlertType = SiteAlertTagHelper.AlertType.Success,
                        MessageId = TeamApplicationMessageModel.MessageId.ApplicationSuccess
                    });

                    _teamApplicationEmailTask.Model = new ApplicationEmailViewModel
                    {
                        RegisteredByUserId   = GetCurrentUserId(),
                        TeamId               = teamInRoundEntity.TeamId,
                        TeamName             = teamInRoundEntity.TeamNameForRound,
                        IsNewApplication     = isNewApplication,
                        TournamentName       = sessionModel.TournamentName,
                        RoundId              = teamInRoundEntity.RoundId,
                        OrganizationContext  = _siteContext,
                        UrlToEditApplication = Url.Action(nameof(EditTeam), nameof(TeamApplication), new { Organization = _siteContext.UrlSegmentValue, teamId = teamInRoundEntity.TeamId }, Request.Scheme, Request.Host.ToString())
                    };
                    _teamApplicationEmailTask.Subject          = _localizer["Registration for team '{0}'", _teamApplicationEmailTask.Model.TeamName].Value;
                    _teamApplicationEmailTask.EmailCultureInfo = CultureInfo.DefaultThreadCurrentUICulture;
                    _teamApplicationEmailTask.Timeout          = TimeSpan.FromMinutes(5);
                    _teamApplicationEmailTask.ViewNames        = new[] { null, ViewNames.Emails.ConfirmTeamApplicationTxt };
                    _queue.QueueTask(_teamApplicationEmailTask);

                    return(RedirectToAction(nameof(List), new { Organization = _siteContext.UrlSegmentValue }));
                }

                throw new Exception($"Saving the {nameof(TeamInRoundEntity)} failed.");
            }
            catch (Exception e)
            {
                _logger.LogCritical(e, "Team application could not be saved.");
                HttpContext.Session.Remove(TeamApplicationSessionName);
                TempData.Put <TeamApplicationMessageModel.TeamApplicationMessage>(
                    nameof(TeamApplicationMessageModel.TeamApplicationMessage),
                    new TeamApplicationMessageModel.TeamApplicationMessage
                {
                    AlertType = SiteAlertTagHelper.AlertType.Danger,
                    MessageId = TeamApplicationMessageModel.MessageId.ApplicationFailure
                });
                return(RedirectToAction(nameof(List), new { Organization = _siteContext.UrlSegmentValue }));
            }
        }