Exemplo n.º 1
0
        private async Task SendEmailConfirmation(IdentityUser user, string returnUrl = null)
        {
            var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

            var redirectUri = returnUrl != null
                ? new Uri(HttpUtility.ParseQueryString(Url.Content(returnUrl)).Get("redirect_uri"))
                              .GetLeftPart(UriPartial.Authority)
                : null;

            var callbackUrl = Url.Action(
                action: nameof(ConfirmEmail),
                controller: "Account",
                values: new { userId = user.Id, code, redirectUri },
                protocol: Request.Scheme);

            var outgoingEmail = new OutgoingEmail
            {
                To       = user.Email,
                From     = _transactionalTemplateConfiguration.FromEmail,
                Template = new Template
                {
                    Id            = _transactionalTemplateConfiguration.RegistrationTemplate,
                    Substitutions = new Dictionary <string, string>
                    {
                        { _transactionalTemplateConfiguration.DynamicUserNameKey, user.UserName },
                        { _transactionalTemplateConfiguration.DynamicLinkKey, callbackUrl }
                    },
                    IsDynamic = true
                }
            };

            await _emailSender.SendEmailAsync(outgoingEmail);
        }
Exemplo n.º 2
0
        private void SaveFavorites(OutgoingEmail email)
        {
            List <string> allOutgoingAddresses = new List <string>();

            foreach (string to in email.To)
            {
                allOutgoingAddresses.Add(to);
            }
            if (email.Cc != null)
            {
                foreach (string cc in email.Cc)
                {
                    allOutgoingAddresses.Add(cc);
                }
            }
            if (email.Bcc != null)
            {
                foreach (string bcc in email.Bcc)
                {
                    allOutgoingAddresses.Add(bcc);
                }
            }
            foreach (string receiver in allOutgoingAddresses)
            {
                if (DatabaseManager.InsertContact(FromAccount.AccountName, receiver))
                {
                    Trace.WriteLine(receiver + " added to Contacts.");
                }
            }
        }
Exemplo n.º 3
0
        public void SendEmail()
        {
            OutgoingEmail email = new OutgoingEmail();

            email.To      = ToAccounts;
            email.Cc      = CcAccounts;
            email.Bcc     = BccAccounts;
            email.Subject = Subject;
            email.Message = MessageBody;

            SmtpClient NewConnection = new SmtpClient(FromAccount, email);

            if (!NewConnection.Connect())
            {
                Trace.WriteLine(NewConnection.Error);
                MessageBoxResult result = MessageBox.Show(NewConnection.Error);
                return;
            }

            if (!NewConnection.SendMail(attachments))
            {
                Trace.WriteLine(NewConnection.Error);
                MessageBoxResult result = MessageBox.Show(NewConnection.Error);
                return;
            }

            FinishInteraction();
            NewConnection.Disconnect();
        }
Exemplo n.º 4
0
        public async void SendEmail(OutgoingEmail email)
        {
            var queue   = new AsyncCollector <OutgoingEmail>();
            var tbTrack = new AsyncCollector <SendEmailTrack>();

            var response = (ObjectResult)await Email.SendEmail(CreateMockRequest(email).Object, queue, tbTrack, logger);

            Assert.Equal(200, response.StatusCode);
            Assert.NotNull(((SendMailResponse)response.Value).TrackerId);
        }
Exemplo n.º 5
0
 public static void Run(TraceWriter log,
                        [ServiceBusTrigger("emailqueue", Connection = "ServiceBusConnection")] OutgoingEmail email,
                        [SendGrid(ApiKey = "SengridApiKey")] out SendGridMessage message)
 {
     log.Info($"Request incoming{email.ToString()}");
     message = new SendGridMessage();
     message.AddTo(email.To);
     message.AddContent("text/html", email.Body);
     message.SetFrom(new EmailAddress(email.From));
     message.SetSubject(email.Subject);
 }
