public async Task <object> Register(RegisterDto model)
        {
            var user = new ApplicationUser()
            {
                UserName    = model.UserName,
                Email       = model.Email,
                PhoneNumber = model.PhoneNumber,
                Name        = model.FullName
            };
            var result = await _userManager.CreateAsync(user, model.Password);

            if (result.Succeeded)
            {
                var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                var callbackUrl = Url.Action("ConfirmEmail",
                                             "Account",
                                             new { userId = user.Id, code = code },
                                             protocol: HttpContext.Request.Scheme);
                SendGridEmailSender emailService = new SendGridEmailSender();
                await emailService.SendEmailAsync(model.Email, "Confirm your account",
                                                  $"Confirm Registration : <a href='http://localhost:4200/user/login'>link</a>");

                await _signInManager.SignInAsync(user, false);

                return(Content("Confirm Registration by email"));
            }

            throw new ApplicationException("UNKNOWN_ERROR");
        }
Exemplo n.º 2
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(Input.Email);

                if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(RedirectToPage("./ForgotPasswordConfirmation"));
                }

                // For more information on how to enable account confirmation and password reset please
                // visit https://go.microsoft.com/fwlink/?LinkID=532713
                var code = await _userManager.GeneratePasswordResetTokenAsync(user);

                code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                var callbackUrl = Url.Page(
                    "/Account/ResetPassword",
                    pageHandler: null,
                    values: new { area = "Identity", code },
                    protocol: Request.Scheme);

                var emailSender = new SendGridEmailSender(this._config["SendGrid:Key"]);
                await emailSender.SendEmailAsync(_config["SendGrid:Email"], EmailConstants.FromMailingName, Input.Email,
                                                 EmailConstants.ConfirmationEmailSubject,
                                                 string.Format(EmailConstants.ConfirmResetPassword, HtmlEncoder.Default.Encode(callbackUrl)));

                return(RedirectToPage("./ForgotPasswordConfirmation"));
            }

            return(Page());
        }
        public async Task <IActionResult> OnPostAsync()
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(Input.Email);

                if (user != null && user.EmailConfirmed == false)
                {
                    _logger.LogInformation($"User with id {user.Id} got reset of the email confirmation token.");

                    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 = user.Id, code = code },
                        protocol: Request.Scheme);

                    var emailSender = new SendGridEmailSender(this._config["SendGrid:Key"]);
                    await emailSender.SendEmailAsync(_config["SendGrid:Email"], EmailConstants.FromMailingName, Input.Email,
                                                     EmailConstants.ConfirmationEmailSubject,
                                                     string.Format(EmailConstants.ResetEmailConfirmation, HtmlEncoder.Default.Encode(callbackUrl)));
                }
            }
            return(RedirectToPage("./EmailConfirmationTokenReset"));
        }
Exemplo n.º 4
0
        public async Task RemoveUserFromProjectAsync(int userId, int projectId)
        {
            var project = await this.projectRepo.All()
                          .Where(x => x.Id == projectId)
                          .Include(x => x.Team)
                          .ThenInclude(x => x.TeamsUsers)
                          .FirstOrDefaultAsync();

            var teamUsersToRemove = project.Team.TeamsUsers
                                    .FirstOrDefault(x => x.UserId == userId && x.TeamId == project.Team.Id);

            this.teamUsersRepo.Delete(teamUsersToRemove);
            await teamUsersRepo.SaveChangesAsync();

            var message = EmailConstants.RemoveFromProject + project.Name;

            await this.notificationsService.AddNotificationToUserAsync(userId, message);

            // Send email to user to inform them about being added to a project.
            var user = await userManager.FindByIdAsync(userId.ToString());

            var emailSender = new SendGridEmailSender(this.config["SendGrid:Key"]);
            await emailSender.SendEmailAsync(this.config["SendGrid:Email"], EmailConstants.FromMailingName,
                                             user.Email, EmailConstants.RemoveFromProjectSubject, message);
        }
        public void SendGridEmailSenderShouldTrowExceptionWhenSubjectOrHtmlContentIsEmpty(string key)
        {
            var sengrid = new SendGridEmailSender(key);

            var result = sengrid.SendEmailAsync("FromMe", "Ivan", "ToYou", null, null, null).IsFaulted;

            Assert.True(result);
        }
