public async Task <ScriptResult> Post([FromBody] ScriptResult result)
        {
            _dataService.AddOrUpdateScriptResult(result);

            if (result.HadErrors && result.SavedScriptId.HasValue)
            {
                var savedScript = await _dataService.GetSavedScript(result.SavedScriptId.Value);

                if (savedScript.GenerateAlertOnError)
                {
                    await _dataService.AddAlert(result.DeviceID,
                                                result.OrganizationID,
                                                $"Alert triggered while running script {savedScript.Name}.",
                                                string.Join("\n", result.ErrorOutput));
                }

                if (savedScript.SendEmailOnError)
                {
                    var device = _dataService.GetDevice(result.DeviceID);

                    await _emailSender.SendEmailAsync(savedScript.SendErrorEmailTo,
                                                      "Script Run Alert",
                                                      $"An alert was triggered while running script {savedScript.Name} on device {device.DeviceName}. <br /><br />" +
                                                      $"Error Output: <br /><br /> " +
                                                      $"{string.Join("<br /><br />", result.ErrorOutput)}");
                }
            }

            if (result.ScriptRunId.HasValue)
            {
                await _dataService.AddScriptResultToScriptRun(result.ID, result.ScriptRunId.Value);
            }

            return(result);
        }
Esempio n. 2
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            var organizationCount = _dataService.GetOrganizationCount();

            if (_appConfig.MaxOrganizationCount > 0 && organizationCount >= _appConfig.MaxOrganizationCount)
            {
                return(NotFound());
            }
            returnUrl ??= Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new RemotelyUser
                {
                    UserName        = Input.Email,
                    Email           = Input.Email,
                    IsServerAdmin   = organizationCount == 0,
                    Organization    = new Organization(),
                    UserOptions     = new RemotelyUserOptions(),
                    IsAdministrator = true
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _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 },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"<img src='{Request.Scheme}://{Request.Host}/images/Fastwire_Logo.png'/><br><br>Please confirm your Fastwire account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email }));
                    }
                    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());
        }
Esempio n. 3
0
        public async Task <IActionResult> OnPostSaveAndTestSmtpAsync()
        {
            var result = await OnPostSaveAsync();

            var user    = _dataService.GetUserByName(User.Identity.Name);
            var success = await _emailSender.SendEmailAsync(user.Email, "Remotely Test Email", "Congratulations! Your SMTP settings are working!", user.OrganizationID);

            if (success)
            {
                StatusMessage = "Test email sent.  Check your inbox (including spam folder).";
            }
            else
            {
                StatusMessage = "Error sending email.  Check the server logs for details.";
            }
            return(result);
        }
        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);

                DataService.WriteEvent($"Sending password reset for user {user.UserName}. Reset URL: {callbackUrl}", user.OrganizationID);

                var emailResult = await _emailSender.SendEmailAsync(
                    Input.Email,
                    "Reset Password",
                    $"<img src='https://remotely.one/media/Remotely_Logo.png'/><br><br>Please reset your Remotely password by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                if (!emailResult)
                {
                    ModelState.AddModelError("EmailError", "Error sending email.");
                    return(Page());
                }


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

            return(Page());
        }
Esempio n. 5
0
        public async Task <IActionResult> OnPostSendVerificationEmailAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."));
            }


            var email = await _userManager.GetEmailAsync(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 = user.Id, code },
                protocol: Request.Scheme);
            var emailResult = await _emailSender.SendEmailAsync(
                email,
                "Confirm your email",
                $"<img src='{Request.Scheme}://{Request.Host}/images/Remotely_Logo.png'/><br><br>Please confirm your Remotely account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.",
                user.OrganizationID);

            if (!emailResult)
            {
                StatusMessage = "Error sending verification email.";
            }
            else
            {
                StatusMessage = "Verification email sent. Please check your email.";
            }
            return(RedirectToPage());
        }
Esempio n. 6
0
        public async Task <IActionResult> Create(AlertOptions alertOptions)
        {
            Request.Headers.TryGetValue("OrganizationID", out var orgID);

            _dataService.WriteEvent("Alert created.  Alert Options: " + JsonSerializer.Serialize(alertOptions), orgID);

            if (alertOptions.ShouldAlert)
            {
                try
                {
                    await _dataService.AddAlert(alertOptions.AlertDeviceID, orgID, alertOptions.AlertMessage);
                }
                catch (Exception ex)
                {
                    _dataService.WriteEvent(ex, orgID);
                }
            }

            if (alertOptions.ShouldEmail)
            {
                try
                {
                    await _emailSender.SendEmailAsync(alertOptions.EmailTo,
                                                      alertOptions.EmailSubject,
                                                      alertOptions.EmailBody,
                                                      orgID);
                }
                catch (Exception ex)
                {
                    _dataService.WriteEvent(ex, orgID);
                }
            }

            if (alertOptions.ShouldSendApiRequest)
            {
                try
                {
                    using var httpClient = _httpClientFactory.CreateClient();
                    using var request    = new HttpRequestMessage(
                              new HttpMethod(alertOptions.ApiRequestMethod),
                              alertOptions.ApiRequestUrl);

                    request.Content = new StringContent(alertOptions.ApiRequestBody);
                    request.Content.Headers.ContentType.MediaType = "application/json";

                    foreach (var header in alertOptions.ApiRequestHeaders)
                    {
                        request.Headers.TryAddWithoutValidation(header.Key, header.Value);
                    }

                    using var response = await httpClient.SendAsync(request);

                    _dataService.WriteEvent($"Alert API Response Status: {response.StatusCode}.", orgID);
                }
                catch (Exception ex)
                {
                    _dataService.WriteEvent(ex, orgID);
                }
            }

            return(Ok());
        }