コード例 #1
0
        public static async Task <Result> SendPasswortResetEmail(string email)
        {
            using (var con = new DBContext(await NsslEnvironment.OpenConnectionAsync(), true))
            {
                User exists = null;
                if (email != null)
                {
                    exists = await FindUserByName(con.Connection, email);
                }
                if (exists == null)
                {
                    exists = await FindUserByEmail(con.Connection, email);

                    if (exists == null)
                    {
                        return new Result {
                                   Success = false, Error = "user could not be found"
                        }
                    }
                    ;
                }

                var sender  = new OutlookDotComMail(mailUser, mailUserPwd);
                var payload = new Dictionary <string, object>()
                {
                    { "Expires", DateTime.UtcNow.AddDays(1) },
                    { "Id", exists.Id },
                    { "Created", DateTime.UtcNow }
                };

                var token     = JsonWebToken.Encode(new Dictionary <string, object>(), payload, SecretKey, JsonWebToken.JwtHashAlgorithm.HS256);
                var tokenUser = new TokenUserId(token, exists.Id);
                tokenUser.Timestamp = DateTime.UtcNow;
                await Q.InsertOne(con.Connection, tokenUser);

                sender.SendMail(exists.Email, "NSSL Password Reset",
                                $"Dear {exists.Username},\r\n\r\n" +
                                "This email was automatically sent following your request to reset your password.\r\n" +
                                "To reset your password, click this link or paste it into your browser's address bar:\r\n" +
                                "https://nssl.susch.eu/password/site/reset?token=" + token +
                                "\r\n\r\n" +
                                "If you did not forget your password, please ignore this email. Thank you.\r\n\r\n" +
                                "Kind Regards,\r\n" +
                                "NSSL Team");
                con.Connection.Close();
                return(new Result {
                    Success = true, Error = ""
                });
            }
        }
コード例 #2
0
        public static void Main(string[] args)
        {
            // This solution takes 3 command-line arguments: receiver email, directory to your email-secret, path to a python-generated log-file
            if (args.Length < 2)
            {
                Console.WriteLine("Usage: {reciever e-mail} {directory to secret} {path to log-file}");
                return;
            }
            else if (args.Length == 2)
            {
                // Fetch email credentials
                ClientCredentials ccr = new Services.ClientCredentials();
                ccr.SetValue(args [1]);
                var credentials = ccr.GetMailCredentials;
                Console.WriteLine(credentials);
                // Setup mail client with credentials
                var cli = new OutlookDotComMail(credentials.Item1, credentials.Item2);
                cli.SendMail(args [0], "Jenkins is working", "Hello!");
            }
            else if (args.Length == 3)
            {
                // Fetch email credentials
                ClientCredentials ccr = new Services.ClientCredentials();
                ccr.SetValue(args [1]);
                var credentials = ccr.GetMailCredentials;
                Console.WriteLine(credentials);
                // Setup mail client with credentials
                var cli = new OutlookDotComMail(credentials.Item1, credentials.Item2);

                // Instantiate log-reader in provided directory
                var logReader = new Services.LogReader();
                logReader.SetValue(args [2]);
                var log = logReader.GetLog;

                // Create HTML table from provided log-file
                var html = new HTMLMake.HTMLTable();
                var tbl  = html.CreateHTMLTable(log);

                // Use SMTP client to send the table with a subject to provided receiver
                cli.SendMail(args [0], "Error Log", tbl);
            }
            else
            {
                Console.WriteLine("Input parameters not understood");
            }
        }
