Skip to content

Commit

Permalink
Merge pull request #649 from immense/jaredg-respect-httplogging-setting
Browse files Browse the repository at this point in the history
Replace DbLogger in the server with Serilog.
  • Loading branch information
bitbound committed May 23, 2023
2 parents 6297175 + c647e03 commit 0386295
Show file tree
Hide file tree
Showing 37 changed files with 806 additions and 681 deletions.
44 changes: 24 additions & 20 deletions Server/API/AgentUpdateController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,32 +27,28 @@ public class AgentUpdateController : ControllerBase


private readonly IHubContext<AgentHub> _agentHubContext;

private readonly ILogger<AgentUpdateController> _logger;
private readonly IApplicationConfig _appConfig;

private readonly IDataService _dataService;

private readonly IWebHostEnvironment _hostEnv;

private readonly IServiceHubSessionCache _serviceSessionCache;

public AgentUpdateController(IWebHostEnvironment hostingEnv,
IDataService dataService,
IApplicationConfig appConfig,
IServiceHubSessionCache serviceSessionCache,
IHubContext<AgentHub> agentHubContext)
IHubContext<AgentHub> agentHubContext,
ILogger<AgentUpdateController> logger)
{
_hostEnv = hostingEnv;
_dataService = dataService;
_appConfig = appConfig;
_serviceSessionCache = serviceSessionCache;
_agentHubContext = agentHubContext;
_logger = logger;
}

[HttpGet("[action]/{downloadId}")]
public ActionResult ClearDownload(string downloadId)
{
_dataService.WriteEvent($"Clearing download ID {downloadId}.", EventType.Debug, null);
_logger.LogDebug("Clearing download ID {downloadId}.", downloadId);
_downloadingAgents.Remove(downloadId);
return Ok();
}
Expand Down Expand Up @@ -92,10 +88,16 @@ public async Task<ActionResult> DownloadPackage(string platform, string download
_downloadingAgents.Set(downloadId, string.Empty, cacheOptions);

var waitTime = DateTimeOffset.Now - startWait;
_dataService.WriteEvent($"Download started after wait time of {waitTime}. " +
$"ID: {downloadId}. " +
$"IP: {remoteIp}. " +
$"Current Downloads: {_downloadingAgents.Count}. Max Allowed: {_appConfig.MaxConcurrentUpdates}", EventType.Debug, null);
_logger.LogDebug(
"Download started after wait time of {waitTime}. " +
"ID: {downloadId}. " +
"IP: {remoteIp}. " +
"Current Downloads: {_downloadingAgentsCount}. Max Allowed: {_appConfigMaxConcurrentUpdates}",
waitTime,
downloadId,
remoteIp,
_downloadingAgents.Count,
_appConfig.MaxConcurrentUpdates);


string filePath;
Expand All @@ -115,11 +117,13 @@ public async Task<ActionResult> DownloadPackage(string platform, string download
filePath = Path.Combine(_hostEnv.WebRootPath, "Content", "Remotely-MacOS-x64.zip");
break;
default:
_dataService.WriteEvent($"Unknown platform requested in {nameof(AgentUpdateController)}. " +
$"Platform: {platform}. " +
$"IP: {remoteIp}.",
EventType.Warning,
null);
_logger.LogWarning(
"Unknown platform requested in {className}. " +
"Platform: {platform}. " +
"IP: {remoteIp}.",
nameof(AgentUpdateController),
platform,
remoteIp);
return BadRequest();
}

Expand All @@ -130,7 +134,7 @@ public async Task<ActionResult> DownloadPackage(string platform, string download
catch (Exception ex)
{
_downloadingAgents.Remove(downloadId);
_dataService.WriteEvent(ex, null);
_logger.LogError(ex, "Error while downloading package.");
return StatusCode((int)HttpStatusCode.InternalServerError);
}
}
Expand All @@ -144,7 +148,7 @@ private async Task<bool> CheckForDeviceBan(string deviceIp)

if (_appConfig.BannedDevices.Contains(deviceIp))
{
_dataService.WriteEvent($"Device IP ({deviceIp}) is banned. Sending uninstall command.", null);
_logger.LogInformation("Device IP ({deviceIp}) is banned. Sending uninstall command.", deviceIp);


var bannedDevices = _serviceSessionCache.GetAllDevices().Where(x => x.PublicIP == deviceIp);
Expand Down
20 changes: 14 additions & 6 deletions Server/API/AlertsController.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Build.Framework;
using Microsoft.Extensions.Logging;
using Remotely.Server.Auth;
using Remotely.Server.Services;
using Remotely.Shared.Models;
Expand All @@ -20,20 +22,26 @@ public class AlertsController : ControllerBase
private readonly IDataService _dataService;
private readonly IEmailSenderEx _emailSender;
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger<AlertsController> _logger;

public AlertsController(IDataService dataService, IEmailSenderEx emailSender, IHttpClientFactory httpClientFactory)
public AlertsController(
IDataService dataService,
IEmailSenderEx emailSender,
IHttpClientFactory httpClientFactory,
ILogger<AlertsController> logger)
{
_dataService = dataService;
_emailSender = emailSender;
_httpClientFactory = httpClientFactory;
_logger = logger;
}

[HttpPost("Create")]
public async Task<IActionResult> Create(AlertOptions alertOptions)
{
Request.Headers.TryGetValue("OrganizationID", out var orgID);

_dataService.WriteEvent("Alert created. Alert Options: " + JsonSerializer.Serialize(alertOptions), orgID);
_logger.LogInformation("Alert created. Alert Options: {options}", JsonSerializer.Serialize(alertOptions));

if (alertOptions.ShouldAlert)
{
Expand All @@ -43,7 +51,7 @@ public async Task<IActionResult> Create(AlertOptions alertOptions)
}
catch (Exception ex)
{
_dataService.WriteEvent(ex, orgID);
_logger.LogError(ex, "Error while adding alert.");
}
}

Expand All @@ -58,7 +66,7 @@ public async Task<IActionResult> Create(AlertOptions alertOptions)
}
catch (Exception ex)
{
_dataService.WriteEvent(ex, orgID);
_logger.LogError(ex, "Error while sending email.");
}

}
Expand All @@ -81,11 +89,11 @@ public async Task<IActionResult> Create(AlertOptions alertOptions)
}