Exemplo n.º 6
0
        private bool StoreEntities(OutgoingEmail email, List <string> attachmentList)
        {
            foreach (string iter in attachmentList)
            {
                FileStream stream = File.OpenRead(iter);
                if (!stream.CanRead)
                {
                    return(false);
                }

                string      mimeType = MimeTypes.GetMimeType(iter);
                ContentType fileType = ContentType.Parse(mimeType);
                MimePart    attachment;
                if (fileType.IsMimeType("text", "*"))
                {
                    attachment = new TextPart(fileType.MediaSubtype);
                    foreach (var param in fileType.Parameters)
                    {
                        attachment.ContentType.Parameters.Add(param);
                    }
                }
                else
                {
                    attachment = new MimePart(fileType);
                }
                attachment.FileName     = Path.GetFileName(iter);
                attachment.IsAttachment = true;

                MemoryBlockStream  memoryBlockStream = new MemoryBlockStream();
                BestEncodingFilter encodingFilter = new BestEncodingFilter();
                byte[]             fileBuffer = new byte[4096];
                int index, length, bytesRead;

                while ((bytesRead = stream.Read(fileBuffer, 0, fileBuffer.Length)) > 0)
                {
                    encodingFilter.Filter(fileBuffer, 0, bytesRead, out index, out length);
                    memoryBlockStream.Write(fileBuffer, 0, bytesRead);
                }

                encodingFilter.Flush(fileBuffer, 0, 0, out index, out length);
                memoryBlockStream.Position = 0;

                attachment.ContentTransferEncoding = encodingFilter.GetBestEncoding(EncodingConstraint.SevenBit);
                attachment.ContentObject           = new ContentObject(memoryBlockStream);

                if (attachment != null)
                {
                    email.AttachmentList.Add(attachment);
                }
            }
            return(true);
        }
        public static void Run([TimerTrigger("10 * * * * *")] TimerInfo myTimer,
                               [SendGrid(ApiKey = "CustomSendGridKeyAppSettingName")] out SendGridMessage message)
        {
            var emailObject = new OutgoingEmail();

            emailObject.Body = "Teste de envio de email no Azure Functions com sendgrid";

            message = new SendGridMessage();
            message.AddTo("*****@*****.**");
            message.AddContent("text/html", emailObject.Body);
            message.SetFrom(new EmailAddress("*****@*****.**"));
            message.SetSubject("Teste Azure Functions");
        }
Exemplo n.º 8
0
        public async Task <IActionResult> ConfirmEmail(string userId, string code, string redirectUri = null)
        {
            if (userId == null || code == null)
            {
                return(RedirectToAction(nameof(Login)));
            }
            var user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {
                return(BadRequest($"Unable to load user with ID '{userId}'."));
            }

            if (user.EmailConfirmed)
            {
                return(RedirectToAction(nameof(Login)));
            }

            var result = await _userManager.ConfirmEmailAsync(user, code);

            if (result.Succeeded)
            {
                await _signInManager.SignInAsync(user, false);

                var outgoingEmail = new OutgoingEmail
                {
                    To       = user.Email,
                    From     = _transactionalTemplateConfiguration.FromEmail,
                    Template = new Template
                    {
                        Id            = _transactionalTemplateConfiguration.WelcomeTemplate,
                        Substitutions = new Dictionary <string, string>
                        {
                            { _transactionalTemplateConfiguration.UserNameKey, user.UserName }
                        },
                        IsDynamic = false
                    }
                };

                await _emailSender.SendEmailAsync(outgoingEmail);
            }

            if (redirectUri != null)
            {
                return(Redirect(redirectUri));
            }
            else
            {
                return(RedirectToAction(nameof(Login)));
            }
        }
Exemplo n.º 9
0
 public static async Task Create(IAsyncCollector <SendEmailTrack> tbTracker, OutgoingEmail emailMessage, Event dEvent,
                                 string messageId = null)
 {
     var content = JsonConvert.SerializeObject(emailMessage);
     await tbTracker.AddAsync(new SendEmailTrack
     {
         PartitionKey = emailMessage.ToAddress.Email,
         RowKey       = emailMessage.TrackerId,
         Event        = dEvent.ToString(),
         Content      = content,
         Date         = DateTime.UtcNow,
         MessageId    = messageId
     });
 }