コード例 #3
0
        public static async Task <Result> ResetPassword(string token, string n)
        {
            using (var c = new DBContext(await NsslEnvironment.OpenConnectionAsync(), true))
            {
                var rpt = await Q.From(TokenUserId.T).Where(x => x.Timestamp.GtV(DateTime.UtcNow.AddDays(-1)).And(x.ResetToken.EqV(token))).FirstOrDefault <TokenUserId>(c.Connection);

                if (rpt == null)
                {
                    return new Result {
                               Success = false, Error = "Token Expired or password reset was not requested"
                    }
                }
                ;
                var user = await Q.From(T).Where(x => x.Id.EqV(rpt.UserId)).FirstOrDefault <User>(c.Connection);

                if (user == null)
                {
                    return new Result {
                               Success = false, Error = "User for the token doesn't exists anymore"
                    }
                }
                ;
                await ChangePassword(user.Id, "", n, true);

                await Q.DeleteFrom(TokenUserId.T).Where(x => x.Timestamp.EqV(rpt.Timestamp).And(x.ResetToken.EqV(rpt.ResetToken).And(x.UserId.EqV(rpt.UserId)))).Execute(c.Connection);

                var sender = new OutlookDotComMail(mailUser, mailUserPwd);
                sender.SendMail(user.Email, "NSSL Password Reset",
                                $@"Dear {user.Username},

This email was sent to you, because you have successfully changed your password.


If it wasn't you, than this might be an indicator, that someone has access to your email account.


Kind Regards,
NSSL Team");
                c.Connection.Close();
                return(new Result {
                    Success = true
                });
            }
        }
コード例 #4
0
        static void Main(string[] args)
        {
            const int confirmationPosition = 80;

            var config   = new Configuration(args);
            var content  = System.IO.File.ReadAllText(config.ContentFile);
            var dataRows = System.IO.File.ReadAllLines(config.DataFile).Select(row => new DataRow(row)).Where(row => !string.IsNullOrEmpty(row.EMail));
            var mail     = new OutlookDotComMail(config);

            int rowNumber = 0;
            int rowTotal  = dataRows.Count();

            foreach (var row in dataRows)
            {
                rowNumber++;
                string confirmation = $"{rowNumber}/{rowTotal}. Send to {row.EMail.Left(confirmationPosition - 22)} (Y/N)? ";
                Console.Write(confirmation);
                if (row.IsEnabled)
                {
                    bool toSend = false;

                    // Automatic sends
                    if (config.PromptBeforeSend)
                    {
                        var keyInfo = Console.ReadKey();
                        if (keyInfo.KeyChar == 'Y' || keyInfo.KeyChar == 'y')
                        {
                            toSend = true;
                        }
                    }
                    else
                    {
                        toSend = true;
                    }

                    if (toSend)
                    {
                        try
                        {
                            mail.SendMail(row.EMail, content, row.Parameters);
                            Console.WriteLine($"{String.Empty.PadLeft(confirmationPosition - confirmation.Length, ' ')} ... Sent");
                        }
                        catch (Exception ex)
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine(ex.Message);
                            Console.ResetColor();
                        }

                        // Wait some seconds before the next sent
                        if (config.PromptBeforeSend == false)
                        {
                            int timeBetweenNext = new Random().Next(500, 2000);
                            System.Threading.Thread.Sleep(timeBetweenNext);
                        }
                    }
                    else
                    {
                        Console.WriteLine($"{String.Empty.PadLeft(confirmationPosition - confirmation.Length, ' ')} ... Skipped");
                    }
                }
                else
                {
                    Console.WriteLine($"{String.Empty.PadLeft(confirmationPosition - confirmation.Length, ' ')}  ... Commented");
                }
            }

            Console.WriteLine("Completed");
        }
コード例 #5
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = Input.Email, Email = Input.Email, FullName = Input.FullName, DateTimeRegister = DateTime.Now
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");
                    // DisplayConfirmAccountLink = false;
                    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);

                    //await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                    //    $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    _logger.Log(LogLevel.Warning, callbackUrl);
                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email }));
                    }
                    else
                    {
                        if (_signInManager.IsSignedIn(User) && User.IsInRole("Admin"))
                        {
                            return(RedirectToAction("ListUsers", "Administration"));
                        }
                        //dokimes
                        string mailUser    = "******";
                        string mailUserPwd = "Kostis10590!";
                        var    sender      = new OutlookDotComMail(mailUser, mailUserPwd);

                        string subjectMsg = "Verify your email";

                        sender.SendMail(user.Email, subjectMsg,
                                        $"Please confirm your account by clicking here {callbackUrl}");

                        return(RedirectToPage("EmailVerification"));


                        //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());
        }