using var response = await httpClient.SendAsync(request);
_dataService.WriteEvent($"Alert API Response Status: {response.StatusCode}.", orgID);
_logger.LogInformation("Alert API Response Status: {responseStatusCode}.", response.StatusCode);
}
catch (Exception ex)
{
_dataService.WriteEvent(ex, orgID);
_logger.LogError(ex, "Error while sending alert API request.");
}

}
Expand Down
17 changes: 11 additions & 6 deletions Server/API/LoginController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Build.Framework;
using Microsoft.Extensions.Logging;
using Remotely.Server.Hubs;
using Remotely.Server.Models;
using Remotely.Server.Services;
Expand All @@ -24,21 +26,24 @@ public class LoginController : ControllerBase
private readonly IDesktopHubSessionCache _desktopSessionCache;
private readonly SignInManager<RemotelyUser> _signInManager;
private readonly IHubContext<ViewerHub> _viewerHub;
private readonly ILogger<LoginController> _logger;

public LoginController(
SignInManager<RemotelyUser> signInManager,
IDataService dataService,
IApplicationConfig appConfig,
IHubContext<DesktopHub> casterHubContext,
IDesktopHubSessionCache desktopSessionCache,
IHubContext<ViewerHub> viewerHubContext)
IHubContext<ViewerHub> viewerHubContext,
ILogger<LoginController> logger)
{
_signInManager = signInManager;
_dataService = dataService;
_appConfig = appConfig;
_desktopHub = casterHubContext;
_desktopSessionCache = desktopSessionCache;
_viewerHub = viewerHubContext;
_logger = logger;
}