Exemplo n.º 10
0
        public void SendEmail()
        {
            OutgoingEmail email = new OutgoingEmail();

            email.To = ExtractRecipients(toAccounts);
            if (!String.IsNullOrEmpty(CcAccounts))
            {
                email.Cc = ExtractRecipients(CcAccounts);
            }
            if (!String.IsNullOrEmpty(BccAccounts))
            {
                email.Bcc = ExtractRecipients(BccAccounts);
            }
            email.Subject = Subject;
            email.Message = MessageBody;
            if (isHtml)
            {
                email.HtmlPart = HtmlBody;
            }
            if (Attachments != null)
            {
                List <string> attachmentFilePaths = new List <string>();
                foreach (AttachmentViewModel attachmentVm in Attachments)
                {
                    attachmentFilePaths.Add(attachmentVm.FilePath);
                }
                StoreEntities(email, attachmentFilePaths);
            }

            SmtpClient NewConnection = new SmtpClient(FromAccount, email);

            if (!NewConnection.Connect())
            {
                Trace.WriteLine(NewConnection.Error);
                MessageBoxResult result = MessageBox.Show(NewConnection.Error);
                return;
            }

            if (!NewConnection.SendMail(isHtml))
            {
                Trace.WriteLine(NewConnection.Error);
                MessageBoxResult result = MessageBox.Show(NewConnection.Error);
                return;
            }

            SaveFavorites(email);
            FinishInteraction();
            Attachments.Clear();
            NewConnection.Disconnect();
        }
Exemplo n.º 11
0
        public async Task SendMail(OutgoingEmail outgoingEmail)
        {
            var client = new SendGridClient(_sendGridApiKey);

            var message = new SendGridMessage
            {
                Subject     = outgoingEmail.Subject,
                HtmlContent = outgoingEmail.Body
            };

            message.SetFrom(outgoingEmail.From);
            message.AddTo(outgoingEmail.To);

            await client.SendEmailAsync(message);
        }
Exemplo n.º 12
0
        public async Task <IActionResult> ForgotPasswordConfirm(ForgotPasswordModel model)
        {
            if (string.IsNullOrEmpty(model?.Email))
            {
                return(View(nameof(ForgotPassword)));
            }

            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(model.Email);

                if (user == null || !await _userManager.IsEmailConfirmedAsync(user))
                {
                    _trackTelemetry.TrackEvent(EventName.ResetPassword, EventType.Action, EventStatus.UserNotFound);

                    // Don't reveal that the user does not exist or is not confirmed
                    return(View(nameof(ForgotPasswordConfirm)));
                }

                var code = await _userManager.GeneratePasswordResetTokenAsync(user);

                _trackTelemetry.TrackEvent(EventName.ResetPassword, EventType.Method, Providers.Zupa);

                var callbackUrl = Url.Action(nameof(ResetPassword), "Account", new { userId = user.Id, code }, HttpContext.Request.Scheme);

                var outgoingEmail = new OutgoingEmail
                {
                    To       = user.Email,
                    From     = _transactionalTemplateConfiguration.FromEmail,
                    Template = new Template
                    {
                        Id            = _transactionalTemplateConfiguration.ResetPasswordTemplate,
                        Substitutions = new Dictionary <string, string>
                        {
                            { _transactionalTemplateConfiguration.UserNameKey, user.UserName },
                            { _transactionalTemplateConfiguration.LinkKey, callbackUrl }
                        },
                        IsDynamic = false,
                    }
                };

                await _emailSender.SendEmailAsync(outgoingEmail);

                return(View(nameof(ForgotPasswordConfirm)));
            }

            return(View(nameof(ForgotPasswordConfirm)));
        }
Exemplo n.º 13
0
        private async Task SendLockoutEmail(IdentityUser user)
        {
            var outgoingEmail = new OutgoingEmail
            {
                To       = user.Email,
                From     = _transactionalTemplateConfiguration.FromEmail,
                Template = new Template
                {
                    Id            = _transactionalTemplateConfiguration.LockoutTemplate,
                    Substitutions = new Dictionary <string, string>
                    {
                        { _transactionalTemplateConfiguration.UserNameKey, user.UserName },
                        { _transactionalTemplateConfiguration.LockoutTimeKey, _lockoutSettings.DefaultLockoutTimeSpan.ToString() }
                    },
                    IsDynamic = false
                }
            };

            await _emailSender.SendEmailAsync(outgoingEmail);
        }