Exemplo n.º 6
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new User {
                    UserName = Input.Email, Email = Input.Email,
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    await _userManager.AddToRoleAsync(user, ApplicationRolesConstatnts.User);

                    _logger.LogInformation("User created a new account with password.");

                    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 = user.Id, code = code, returnUrl = returnUrl },
                        protocol: Request.Scheme);

                    var emailSender = new SendGridEmailSender(this._config["SendGrid:Key"]);
                    await emailSender.SendEmailAsync(_config["SendGrid:Email"], EmailConstants.FromMailingName, Input.Email,
                                                     EmailConstants.ConfirmationEmailSubject,
                                                     string.Format(EmailConstants.ConfirmEmail, HtmlEncoder.Default.Encode(callbackUrl)));

                    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());
        }
Exemplo n.º 7
0
        public Reservatie AddReservatie(Reservatie reservatie)
        {
            var createdReservatie = _restaurantRepository.AddReservatie(reservatie);

            if (createdReservatie == null)
            {
                throw new RestaurantVolzetException();
            }
            try
            {
                _restaurantRepository.SaveChanges();
            }
            catch (Exception)
            {
                return(null);
            }
            string mailmsg = CreateMailMessage(createdReservatie);

            emailSender.SendEmailAsync(createdReservatie.Email, "Bevestiging van uw reservatie.", mailmsg).Wait();
            return(createdReservatie);
        }
        public static async Task <SendEmailResponse> SendUserVerificationEmail(string displayName, string email, string verificationURL,
                                                                               string body)
        {
            IEmailSender _sender = new SendGridEmailSender(ConfigExtension._config);

            var response = await Task.Run(() =>
            {
                return(_sender.SendEmailAsync(new SendEmailDetails
                {
                    IsHtml = true,
                    FromEmail = ConfigExtension._config["SendGrid:FromEmail"],
                    FromName = ConfigExtension._config["SendGrid:FromName"],
                    ToEmail = email,
                    ToName = displayName,
                    Subject = "Mail de Verificación",
                    BodyContent = body
                }));
            });


            return(response);
        }
Exemplo n.º 9
0
        public async Task AddUserToProject(int userId, int projectId)
        {
            var project = await this.projectRepo.All()
                          .Where(x => x.Id == projectId)
                          .Include(x => x.Team)
                          .FirstOrDefaultAsync();

            project.Team.TeamsUsers.Add(new TeamsUsers {
                UserId = userId, TeamId = project.Team.Id
            });
            await this.projectRepo.SaveChangesAsync();

            var message = EmailConstants.AddedToProject + project.Name;

            await this.notificationsService.AddNotificationToUserAsync(userId, message);

            // Send email to user to inform them about being added to a project.
            var user = await userManager.FindByIdAsync(userId.ToString());

            var emailSender = new SendGridEmailSender(this.config["SendGrid:Key"]);
            await emailSender.SendEmailAsync(this.config["SendGrid:Email"], EmailConstants.FromMailingName,
                                             user.Email, EmailConstants.AddedToProjectSubject, message);
        }
        public async Task <IActionResult> OnGetAsync(string email, string returnUrl = null)
        {
            if (email == null)
            {
                return(RedirectToPage("/Index"));
            }

            var user = await _userManager.FindByEmailAsync(email);

            if (user == null)
            {
                return(NotFound($"Unable to load user with email '{email}'."));
            }

            Email = email;
            // Once you add a real email sender, you should remove this code that lets you confirm the account
            DisplayConfirmAccountLink = false;
            if (DisplayConfirmAccountLink)
            {
                var userId = await _userManager.GetUserIdAsync(user);

                var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                EmailConfirmationUrl = Url.Page(
                    "/Account/ConfirmEmail",
                    pageHandler: null,
                    values: new { area = "Identity", userId = userId, code = code, returnUrl = returnUrl },
                    protocol: Request.Scheme);
            }

            var emailSender = new SendGridEmailSender(_config["SendGrid:Key"]);
            await emailSender.SendEmailAsync(_config["SendGrid:Key"], EmailConstants.FromMailingName, user.Email,
                                             EmailConstants.RegisterConfirmation, string.Format(EmailConstants.ConfirmEmail, HtmlEncoder.Default.Encode(EmailConfirmationUrl)));

            return(Page());
        }
Exemplo n.º 11
0
 public Task SendEmail([FromBody] Email email)
 => _sender.SendEmailAsync(email);