[HttpGet("Logout")]
Expand All @@ -60,7 +65,7 @@ public async Task<IActionResult> Logout()
}
}
await _signInManager.SignOutAsync();
_dataService.WriteEvent($"API logout successful for {HttpContext?.User?.Identity?.Name}.", orgId);
_logger.LogInformation("API logout successful for {userName}.", HttpContext?.User?.Identity?.Name);
return Ok();
}

Expand All @@ -77,20 +82,20 @@ public async Task<IActionResult> Post([FromBody] ApiLogin login)
var result = await _signInManager.PasswordSignInAsync(login.Email, login.Password, false, true);
if (result.Succeeded)
{
_dataService.WriteEvent($"API login successful for {login.Email}.", orgId);
_logger.LogInformation("API login successful for {loginEmail}.", login.Email);
return Ok();
}
else if (result.IsLockedOut)
{
_dataService.WriteEvent($"API login unsuccessful due to lockout for {login.Email}.", orgId);
_logger.LogInformation("API login unsuccessful due to lockout for {loginEmail}.", login.Email);
return Unauthorized("Account is locked.");
}
else if (result.RequiresTwoFactor)
{
_dataService.WriteEvent($"API login unsuccessful due to 2FA for {login.Email}.", orgId);
_logger.LogInformation("API login unsuccessful due to 2FA for {loginEmail}.", login.Email);
return Unauthorized("Account requires two-factor authentication.");
}
_dataService.WriteEvent($"API login unsuccessful due to bad attempt for {login.Email}.", orgId);
_logger.LogInformation("API login unsuccessful due to bad attempt for {loginEmail}.", login.Email);
return BadRequest();
}
}
Expand Down
15 changes: 10 additions & 5 deletions Server/API/RemoteControlController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
using Remotely.Server.Services.RcImplementations;
using Immense.RemoteControl.Server.Abstractions;
using Immense.RemoteControl.Shared.Helpers;
using Microsoft.Build.Framework;
using Microsoft.Extensions.Logging;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

Expand All @@ -32,6 +34,7 @@ public class RemoteControlController : ControllerBase
private readonly IHubEventHandler _hubEvents;
private readonly IDataService _dataService;
private readonly SignInManager<RemotelyUser> _signInManager;
private readonly ILogger<RemoteControlController> _logger;

public RemoteControlController(
SignInManager<RemotelyUser> signInManager,
Expand All @@ -41,7 +44,8 @@ public class RemoteControlController : ControllerBase
IServiceHubSessionCache serviceSessionCache,
IOtpProvider otpProvider,
IHubEventHandler hubEvents,
IApplicationConfig appConfig)
IApplicationConfig appConfig,
ILogger<RemoteControlController> logger)
{
_dataService = dataService;
_serviceHub = serviceHub;
Expand All @@ -51,6 +55,7 @@ public class RemoteControlController : ControllerBase
_otpProvider = otpProvider;
_hubEvents = hubEvents;
_signInManager = signInManager;
_logger = logger;
}

[HttpGet("{deviceID}")]
Expand All @@ -75,20 +80,20 @@ public async Task<IActionResult> Post([FromBody] RemoteControlRequest rcRequest)
if (result.Succeeded &&
_dataService.DoesUserHaveAccessToDevice(rcRequest.DeviceID, _dataService.GetUserByNameWithOrg(rcRequest.Email)))
{
_dataService.WriteEvent($"API login successful for {rcRequest.Email}.", orgId);
_logger.LogInformation("API login successful for {rcRequestEmail}.", rcRequest.Email);
return await InitiateRemoteControl(rcRequest.DeviceID, orgId);
}
else if (result.IsLockedOut)
{
_dataService.WriteEvent($"API login unsuccessful due to lockout for {rcRequest.Email}.", orgId);
_logger.LogInformation("API login successful for {rcRequestEmail}.", rcRequest.Email);
return Unauthorized("Account is locked.");
}
else if (result.RequiresTwoFactor)
{
_dataService.WriteEvent($"API login unsuccessful due to 2FA for {rcRequest.Email}.", orgId);
_logger.LogInformation("API login successful for {rcRequestEmail}.", rcRequest.Email);
return Unauthorized("Account requires two-factor authentication.");
}
_dataService.WriteEvent($"API login unsuccessful due to bad attempt for {rcRequest.Email}.", orgId);
_logger.LogInformation("API login unsuccessful due to bad attempt for {rcRequestEmail}.", rcRequest.Email);
return BadRequest();
}