Exemplo n.º 14
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            var smtp = new SMTP()
            {
                Email    = "*****@*****.**",
                Server   = "server.enguzelyerler.com",
                Port     = 587,
                Password = "******"
            };
            var outgoingEmail = new OutgoingEmail()
            {
                To      = "*****@*****.**",
                Subject = "Bu bir deneme emailidir",
                Body    = "bu benim istediğim içerik <b>olabilir</b>."
            };

            MailHelper.Send(SendCompletedCallback, smtp, outgoingEmail);
            Console.ReadLine();
        }
Exemplo n.º 15
0
        public static async Task ProcessEmailQueue(
            [QueueTrigger(EMAIL_QUEUE)] OutgoingEmail emailQueue,
            [Table(EMAIL_TRACK)] CloudTable tbEmailTrack,
            [Table(EMAIL_BLOCKED)] CloudTable tbEmailBlocked,
            int dequeueCount,
            ILogger log)
        {
            log.LogInformation($"New email to send. Dequeue count for this message: {dequeueCount}.");

            try
            {
                var toEmail = emailQueue.ToAddress.Email;

                //Check whether the recipient of the message is blocked
                //TODO: Change this method to check if the email is blocked calling a SendGrid Api
                var recipientIsBlocked = await EmailBlocker.CheckIfBlocked(toEmail, tbEmailBlocked);

                if (recipientIsBlocked)
                {
                    log.LogInformation($"Can't send email to {toEmail} because it has been blocked");
                    await EmailTracker.Update(tbEmailTrack, toEmail, emailQueue.TrackerId, Event.Blocked, log);

                    return;
                }

                var response = await SendMail.SendSingleEmail(emailQueue.FromAddress, emailQueue.ToAddress, emailQueue.Subject, emailQueue.Body,
                                                              emailQueue.TrackerId, log);

                if (!SuccessStatusCodes.Contains(response.StatusCode))
                {
                    throw new Exception($"Error sending mail. SendGrid response {response.StatusCode}");
                }
                //Track that email request was sent
                await EmailTracker.Update(tbEmailTrack, toEmail, emailQueue.TrackerId, Event.SendRequested, log, response.MessageId);
            }
            catch (Exception ex)
            {
                log.LogError("An error has occurred: {0}", ex);
                throw;
            }
        }
Exemplo n.º 16
0
        public static async Task BatchInsert(
            [ActivityTrigger] OutgoingEmail emailObject,
            [SendGrid(ApiKey = "SendGridApiKey")] IAsyncCollector <SendGridMessage> messageCollector, ILogger log)
        {
            log.LogInformation($"Notifications triggered for new cars");

            try
            {
                var message = new SendGridMessage();
                message.AddTo(emailObject.To); // TODO - should probably be in bcc instead. But email without any 'to' address is not allowed
                message.AddContent("text/html", emailObject.Body);
                message.SetFrom(new EmailAddress(emailObject.From));
                message.SetSubject(emailObject.Subject);

                await messageCollector.AddAsync(message);
            }
            catch (Exception e)
            {
                log.LogError(e, "Exception caught in EmailSender");
                throw e;
            }
        }