Exemplo n.º 12
0
        public Reservatie DeleteReservatie(long id, string user = "******")
        {
            var verwijderdeReservatie = _reserveringRepository.DeleteReservatie(id, user);

            if (DateTime.ParseExact(verwijderdeReservatie.Datum, "yyyy-MM-dd", null) < DateTime.Now)
            {
                verwijderdeReservatie.Naam = "PAST";
                return(verwijderdeReservatie);
            }
            if (verwijderdeReservatie != null)
            {
                _reserveringRepository.SaveChanges();
                string enter = "<br>";
                string mailmsg;
                switch (user)
                {
                case "gebruiker":
                    mailmsg =
                        "Beste " + verwijderdeReservatie.Naam + "," +
                        enter +
                        enter +
                        "Hierbij een bevestiging van uw geannuleerde reservatie met onderstaande gegevens." +
                        enter +
                        enter +
                        "<ul>" +
                        "<li> Op naam van: " + verwijderdeReservatie.Naam + "</li>" +
                        "<li> Bij restaurant: " + verwijderdeReservatie.Restaurant.Naam + "</li>" +
                        "<li> Aantal personen: " + verwijderdeReservatie.AantalPersonen + "</li>" +
                        "<li> Gepland op: " + verwijderdeReservatie.Datum + " om " + verwijderdeReservatie.Tijdstip + "</li>" +
                        "<li> Email adres: " + verwijderdeReservatie.Email + "</li>" +
                        "<li> Telefoonnummer: " + verwijderdeReservatie.TelefoonNummer.ToString() + "</li>" +
                        "</ul>";
                    break;

                case "uitbater":
                    mailmsg =
                        "Beste " + verwijderdeReservatie.Naam + "," +
                        enter +
                        enter +
                        "Het restaurant waarbij u een reservatie maakt heeft uw reservatie met onderstaande gegevens geannuleerd." +
                        enter +
                        "Als dit onverwachts is, gelieve contact op te nemen met het restaurant." +
                        enter +
                        enter +
                        "<ul>" +
                        "<li> Op naam van: " + verwijderdeReservatie.Naam + "</li>" +
                        "<li> Bij restaurant: " + verwijderdeReservatie.Restaurant.Naam + "</li>" +
                        "<li> Aantal personen: " + verwijderdeReservatie.AantalPersonen + "</li>" +
                        "<li> Gepland op: " + verwijderdeReservatie.Datum + " om " + verwijderdeReservatie.Tijdstip + "</li>" +
                        "<li> Email adres: " + verwijderdeReservatie.Email + "</li>" +
                        "<li> Telefoonnummer: " + verwijderdeReservatie.TelefoonNummer.ToString() + "</li>" +
                        "</ul>";
                    break;

                default:
                    return(null);
                }
                emailSender.SendEmailAsync(verwijderdeReservatie.Email, "Annulatie van uw reservatie.", mailmsg).Wait();
            }
            return(verwijderdeReservatie);
        }
        public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            // Get the information about the user from the external login provider
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ErrorMessage = "Error loading external login information during confirmation.";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            if (ModelState.IsValid)
            {
                var user = new User {
                    UserName = Input.Email, Email = Input.Email
                };

                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);

                        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 },
                            protocol: Request.Scheme);

                        var emailSender = new SendGridEmailSender(this._config["SendGrid:Key"]);
                        await emailSender.SendEmailAsync(_config["SendGrid:Email"], EmailConstants.FromMailingName, Input.Email,
                                                         EmailConstants.ConfirmationEmailSubject,
                                                         string.Format(EmailConstants.ExternalLogin, HtmlEncoder.Default.Encode(callbackUrl)));

                        //var emailToSend = new Email(_config["EmailSenderInformation:Email"], Input.Email,
                        //$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.",
                        //EmailConstants.ConfirmationEmailSubject);

                        //await _emailSender.SendAsync(emailToSend, _config["EmailSenderInformation:Password"],
                        //    _config["EmailSenderOptions:SmtpServer"], int.Parse(_config["EmailSenderOptions:Port"]));

                        // If account confirmation is required, we need to show the link if we don't have a real email sender
                        if (_userManager.Options.SignIn.RequireConfirmedAccount)
                        {
                            return(RedirectToPage("./RegisterConfirmation", new { Email = Input.Email }));
                        }

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

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            ProviderDisplayName = info.ProviderDisplayName;
            ReturnUrl           = returnUrl;
            return(Page());
        }