Expand Down
33 changes: 23 additions & 10 deletions Server/API/ServerLogsController.cs
Original file line number Diff line number Diff line change
@@ -1,33 +1,46 @@
using Microsoft.AspNetCore.Mvc;
using Remotely.Server.Auth;
using Remotely.Server.Services;
using System.Text;
using System.Text.Json;
using System;
using Microsoft.Extensions.Logging;
using Remotely.Server.Services;
using System.IO;
using System.Threading.Tasks;

namespace Remotely.Server.API
{
[Route("api/[controller]")]
[ApiController]
public class ServerLogsController : ControllerBase
{
private readonly IDataService _dataService;
private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions() { WriteIndented = true };
private readonly ILogsManager _logsManager;
private readonly ILogger<ServerLogsController> _logger;

public ServerLogsController(IDataService dataService)
public ServerLogsController(
ILogsManager logsManager,
ILogger<ServerLogsController> logger)
{
_dataService = dataService;
_logsManager = logsManager;
_logger = logger;
}

[ServiceFilter(typeof(ApiAuthorizationFilter))]
[HttpGet("Download")]
public ActionResult Download()
public async Task<IActionResult> Download()
{
Request.Headers.TryGetValue("OrganizationID", out var orgId);
_logger.LogInformation(
"Downloading server logs. Remote IP: {ip}",
HttpContext.Connection.RemoteIpAddress);

var zipFile = await _logsManager.ZipAllLogs();
Response.OnCompleted(() =>
{
Directory.Delete(zipFile.DirectoryName, true);
return Task.CompletedTask;
});

var logs = _dataService.GetAllEventLogs(User.Identity?.Name, orgId);
var fileBytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(logs, _jsonOptions));
return File(fileBytes, "application/octet-stream", "ServerLogs.json");
return File(zipFile.OpenRead(), "application/octet-stream", zipFile.Name);
}
}
}
12 changes: 9 additions & 3 deletions Server/Areas/Identity/Pages/Account/ForgotPassword.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
using Microsoft.AspNetCore.WebUtilities;
using Remotely.Shared.Models;
using Remotely.Server.Services;
using Microsoft.Extensions.Logging;

namespace Remotely.Server.Areas.Identity.Pages.Account
{
Expand All @@ -21,14 +22,18 @@ public class ForgotPasswordModel : PageModel
private readonly UserManager<RemotelyUser> _userManager;
private readonly IEmailSenderEx _emailSender;
private readonly IDataService _dataService;
private readonly ILogger<ForgotPasswordModel> _logger;

public ForgotPasswordModel(UserManager<RemotelyUser> userManager,
public ForgotPasswordModel(
UserManager<RemotelyUser> userManager,
IEmailSenderEx emailSender,
IDataService dataService)
IDataService dataService,
ILogger<ForgotPasswordModel> logger)
{
_userManager = userManager;
_emailSender = emailSender;
_dataService = dataService;
_logger = logger;
}

[BindProperty]
Expand Down Expand Up @@ -62,7 +67,8 @@ public async Task<IActionResult> OnPostAsync()
values: new { area = "Identity", code },
protocol: Request.Scheme);

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

var emailResult = await _emailSender.SendEmailAsync(
Input.Email,
Expand Down

0 comments on commit 0386295

Please sign in to comment.