Exemplo n.º 17
0
        public string GetEmailTemplateBody(OutgoingEmail outgoingEmail)
        {
            //var path = AppDomain.CurrentDomain.BaseDirectory + @"\bin";

            //TemplatePath = Path.Combine(path, @"AD\EmailTemplate.html");

            //TemplatePath = TemplatePath.Replace(@"file:\\", "");

            var    TemplatePath = ConfigurationManager.AppSettings["EmailTemplatePath"];
            string text         = System.IO.File.ReadAllText(TemplatePath);

            text = text.Replace("{{SystemURL}}", ConfigurationManager.AppSettings["SystemBaseURL"].ToString());
            text = text.Replace("{{MailTo}}", ConfigurationManager.AppSettings["SupportEmail"].ToString());
            text = text.Replace("{{EmailAboutBody}}", App.Entity.Resources.KidsApp.AboutEmailBody);

            //Email Body
            text = text.Replace("{{MsgBodyEn}}", outgoingEmail.TextEn);
            text = text.Replace("{{MsgBodyAr}}", outgoingEmail.TextAr);

            return(text);
            //MailSender.SendEmail(App.Entity.Resources.KidsApp.WelcomEmailSubject, text, "*****@*****.**");
        }
Exemplo n.º 18
0
        public IHttpActionResult AddOutgoingEmail(OutgoingEmail outgoingEmail)
        {
            try
            {
                if (this.ActiveUser.UserType != SharedEnums.UserTypes.Manager)
                {
                    return(BadRequest());
                }



                //Save Reply
                outgoingEmail.State = BaseState.Added;
                Mgr.AddUpdate(outgoingEmail);
                Unit.SaveChanges();

                return(Ok(outgoingEmail));
            }
            catch (Exception ex)
            {
                Unit.LogError(ex, this.ToString(), this.ActionContext.ActionArguments.ToList());
                return(InternalServerError(ex));
            }
        }
Exemplo n.º 19
0
            public static void Send(EventHandler <System.ComponentModel.AsyncCompletedEventArgs> sendCompletedCallback, SMTP smtp, OutgoingEmail outgoingEmail)
            {
                SmtpClient smtpClient = new SmtpClient(smtp.Server, smtp.Port)
                {
                    EnableSsl             = false,
                    UseDefaultCredentials = false,
                    Credentials           = new NetworkCredential(smtp.Email, smtp.Password)
                };

                MailAddress fromMailAddress = new MailAddress(smtp.Email, "Bilge Adam", Encoding.UTF8);
                MailAddress toMailAddress   = new MailAddress(outgoingEmail.To);

                MailMessage mailMessage = new MailMessage(fromMailAddress, toMailAddress)
                {
                    IsBodyHtml      = true,
                    Body            = outgoingEmail.Body,
                    Subject         = outgoingEmail.Subject,
                    SubjectEncoding = Encoding.UTF8,
                    BodyEncoding    = Encoding.UTF8
                };

                smtpClient.SendCompleted += new SendCompletedEventHandler((sender, args) => sendCompletedCallback?.Invoke(null, args));
                smtpClient.SendAsync(mailMessage, 123);
            }
Exemplo n.º 20
0
        public static async Task Run(
            [QueueTrigger("emails")] OutgoingEmail email,
            [SendGrid] IAsyncCollector <SendGridMessage> messageCollector, ILogger log)
        {
            try
            {
                if (email is null)
                {
                    throw new ArgumentNullException(nameof(email));
                }
                else if (email.Tos is null || !email.Tos.Any())
                {
                    throw new ArgumentException("There must be at least one recipient.", nameof(email.Tos));
                }
                else if (string.IsNullOrWhiteSpace(email.Body))
                {
                    throw new ArgumentNullException("There must be a body for the email.", nameof(email.Body));
                }

                log.LogInformation("Starting email process");

                var message = new SendGridMessage();

                message.SetFrom(new EmailAddress(Environment.GetEnvironmentVariable("FromEmail"), Environment.GetEnvironmentVariable("FromName")));
                message.SetSubject(email.Subject);
                message.HtmlContent = email.Body;

                var hardcodedToEmail = Environment.GetEnvironmentVariable("ToEmail");
                if (string.IsNullOrWhiteSpace(hardcodedToEmail))
                {
                    foreach (var toEmail in email.Tos)
                    {
                        log.LogInformation("email: {toEmail}", toEmail);
                        message.AddTo(toEmail);
                    }
                }
                else
                {
                    log.LogInformation("harcoded email: {email}", hardcodedToEmail);
                    message.AddTo(hardcodedToEmail);
                }

                if (email.Attachments != null && email.Attachments.Any())
                {
                    log.LogInformation("Have {count} attachment(s)", email.Attachments.Count);
                    var storageAccount = CloudStorageAccount.Parse(Environment.GetEnvironmentVariable("AzureWebJobsStorage"));

                    var client    = storageAccount.CreateCloudBlobClient();
                    var container = client.GetContainerReference(Environment.GetEnvironmentVariable("Container_Name"));
                    await container.CreateIfNotExistsAsync();

                    foreach (var file in email.Attachments)
                    {
                        var dirRef      = container.GetDirectoryReference(file);
                        var isDirectory = dirRef.ListBlobs().Count() > 0;

                        if (isDirectory)
                        {
                            log.LogInformation("Processing folder: {file}", file);
                            var bag      = new ConcurrentBag <Attachment>();
                            var taskList = new List <Task>();

                            foreach (CloudBlob b in dirRef.ListBlobs(useFlatBlobListing: true))
                            {
                                taskList.Add(Task.Run(async() => bag.Add(await DownloadBlob(b, log))));
                            }

                            await Task.WhenAll(taskList);

                            if (bag.Any())
                            {
                                message.AddAttachments(bag.ToList());
                            }
                            else
                            {
                                log.LogWarning("There are no files in the {folder} folder", file);
                            }
                        }
                        else
                        {
                            log.LogInformation("Processing file: {file}", file);
                            var blobRef = container.GetBlobReference(file);
                            if (await blobRef.ExistsAsync())
                            {
                                message.Attachments.Add(await DownloadBlob(blobRef, log));
                            }
                            else
                            {
                                throw new ArgumentException($"The file {file} does not exists", nameof(file));
                            }
                        }
                    }
                }

                log.LogDebug("Sending an email with the subject: {subject}", email.Subject);

                await messageCollector.AddAsync(message);

                log.LogInformation("Finished sending email");
            }
Exemplo n.º 21
0
 public SmtpClient(Account account, OutgoingEmail email)
 {
     Account  = account;
     NewEmail = email;
 }
Exemplo n.º 22
0
        public ActionResult SignUp(SignUp signUp)
        {
            try
            {
                ActionResult actionResult = ServiceHelper.IsAnyNullOrEmpty(signUp);
                if (actionResult.Success)
                {
                    actionResult.Success = false;
                    return(actionResult);
                }

                ApplicationUserManager manager = HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>();
                string password = PasswordService.GeneratePassword(PasswordOptions.HasCapitals |
                                                                   PasswordOptions.HasDigits |
                                                                   PasswordOptions.HasLower |
                                                                   PasswordOptions.HasSymbols |
                                                                   PasswordOptions.NoRepeating);
                Guid userId = Guid.NewGuid();
                manager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(10);
                manager.MaxFailedAccessAttemptsBeforeLockout = 3;
                manager.UserLockoutEnabledByDefault          = true;
                ApplicationUser applicationUser = new ApplicationUser
                {
                    UserName       = signUp.Username,
                    Email          = signUp.Email,
                    PhoneNumber    = signUp.PhoneNumber,
                    Id             = userId.ToString(),
                    LockoutEnabled = true
                };
                IdentityResult result = manager.Create(applicationUser, password);
                string         error  = result.Errors.Aggregate(string.Empty, (current, resultError) => current + resultError + Environment.NewLine);
                if (!result.Succeeded)
                {
                    return(new ActionResult
                    {
                        Success = false,
                        Message = error
                    });
                }

                string userRole = signUp.UserRole.ToString();
                result = manager.AddToRole(applicationUser.Id, userRole);
                using (ESamhashoEntities entities = new ESamhashoEntities())
                {
                    string       emailConfirmationToken = manager.GenerateEmailConfirmationToken(applicationUser.Id);
                    ActionResult guid = UserManagement.SaveVerificationDetails(applicationUser.Email, emailConfirmationToken);
                    if (!guid.Success)
                    {
                        return(new ActionResult
                        {
                            Success = false,
                            Message = "Failed to register new user."
                        });
                    }

                    Uri           requestUrl = new Uri(HttpContext.Current.Request.Url, "/Backoffice/Authentication.svc/json/VerifyEmail/" + guid.Message);
                    EmailTemplate emailBody  = entities.EmailTemplates.FirstOrDefault(a => a.EmailTemplateId == (byte)EmailTemplateId.SignUp);
                    if (emailBody != null)
                    {
                        string body = emailBody.Body.Replace("{activateaccount}", requestUrl.ToString())
                                      .Replace("{email}", applicationUser.Email)
                                      .Replace("{password}", password)
                                      .Replace("{accountname}", applicationUser.UserName);
                        string        subject       = "Esamhasho registration confirmation";
                        OutgoingEmail outgoingEmail = new OutgoingEmail
                        {
                            Body        = body,
                            Date        = DateTime.Now,
                            Destination = applicationUser.Email,
                            Reference   = applicationUser.Id,
                            Status      = (byte)EmailStatus.Pending,
                            Subject     = subject
                        };
                        entities.OutgoingEmails.Add(outgoingEmail);
                        entities.SaveChanges();
                        manager.SendEmail(applicationUser.Id, subject, body);
                        OutgoingEmail email = entities.OutgoingEmails.FirstOrDefault(a => a.Id == outgoingEmail.Id);
                        if (email != null)
                        {
                            email.Status = (byte)EmailStatus.Success;
                        }
                        entities.SaveChanges();
                    }
                }

                if (result.Succeeded)
                {
                    return(new ActionResult
                    {
                        Success = true,
                        Message = "Successfully register new user. The user should check there email to avtivate there account."
                    });
                }

                error = result.Errors.Aggregate(string.Empty, (current, resultError) => current + resultError + Environment.NewLine);
                return(new ActionResult
                {
                    Success = false,
                    Message = error
                });
            }
            catch (Exception exception)
            {
                Dictionary <string, string> dictionary = signUp.ToDictionary();
                ServiceHelper.LogException(exception, dictionary, ErrorSource.Authentication);
                return(new ActionResult
                {
                    Success = false,
                    Message = "Error, failed to register new user."
                });
            }
        }
Exemplo n.º 23
0
        public ActionResult ForgotPassword(string username)
        {
            try
            {
                ActionResult actionResult = ServiceHelper.IsAnyNullOrEmpty(username);
                if (actionResult.Success)
                {
                    actionResult.Success = false;
                    return(actionResult);
                }

                ApplicationUserManager manager = new ApplicationUserManager(new UserStore <ApplicationUser>(new ApplicationDbContext()));
                ApplicationUser        user    = manager.FindByEmail(username);
                if (user == null)
                {
                    return(new ActionResult
                    {
                        Message = "User does not exist",
                        Success = false
                    });
                }

                if (!manager.IsEmailConfirmed(user.Id))
                {
                    return new ActionResult
                           {
                               Success = false,
                               Message = "You need to confirm your email."
                           }
                }
                ;
                ApplicationUserManager userManager = HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>();
                string resetToken  = userManager.GeneratePasswordResetToken(user.Id);
                string newPassword = PasswordService.GeneratePassword(PasswordOptions.HasCapitals |
                                                                      PasswordOptions.HasDigits |
                                                                      PasswordOptions.HasLower |
                                                                      PasswordOptions.HasSymbols |
                                                                      PasswordOptions.NoRepeating);

                IdentityResult result = userManager.ResetPassword(user.Id, resetToken, newPassword);
                if (result.Succeeded)
                {
                    using (ESamhashoEntities entities = new ESamhashoEntities())
                    {
                        EmailTemplate emailBody = entities.EmailTemplates.FirstOrDefault(a => a.EmailTemplateId == (byte)EmailTemplateId.ResetPassword);
                        if (emailBody != null)
                        {
                            string body = emailBody.Body.Replace("{password}", newPassword)
                                          .Replace("{accountname}", user.UserName);
                            string        subject       = "Esamhasho password reset";
                            OutgoingEmail outgoingEmail = new OutgoingEmail
                            {
                                Body        = body,
                                Date        = DateTime.Now,
                                Destination = user.Email,
                                Reference   = user.Id,
                                Status      = (byte)EmailStatus.Pending,
                                Subject     = subject
                            };
                            entities.OutgoingEmails.Add(outgoingEmail);
                            entities.SaveChanges();
                            manager.SendEmail(user.Id, subject, body);
                            OutgoingEmail email = entities.OutgoingEmails.FirstOrDefault(a => a.Id == outgoingEmail.Id);
                            if (email != null)
                            {
                                email.Status = (byte)EmailStatus.Success;
                            }
                            entities.SaveChanges();
                        }
                    }

                    return(new ActionResult
                    {
                        Message = "Password successfully reset. Check your email for your new password.",
                        Success = true
                    });
                }

                string error = result.Errors.Aggregate(string.Empty, (current, resultError) => current + resultError + Environment.NewLine);
                return(new ActionResult {
                    Message = error, Success = result.Succeeded
                });
            }
            catch (Exception exception)
            {
                Dictionary <string, string> dictionary = username.ToDictionary();
                ServiceHelper.LogException(exception, dictionary, ErrorSource.Authentication);
                return(new ActionResult
                {
                    Success = false,
                    Message = "Error, failed to reset password."
                });
            }
        }
Exemplo n.º 24
0
        public ActionResult ChangePassword(ChangePassword changePassword)
        {
            try
            {
                string token = HttpContext.Current.Request.Headers["Token"];
                if (!Security.ValidateToken(token, out List <Claim> claims))
                {
                    return(new ActionResult
                    {
                        Message = "Please login",
                        Success = false
                    });
                }
                ActionResult actionResult = ServiceHelper.IsAnyNullOrEmpty(changePassword);
                if (actionResult.Success)
                {
                    actionResult.Success = false;
                    return(actionResult);
                }

                ApplicationUserManager manager = new ApplicationUserManager(new UserStore <ApplicationUser>(new ApplicationDbContext()));
                ApplicationUser        user    = manager.FindByName(changePassword.Username);
                if (user == null)
                {
                    return(new ActionResult
                    {
                        Message = "User does not exist",
                        Success = false
                    });
                }

                IdentityResult result = manager.ChangePassword(user.Id, changePassword.OldPassword, changePassword.NewPassword);
                if (result.Succeeded)
                {
                    using (ESamhashoEntities entities = new ESamhashoEntities())
                    {
                        EmailTemplate emailBody = entities.EmailTemplates.FirstOrDefault(a => a.EmailTemplateId == (byte)EmailTemplateId.ResetPassword);
                        if (emailBody != null)
                        {
                            string body = emailBody.Body.Replace("{password}", changePassword.NewPassword)
                                          .Replace("{accountname}", user.UserName);
                            string        subject       = "Esamhasho password reset";
                            OutgoingEmail outgoingEmail = new OutgoingEmail
                            {
                                Body        = body,
                                Date        = DateTime.Now,
                                Destination = user.Email,
                                Reference   = user.Id,
                                Status      = (byte)EmailStatus.Pending,
                                Subject     = subject
                            };
                            entities.OutgoingEmails.Add(outgoingEmail);
                            entities.SaveChanges();
                            manager.SendEmail(user.Id, subject, body);
                            OutgoingEmail email = entities.OutgoingEmails.FirstOrDefault(a => a.Id == outgoingEmail.Id);
                            if (email != null)
                            {
                                email.Status = (byte)EmailStatus.Success;
                            }
                            entities.SaveChanges();
                        }
                    }

                    return(new ActionResult
                    {
                        Message = "Password successfully changed",
                        Success = true
                    });
                }

                string error = result.Errors.Aggregate(string.Empty, (current, resultError) => current + resultError + Environment.NewLine);
                return(new ActionResult
                {
                    Message = error
                });
            }
            catch (Exception exception)
            {
                Dictionary <string, string> dictionary = changePassword.ToDictionary();
                ServiceHelper.LogException(exception, dictionary, ErrorSource.Authentication);
                return(new ActionResult
                {
                    Success = false,
                    Message = "Error, failed to change password."
                });
            }
        }