diff --git a/AlertHawk.Authentication/AlertHawk.Application/Interfaces/IJwtTokenService.cs b/AlertHawk.Authentication/AlertHawk.Application/Interfaces/IJwtTokenService.cs index 54264f37..3127e32d 100644 --- a/AlertHawk.Authentication/AlertHawk.Application/Interfaces/IJwtTokenService.cs +++ b/AlertHawk.Authentication/AlertHawk.Application/Interfaces/IJwtTokenService.cs @@ -4,5 +4,5 @@ namespace AlertHawk.Application.Interfaces; public interface IJwtTokenService { - string GenerateToken(UserDto user); + string GenerateToken(UserDto? user); } \ No newline at end of file diff --git a/AlertHawk.Authentication/AlertHawk.Application/Interfaces/IUserService.cs b/AlertHawk.Authentication/AlertHawk.Application/Interfaces/IUserService.cs index 1c04c23b..1f6d4fa1 100644 --- a/AlertHawk.Authentication/AlertHawk.Application/Interfaces/IUserService.cs +++ b/AlertHawk.Authentication/AlertHawk.Application/Interfaces/IUserService.cs @@ -21,4 +21,6 @@ public interface IUserService Task GetByUsername(string username); Task?> GetAll(); + Task GetUserByToken(string? jwtToken); + Task UpdateUserToken(string token, string username); } \ No newline at end of file diff --git a/AlertHawk.Authentication/AlertHawk.Application/Services/GetOrCreateUserService.cs b/AlertHawk.Authentication/AlertHawk.Application/Services/GetOrCreateUserService.cs index 71944579..c00e5b90 100644 --- a/AlertHawk.Authentication/AlertHawk.Application/Services/GetOrCreateUserService.cs +++ b/AlertHawk.Authentication/AlertHawk.Application/Services/GetOrCreateUserService.cs @@ -7,7 +7,6 @@ namespace AlertHawk.Application.Services; public class GetOrCreateUserService(IUserService userService) : IGetOrCreateUserService { - public async Task GetUserOrCreateUser(ClaimsPrincipal claims) { string? userEmail = ""; @@ -28,6 +27,11 @@ public async Task GetUserOrCreateUser(ClaimsPrincipal claims) userEmail = claims.Claims?.FirstOrDefault(c => c.Type == "preferred_username")?.Value; } + if (string.IsNullOrWhiteSpace(userEmail)) + { + userEmail = claims.Claims?.FirstOrDefault(c => c.Type == "emailaddress")?.Value; + } + var user = await userService.GetByEmail(userEmail); // This is for AD First Login only diff --git a/AlertHawk.Authentication/AlertHawk.Application/Services/JwtTokenService.cs b/AlertHawk.Authentication/AlertHawk.Application/Services/JwtTokenService.cs index e8782e63..51ff1abe 100644 --- a/AlertHawk.Authentication/AlertHawk.Application/Services/JwtTokenService.cs +++ b/AlertHawk.Authentication/AlertHawk.Application/Services/JwtTokenService.cs @@ -12,32 +12,33 @@ namespace AlertHawk.Application.Services; public class JwtTokenService : IJwtTokenService { private readonly string? _secret; - private readonly string? _issuer; - private readonly string? _audience; + private readonly string? _issuers; + private readonly string? _audiences; public JwtTokenService(IConfiguration configuration) { _secret = configuration["Jwt:Key"]; - _issuer = configuration["Jwt:Issuer"]; - _audience = configuration["Jwt:Audience"]; + _issuers = configuration["Jwt:Issuers"]; + _audiences = configuration["Jwt:Audiences"]; } - public string GenerateToken(UserDto user) + public string GenerateToken(UserDto? user) { var claims = new[] { new Claim("id", user.Id.ToString()), - new Claim("username", user.Username), + new Claim("givenname", user.Username), + new Claim("surname", user.Username), new Claim("emailaddress", user.Email), new Claim("isAdmin", user.IsAdmin.ToString()) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_secret ?? throw new InvalidOperationException("Secret key is undefined."))); var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); - + var token = new JwtSecurityToken( - _issuer, - _audience, + _issuers?.Split(",")[0], + _audiences?.Split(",")[0], claims, expires: DateTime.UtcNow.AddHours(1), signingCredentials: credentials); diff --git a/AlertHawk.Authentication/AlertHawk.Application/Services/UserService.cs b/AlertHawk.Authentication/AlertHawk.Application/Services/UserService.cs index 0e6712a4..d4ba7237 100644 --- a/AlertHawk.Authentication/AlertHawk.Application/Services/UserService.cs +++ b/AlertHawk.Authentication/AlertHawk.Application/Services/UserService.cs @@ -76,4 +76,14 @@ public async Task ResetPassword(string username) { return _userRepository.GetAll(); } + + public async Task GetUserByToken(string? jwtToken) + { + return await _userRepository.GetUserByToken(jwtToken); + } + + public async Task UpdateUserToken(string token, string username) + { + await _userRepository.UpdateUserToken(token, username); + } } \ No newline at end of file diff --git a/AlertHawk.Authentication/AlertHawk.Authentication.Domain/Entities/User.cs b/AlertHawk.Authentication/AlertHawk.Authentication.Domain/Entities/User.cs index 5b182fd2..ccecfe47 100644 --- a/AlertHawk.Authentication/AlertHawk.Authentication.Domain/Entities/User.cs +++ b/AlertHawk.Authentication/AlertHawk.Authentication.Domain/Entities/User.cs @@ -10,4 +10,5 @@ public class User public required string Password { get; set; } public required string Salt { get; set; } public bool IsAdmin { get; set; } + public string? Token { get; set; } } \ No newline at end of file diff --git a/AlertHawk.Authentication/AlertHawk.Authentication.Infrastructure/Interfaces/IUserRepository.cs b/AlertHawk.Authentication/AlertHawk.Authentication.Infrastructure/Interfaces/IUserRepository.cs index fc35bd74..9868b1fc 100644 --- a/AlertHawk.Authentication/AlertHawk.Authentication.Infrastructure/Interfaces/IUserRepository.cs +++ b/AlertHawk.Authentication/AlertHawk.Authentication.Infrastructure/Interfaces/IUserRepository.cs @@ -19,4 +19,6 @@ public interface IUserRepository Task GetByUsername(string username); Task?> GetAll(); Task Delete(Guid id); + Task GetUserByToken(string? jwtToken); + Task UpdateUserToken(string token, string username); } \ No newline at end of file diff --git a/AlertHawk.Authentication/AlertHawk.Authentication.Infrastructure/Repositories/UserRepository.cs b/AlertHawk.Authentication/AlertHawk.Authentication.Infrastructure/Repositories/UserRepository.cs index f82d234a..282f5f99 100644 --- a/AlertHawk.Authentication/AlertHawk.Authentication.Infrastructure/Repositories/UserRepository.cs +++ b/AlertHawk.Authentication/AlertHawk.Authentication.Infrastructure/Repositories/UserRepository.cs @@ -59,6 +59,19 @@ public async Task Delete(Guid id) await ExecuteNonQueryAsync(sql, new { Id = id }); } + public async Task GetUserByToken(string? jwtToken) + { + const string sql = "SELECT Username, Email, IsAdmin FROM Users WHERE Token = @jwtToken"; + var user = await ExecuteQueryFirstOrDefaultAsync(sql, new { jwtToken }); + return _mapper.Map(user); + } + + public async Task UpdateUserToken(string token, string username) + { + const string sql = "UPDATE Users SET Token = @token WHERE LOWER(Username) = @username"; + await ExecuteNonQueryAsync(sql, new { token, username }); + } + public async Task Create(UserCreation userCreation) { string checkExistingUserSql = "SELECT Id FROM Users WHERE LOWER(Email) = @Email"; diff --git a/AlertHawk.Authentication/AlertHawk.Authentication.Infrastructure/Utils/TokenUtils.cs b/AlertHawk.Authentication/AlertHawk.Authentication.Infrastructure/Utils/TokenUtils.cs new file mode 100644 index 00000000..ae90cb3e --- /dev/null +++ b/AlertHawk.Authentication/AlertHawk.Authentication.Infrastructure/Utils/TokenUtils.cs @@ -0,0 +1,21 @@ +namespace AlertHawk.Authentication.Infrastructure.Utils; + +public static class TokenUtils +{ + public static string? GetJwtToken(string? token) + { + if (token == null) + { + return null; + } + + string[] tokenParts = token.Split(' '); + if (tokenParts.Length != 2 || !tokenParts[0].Equals("Bearer", StringComparison.OrdinalIgnoreCase)) + { + return null; + } + + string jwtToken = tokenParts[1]; + return jwtToken; + } +} \ No newline at end of file diff --git a/AlertHawk.Authentication/AlertHawk.Authentication.Tests/ControllerTests/AuthControllerTests.cs b/AlertHawk.Authentication/AlertHawk.Authentication.Tests/ControllerTests/AuthControllerTests.cs index 373933a6..c4db6395 100644 --- a/AlertHawk.Authentication/AlertHawk.Authentication.Tests/ControllerTests/AuthControllerTests.cs +++ b/AlertHawk.Authentication/AlertHawk.Authentication.Tests/ControllerTests/AuthControllerTests.cs @@ -14,13 +14,16 @@ public class AuthControllerTests { private readonly Mock _mockUserService; private readonly Mock _mockJwtTokenService; + private readonly Mock _mockGetOrCreateUserService; private readonly AuthController _controller; public AuthControllerTests() { + _mockGetOrCreateUserService = new Mock(); _mockUserService = new Mock(); _mockJwtTokenService = new Mock(); - _controller = new AuthController(_mockUserService.Object, _mockJwtTokenService.Object); + + _controller = new AuthController(_mockUserService.Object, _mockJwtTokenService.Object, _mockGetOrCreateUserService.Object); } [Fact] diff --git a/AlertHawk.Authentication/AlertHawk.Authentication/Controllers/AuthController.cs b/AlertHawk.Authentication/AlertHawk.Authentication/Controllers/AuthController.cs index ecf50372..d915cc28 100644 --- a/AlertHawk.Authentication/AlertHawk.Authentication/Controllers/AuthController.cs +++ b/AlertHawk.Authentication/AlertHawk.Authentication/Controllers/AuthController.cs @@ -1,6 +1,9 @@ using AlertHawk.Application.Interfaces; using AlertHawk.Authentication.Domain.Custom; +using AlertHawk.Authentication.Domain.Dto; using AlertHawk.Authentication.Domain.Entities; +using AlertHawk.Authentication.Infrastructure.Utils; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Sentry; using Swashbuckle.AspNetCore.Annotations; @@ -13,11 +16,42 @@ public class AuthController : ControllerBase { private readonly IUserService _userService; private readonly IJwtTokenService _jwtTokenService; + private readonly IGetOrCreateUserService _getOrCreateUserService; - public AuthController(IUserService userService, IJwtTokenService jwtTokenService) + public AuthController(IUserService userService, IJwtTokenService jwtTokenService, + IGetOrCreateUserService getOrCreateUserService) { _userService = userService; _jwtTokenService = jwtTokenService; + _getOrCreateUserService = getOrCreateUserService; + } + + [HttpPost("refreshToken")] + [SwaggerOperation(Summary = "Refresh User Token")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(Message), StatusCodes.Status400BadRequest)] + public async Task RefreshUserToken() + { + try + { + var jwtToken = TokenUtils.GetJwtToken(Request.Headers["Authorization"].ToString()); + var user = await _userService.GetUserByToken(jwtToken); + + if (user is null) + { + return BadRequest(new Message("Invalid token.")); + } + + var token = _jwtTokenService.GenerateToken(user); + await _userService.UpdateUserToken(token, user.Username.ToLower()); + + return Ok(new { token }); + } + catch (Exception err) + { + SentrySdk.CaptureException(err); + return StatusCode(StatusCodes.Status500InternalServerError, new Message("Something went wrong.")); + } } [HttpPost("login")] @@ -37,6 +71,8 @@ public async Task PostUserAuth([FromBody] UserAuth userAuth) var token = _jwtTokenService.GenerateToken(user); + await _userService.UpdateUserToken(token, user.Username.ToLower()); + return Ok(new { token }); } catch (Exception err) diff --git a/AlertHawk.Authentication/AlertHawk.Authentication/Controllers/UserController.cs b/AlertHawk.Authentication/AlertHawk.Authentication/Controllers/UserController.cs index 7a08e6c5..addd5287 100644 --- a/AlertHawk.Authentication/AlertHawk.Authentication/Controllers/UserController.cs +++ b/AlertHawk.Authentication/AlertHawk.Authentication/Controllers/UserController.cs @@ -8,6 +8,7 @@ namespace AlertHawk.Authentication.Controllers; +[Authorize] [Route("api/[controller]")] [ApiController] public class UserController : Controller @@ -20,14 +21,15 @@ public UserController(IUserService userService, IGetOrCreateUserService getOrCre _userService = userService; _getOrCreateUserService = getOrCreateUserService; } - + + [AllowAnonymous] [HttpPost("create")] [SwaggerOperation(Summary = "Create User")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] public async Task PostUserCreation([FromBody] UserCreation userCreation) { - await IsUserAdmin(); + //await IsUserAdmin(); if (!ModelState.IsValid) { diff --git a/AlertHawk.Authentication/AlertHawk.Authentication/Controllers/UsersMonitorGroupController.cs b/AlertHawk.Authentication/AlertHawk.Authentication/Controllers/UsersMonitorGroupController.cs index 7086c7a2..a3c07911 100644 --- a/AlertHawk.Authentication/AlertHawk.Authentication/Controllers/UsersMonitorGroupController.cs +++ b/AlertHawk.Authentication/AlertHawk.Authentication/Controllers/UsersMonitorGroupController.cs @@ -3,14 +3,13 @@ using AlertHawk.Authentication.Domain.Custom; using AlertHawk.Authentication.Domain.Dto; using AlertHawk.Authentication.Domain.Entities; -using AlertHawk.Authentication.Helpers; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; -using Sentry; using Swashbuckle.AspNetCore.Annotations; namespace AlertHawk.Authentication.Controllers { + [Authorize] [Route("api/[controller]")] [ApiController] public class UsersMonitorGroupController : Controller diff --git a/AlertHawk.Authentication/AlertHawk.Authentication/Program.cs b/AlertHawk.Authentication/AlertHawk.Authentication/Program.cs index 2d7b33f8..e8784197 100644 --- a/AlertHawk.Authentication/AlertHawk.Authentication/Program.cs +++ b/AlertHawk.Authentication/AlertHawk.Authentication/Program.cs @@ -6,7 +6,11 @@ using EasyMemoryCache.Configuration; using Microsoft.OpenApi.Models; using System.Reflection; +using System.Text; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Authorization; using Microsoft.Identity.Web; +using Microsoft.IdentityModel.Tokens; var builder = WebApplication.CreateBuilder(args); @@ -25,46 +29,60 @@ builder.Services.AddDomain(); builder.Services.AddInfrastructure(); -builder.Services.AddAutoMapper((_, config) => -{ - config.AddCollectionMappers(); -}, AppDomain.CurrentDomain.GetAssemblies()); - -//var issuer = configuration["Jwt:Issuer"] ?? throw new ArgumentException("Configuration value for 'Jwt:Issuer' not found."); -//var issuers = configuration["Jwt:Issuers"] ?? throw new ArgumentException("Configuration value for 'Jwt:Issuers' not found."); -//var audience = configuration["Jwt:Audience"] ?? throw new ArgumentException("Configuration value for 'Jwt:Audience' not found."); -//var audiences = configuration["Jwt:Audiences"] ?? throw new ArgumentException("Configuration value for 'Jwt:Audiences' not found."); -//var key = configuration["Jwt:Key"] ?? throw new ArgumentException("Configuration value for 'Jwt:Key' not found."); - -//builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) -// .AddJwtBearer(options => -// { -// options.TokenValidationParameters = new TokenValidationParameters -// { -// ValidateIssuer = true, -// ValidIssuers = issuers.Split(","), -// //ValidIssuer = issuer, -// ValidateAudience = true, -// ValidAudiences = audiences.Split(","), -// //ValidAudience = audience, -// ValidateIssuerSigningKey = true, -// IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)), -// RequireExpirationTime = true, -// ValidateLifetime = true, -// ClockSkew = TimeSpan.Zero, -// }; -// options.UseSecurityTokenValidators = true; -// options.MapInboundClaims = false; -// options.Audience = audience; -// }); - -builder.Services.AddMicrosoftIdentityWebApiAuthentication(configuration, jwtBearerScheme: "AzureAd"); +builder.Services.AddAutoMapper((_, config) => { config.AddCollectionMappers(); }, + AppDomain.CurrentDomain.GetAssemblies()); + +var issuers = configuration["Jwt:Issuers"] ?? + "issuer"; + +var audiences = configuration["Jwt:Audiences"] ?? + "aud"; +var key = configuration["Jwt:Key"] ?? "fakeKey"; + +Console.WriteLine(issuers); + +// Add services to the container +builder.Services.AddAuthentication(options => + { + options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; + }) + .AddJwtBearer("JwtBearer", options => + { + options.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuer = true, + ValidIssuers = issuers.Split(","), + ValidateAudience = true, + ValidAudiences = audiences.Split(","), + ValidateIssuerSigningKey = false, + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)), + RequireExpirationTime = true, + ValidateLifetime = true, + ClockSkew = TimeSpan.Zero, + }; + }) + .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"), jwtBearerScheme: "AzureAd"); + +builder.Services.AddAuthorization(options => +{ + var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder( + "JwtBearer", + "AzureAd" + ); + defaultAuthorizationPolicyBuilder = defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser(); + options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build(); +}); builder.Services.AddSwaggerGen(c => { c.EnableAnnotations(); - c.SwaggerDoc("v1", new OpenApiInfo { Title = "AlertHawk Authentication API", Version = Assembly.GetEntryAssembly()?.GetName().Version?.ToString() }); + c.SwaggerDoc("v1", + new OpenApiInfo + { + Title = "AlertHawk Authentication API", Version = Assembly.GetEntryAssembly()?.GetName().Version?.ToString() + }); c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Name = "Authorization", @@ -113,7 +131,8 @@ c.RouteTemplate = "swagger/{documentName}/swagger.json"; c.PreSerializeFilters.Add((swaggerDoc, httpReq) => { - swaggerDoc.Servers = new List { new OpenApiServer { Url = $"https://{httpReq.Host.Value}{basePath}" } }; + swaggerDoc.Servers = new List + { new OpenApiServer { Url = $"https://{httpReq.Host.Value}{basePath}" } }; }); }); app.UseSwaggerUI(); @@ -128,4 +147,4 @@ app.MapControllers(); -app.Run(); +app.Run(); \ No newline at end of file diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Classes/MonitorAlertService.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Classes/MonitorAlertService.cs index 42250302..8dadb3e8 100644 --- a/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Classes/MonitorAlertService.cs +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Classes/MonitorAlertService.cs @@ -28,9 +28,10 @@ public async Task> GetMonitorAlerts(int? monitorId, in } public async Task GetMonitorAlertsReport(int? monitorId, int? days, string jwtToken, + MonitorEnvironment? environment, ReportType reportType) { - var monitorAlerts = await GetMonitorAlerts(monitorId, days, MonitorEnvironment.All, jwtToken); + var monitorAlerts = await GetMonitorAlerts(monitorId, days, environment, jwtToken); return reportType switch { diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Classes/MonitorGroupService.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Classes/MonitorGroupService.cs index f50aca4d..c991b7ea 100644 --- a/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Classes/MonitorGroupService.cs +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Classes/MonitorGroupService.cs @@ -18,14 +18,16 @@ public class MonitorGroupService : IMonitorGroupService private readonly string _cacheKeyMonitorDayHist = "CacheKeyMonitorDayHist_"; private readonly IMonitorRepository _monitorRepository; private readonly IHttpClientFactory _httpClientFactory; + private readonly IMonitorHistoryRepository _monitorHistoryRepository; public MonitorGroupService(IMonitorGroupRepository monitorGroupRepository, ICaching caching, - IMonitorRepository monitorRepository, IHttpClientFactory httpClientFactory) + IMonitorRepository monitorRepository, IHttpClientFactory httpClientFactory, IMonitorHistoryRepository monitorHistoryRepository) { _monitorGroupRepository = monitorGroupRepository; _caching = caching; _monitorRepository = monitorRepository; _httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory)); + _monitorHistoryRepository = monitorHistoryRepository; } public async Task> GetMonitorGroupList() @@ -84,7 +86,7 @@ public async Task> GetMonitorGroupListByEnvironment(st var data = await _caching.GetOrSetObjectFromCacheAsync(_cacheKeyMonitorDayHist + monitor.Id, 10, () => - _monitorRepository.GetMonitorHistoryByIdAndHours(monitor.Id, 1)); + _monitorHistoryRepository.GetMonitorHistoryByIdAndHours(monitor.Id, 1)); monitor.MonitorStatusDashboard.HistoryData = data; } diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Classes/MonitorHistoryService.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Classes/MonitorHistoryService.cs new file mode 100644 index 00000000..a10215d0 --- /dev/null +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Classes/MonitorHistoryService.cs @@ -0,0 +1,41 @@ +using AlertHawk.Monitoring.Domain.Entities; +using AlertHawk.Monitoring.Domain.Interfaces.Repositories; +using AlertHawk.Monitoring.Domain.Interfaces.Services; +using EasyMemoryCache; + +namespace AlertHawk.Monitoring.Domain.Classes; + +public class MonitorHistoryService : IMonitorHistoryService +{ + private readonly string _monitorHistoryCount = "MonitorHistoryCountKey"; + private readonly ICaching _caching; + private readonly IMonitorHistoryRepository _monitorHistoryRepository; + + public MonitorHistoryService(ICaching caching, IMonitorHistoryRepository monitorHistoryRepository) + { + _caching = caching; + _monitorHistoryRepository = monitorHistoryRepository; + } + + public async Task> GetMonitorHistory(int id) + { + return await _monitorHistoryRepository.GetMonitorHistory(id); + } + + public async Task> GetMonitorHistory(int id, int days) + { + return await _monitorHistoryRepository.GetMonitorHistoryByIdAndDays(id, days); + } + + public async Task DeleteMonitorHistory(int days) + { + await _monitorHistoryRepository.DeleteMonitorHistory(days); + } + + public async Task GetMonitorHistoryCount() + { + var count = await _caching.GetOrSetObjectFromCacheAsync(_monitorHistoryCount, 20, + () => _monitorHistoryRepository.GetMonitorHistoryCount()); + return count; + } +} \ No newline at end of file diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Classes/MonitorNotificationService.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Classes/MonitorNotificationService.cs new file mode 100644 index 00000000..ecd938d3 --- /dev/null +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Classes/MonitorNotificationService.cs @@ -0,0 +1,73 @@ +using AlertHawk.Monitoring.Domain.Entities; +using AlertHawk.Monitoring.Domain.Interfaces.Repositories; +using AlertHawk.Monitoring.Domain.Interfaces.Services; + +namespace AlertHawk.Monitoring.Domain.Classes; + +public class MonitorNotificationService: IMonitorNotificationService +{ + private readonly IMonitorGroupService _monitorGroupService; + private readonly IMonitorNotificationRepository _monitorNotificationRepository; + + public MonitorNotificationService(IMonitorGroupService monitorGroupService, IMonitorNotificationRepository monitorNotificationRepository) + { + _monitorGroupService = monitorGroupService; + _monitorNotificationRepository = monitorNotificationRepository; + } + + public async Task> GetMonitorNotifications(int id) + { + return await _monitorNotificationRepository.GetMonitorNotifications(id); + } + + public async Task AddMonitorNotification(MonitorNotification monitorNotification) + { + await _monitorNotificationRepository.AddMonitorNotification(monitorNotification); + } + + public async Task RemoveMonitorNotification(MonitorNotification monitorNotification) + { + await _monitorNotificationRepository.RemoveMonitorNotification(monitorNotification); + } + + public async Task AddMonitorGroupNotification(MonitorGroupNotification monitorGroupNotification) + { + var monitorList = await _monitorGroupService.GetMonitorGroupById(monitorGroupNotification.MonitorGroupId); + + if (monitorList != null) + { + foreach (var monitor in monitorList.Monitors) + { + var monitorNotification = new MonitorNotification + { + MonitorId = monitor.Id, + NotificationId = monitorGroupNotification.NotificationId + }; + + var notificationExist = await _monitorNotificationRepository.GetMonitorNotifications(monitor.Id); + if (notificationExist.All(x => x.NotificationId != monitorGroupNotification.NotificationId)) + { + await AddMonitorNotification(monitorNotification); + } + } + } + } + + public async Task RemoveMonitorGroupNotification(MonitorGroupNotification monitorGroupNotification) + { + var monitorList = await _monitorGroupService.GetMonitorGroupById(monitorGroupNotification.MonitorGroupId); + + if (monitorList != null) + { + foreach (var monitor in monitorList.Monitors) + { + var monitorNotification = new MonitorNotification + { + MonitorId = monitor.Id, + NotificationId = monitorGroupNotification.NotificationId + }; + await RemoveMonitorNotification(monitorNotification); + } + } + } +} \ No newline at end of file diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Classes/MonitorService.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Classes/MonitorService.cs index 55605e04..c09d1f59 100644 --- a/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Classes/MonitorService.cs +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Classes/MonitorService.cs @@ -19,43 +19,28 @@ public class MonitorService : IMonitorService private readonly string _cacheKeyDashboardList = "MonitorDashboardList"; private readonly IMonitorGroupService _monitorGroupService; private readonly IHttpClientFactory _httpClientFactory; - private readonly string _monitorHistoryCount = "MonitorHistoryCountKey"; + private readonly IMonitorHistoryRepository _monitorHistoryRepository; + private readonly IHttpClientRunner _httpClientRunner; public MonitorService(IMonitorRepository monitorRepository, ICaching caching, - IMonitorGroupService monitorGroupService, IHttpClientFactory httpClientFactory, IHttpClientRunner httpClientRunner) + IMonitorGroupService monitorGroupService, IHttpClientFactory httpClientFactory, + IHttpClientRunner httpClientRunner, IMonitorHistoryRepository monitorHistoryRepository) { _monitorRepository = monitorRepository; _caching = caching; _monitorGroupService = monitorGroupService; _httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory)); _httpClientRunner = httpClientRunner; + _monitorHistoryRepository = monitorHistoryRepository; } - public async Task> GetMonitorNotifications(int id) - { - return await _monitorRepository.GetMonitorNotifications(id); - } - - public async Task> GetMonitorHistory(int id) - { - return await _monitorRepository.GetMonitorHistory(id); - } - - public async Task> GetMonitorHistory(int id, int days) - { - return await _monitorRepository.GetMonitorHistoryByIdAndDays(id, days); - } public async Task> GetMonitorList() { return await _monitorRepository.GetMonitorList(); } - public async Task DeleteMonitorHistory(int days) - { - await _monitorRepository.DeleteMonitorHistory(days); - } public async Task PauseMonitor(int id, bool paused) { @@ -67,7 +52,7 @@ public async Task PauseMonitor(int id, bool paused) { try { - var result = await _monitorRepository.GetMonitorHistoryByIdAndDays(id, 90); + var result = await _monitorHistoryRepository.GetMonitorHistoryByIdAndDays(id, 90); var monitorHistories = result.ToList(); if (!monitorHistories.Any()) { @@ -290,10 +275,10 @@ public async Task CreateMonitorHttp(MonitorHttp monitorHttp) { monitorHttp.Name = monitorHttp.Name.TrimStart(); monitorHttp.Name = monitorHttp.Name.TrimEnd(); - + monitorHttp.UrlToCheck = monitorHttp.UrlToCheck.TrimStart(); monitorHttp.UrlToCheck = monitorHttp.UrlToCheck.TrimEnd(); - + if (monitorHttp!.Headers != null) { monitorHttp.HeadersJson = JsonUtils.ConvertTupleToJson(monitorHttp.Headers); @@ -360,10 +345,10 @@ public async Task UpdateMonitorHttp(MonitorHttp monitorHttp) { monitorHttp.Name = monitorHttp.Name.TrimStart(); monitorHttp.Name = monitorHttp.Name.TrimEnd(); - + monitorHttp.UrlToCheck = monitorHttp.UrlToCheck.TrimStart(); monitorHttp.UrlToCheck = monitorHttp.UrlToCheck.TrimEnd(); - + if (monitorHttp!.Headers != null) { monitorHttp.HeadersJson = JsonUtils.ConvertTupleToJson(monitorHttp.Headers); @@ -399,7 +384,7 @@ public async Task CreateMonitorTcp(MonitorTcp monitorTcp) monitorTcp.IP = monitorTcp.IP.TrimStart(); monitorTcp.IP = monitorTcp.IP.TrimEnd(); - + return await _monitorRepository.CreateMonitorTcp(monitorTcp); } @@ -407,10 +392,10 @@ public async Task UpdateMonitorTcp(MonitorTcp monitorTcp) { monitorTcp.Name = monitorTcp.Name.TrimStart(); monitorTcp.Name = monitorTcp.Name.TrimEnd(); - + monitorTcp.IP = monitorTcp.IP.TrimStart(); monitorTcp.IP = monitorTcp.IP.TrimEnd(); - + await _monitorRepository.UpdateMonitorTcp(monitorTcp); } @@ -436,16 +421,6 @@ public async Task PauseMonitorByGroupId(int groupId, bool paused) } } - public async Task AddMonitorNotification(MonitorNotification monitorNotification) - { - await _monitorRepository.AddMonitorNotification(monitorNotification); - } - - public async Task RemoveMonitorNotification(MonitorNotification monitorNotification) - { - await _monitorRepository.RemoveMonitorNotification(monitorNotification); - } - public async Task> GetMonitorListByTag(string tag) { return await _monitorRepository.GetMonitorListbyTag(tag); @@ -456,53 +431,6 @@ public async Task RemoveMonitorNotification(MonitorNotification monitorNotificat return await _monitorRepository.GetMonitorTagList(); } - public async Task GetMonitorHistoryCount() - { - var count = await _caching.GetOrSetObjectFromCacheAsync(_monitorHistoryCount, 20, - () => _monitorRepository.GetMonitorHistoryCount()); - return count; - } - - public async Task AddMonitorGroupNotification(MonitorGroupNotification monitorGroupNotification) - { - var monitorList = await _monitorGroupService.GetMonitorGroupById(monitorGroupNotification.MonitorGroupId); - - if (monitorList != null) - { - foreach (var monitor in monitorList.Monitors) - { - var monitorNotification = new MonitorNotification - { - MonitorId = monitor.Id, - NotificationId = monitorGroupNotification.NotificationId - }; - - var notificationExist = await _monitorRepository.GetMonitorNotifications(monitor.Id); - if (notificationExist.All(x => x.NotificationId != monitorGroupNotification.NotificationId)) - { - await AddMonitorNotification(monitorNotification); - } - } - } - } - - public async Task RemoveMonitorGroupNotification(MonitorGroupNotification monitorGroupNotification) - { - var monitorList = await _monitorGroupService.GetMonitorGroupById(monitorGroupNotification.MonitorGroupId); - - if (monitorList != null) - { - foreach (var monitor in monitorList.Monitors) - { - var monitorNotification = new MonitorNotification - { - MonitorId = monitor.Id, - NotificationId = monitorGroupNotification.NotificationId - }; - await RemoveMonitorNotification(monitorNotification); - } - } - } public IEnumerable GetMonitorDashboardDataList(List ids) { diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Interfaces/Repositories/IMonitorHistoryRepository.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Interfaces/Repositories/IMonitorHistoryRepository.cs new file mode 100644 index 00000000..2f874e04 --- /dev/null +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Interfaces/Repositories/IMonitorHistoryRepository.cs @@ -0,0 +1,13 @@ +using AlertHawk.Monitoring.Domain.Entities; + +namespace AlertHawk.Monitoring.Domain.Interfaces.Repositories; + +public interface IMonitorHistoryRepository +{ + Task SaveMonitorHistory(MonitorHistory monitorHistory); + Task> GetMonitorHistory(int id); + Task> GetMonitorHistoryByIdAndDays(int id, int days); + Task DeleteMonitorHistory(int days); + Task GetMonitorHistoryCount(); + Task> GetMonitorHistoryByIdAndHours(int id, int hours); +} \ No newline at end of file diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Interfaces/Repositories/IMonitorNotificationRepository.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Interfaces/Repositories/IMonitorNotificationRepository.cs new file mode 100644 index 00000000..09eb1bb2 --- /dev/null +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Interfaces/Repositories/IMonitorNotificationRepository.cs @@ -0,0 +1,10 @@ +using AlertHawk.Monitoring.Domain.Entities; + +namespace AlertHawk.Monitoring.Domain.Interfaces.Repositories; + +public interface IMonitorNotificationRepository +{ + Task AddMonitorNotification(MonitorNotification monitorNotification); + Task RemoveMonitorNotification(MonitorNotification monitorNotification); + Task> GetMonitorNotifications(int id); +} \ No newline at end of file diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Interfaces/Repositories/IMonitorRepository.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Interfaces/Repositories/IMonitorRepository.cs index 4222b0bf..0729cde1 100644 --- a/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Interfaces/Repositories/IMonitorRepository.cs +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Interfaces/Repositories/IMonitorRepository.cs @@ -13,12 +13,7 @@ public interface IMonitorRepository Task GetMonitorById(int id); Task GetHttpMonitorByMonitorId(int id); Task GetTcpMonitorByMonitorId(int id); - Task> GetMonitorNotifications(int id); Task UpdateMonitorStatus(int id, bool status, int daysToExpireCert); - Task SaveMonitorHistory(MonitorHistory monitorHistory); - Task> GetMonitorHistory(int id); - Task> GetMonitorHistoryByIdAndDays(int id, int days); - Task DeleteMonitorHistory(int days); Task PauseMonitor(int id, bool paused); Task CreateMonitorHttp(MonitorHttp monitorHttp); Task> GetMonitorFailureCount(int days); @@ -29,10 +24,6 @@ public interface IMonitorRepository Task CreateMonitorTcp(MonitorTcp monitorTcp); Task UpdateMonitorTcp(MonitorTcp monitorTcp); Task> GetMonitorList(MonitorEnvironment environment); - Task AddMonitorNotification(MonitorNotification monitorNotification); - Task RemoveMonitorNotification(MonitorNotification monitorNotification); - Task> GetMonitorHistoryByIdAndHours(int id, int hours); Task> GetMonitorListbyTag(string Tag); Task> GetMonitorTagList(); - Task GetMonitorHistoryCount(); } \ No newline at end of file diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Interfaces/Services/IMonitorAlertService.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Interfaces/Services/IMonitorAlertService.cs index 295c4015..c15a9b1a 100644 --- a/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Interfaces/Services/IMonitorAlertService.cs +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Interfaces/Services/IMonitorAlertService.cs @@ -6,5 +6,6 @@ public interface IMonitorAlertService { Task> GetMonitorAlerts(int? monitorId, int? days, MonitorEnvironment? environment, string jwtToken); - Task GetMonitorAlertsReport(int? monitorId, int? days, string jwtToken, ReportType reportType); + Task GetMonitorAlertsReport(int? monitorId, int? days, string jwtToken, + MonitorEnvironment? environment, ReportType reportType); } \ No newline at end of file diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Interfaces/Services/IMonitorHistoryService.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Interfaces/Services/IMonitorHistoryService.cs new file mode 100644 index 00000000..3cdb3b35 --- /dev/null +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Interfaces/Services/IMonitorHistoryService.cs @@ -0,0 +1,11 @@ +using AlertHawk.Monitoring.Domain.Entities; + +namespace AlertHawk.Monitoring.Domain.Interfaces.Services; + +public interface IMonitorHistoryService +{ + Task> GetMonitorHistory(int id); + Task> GetMonitorHistory(int id, int days); + Task DeleteMonitorHistory(int days); + Task GetMonitorHistoryCount(); +} \ No newline at end of file diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Interfaces/Services/IMonitorNotificationService.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Interfaces/Services/IMonitorNotificationService.cs new file mode 100644 index 00000000..0931f50a --- /dev/null +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Interfaces/Services/IMonitorNotificationService.cs @@ -0,0 +1,12 @@ +using AlertHawk.Monitoring.Domain.Entities; + +namespace AlertHawk.Monitoring.Domain.Interfaces.Services; + +public interface IMonitorNotificationService +{ + Task> GetMonitorNotifications(int id); + Task AddMonitorNotification(MonitorNotification monitorNotification); + Task RemoveMonitorNotification(MonitorNotification monitorNotification); + Task AddMonitorGroupNotification(MonitorGroupNotification monitorGroupNotification); + Task RemoveMonitorGroupNotification(MonitorGroupNotification monitorGroupNotification); +} \ No newline at end of file diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Interfaces/Services/IMonitorService.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Interfaces/Services/IMonitorService.cs index 03c4172f..c6cda843 100644 --- a/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Interfaces/Services/IMonitorService.cs +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring.Domain/Interfaces/Services/IMonitorService.cs @@ -5,11 +5,7 @@ namespace AlertHawk.Monitoring.Domain.Interfaces.Services; public interface IMonitorService { - Task> GetMonitorNotifications(int id); - Task> GetMonitorHistory(int id); - Task> GetMonitorHistory(int id, int days); Task> GetMonitorList(); - Task DeleteMonitorHistory(int days); Task PauseMonitor(int id, bool paused); Task GetMonitorDashboardData(int id); IEnumerable GetMonitorDashboardDataList(List ids); @@ -25,11 +21,7 @@ public interface IMonitorService Task GetHttpMonitorByMonitorId(int id); Task GetTcpMonitorByMonitorId(int id); Task PauseMonitorByGroupId(int groupId, bool paused); - Task AddMonitorNotification(MonitorNotification monitorNotification); - Task RemoveMonitorNotification(MonitorNotification monitorNotification); + Task> GetMonitorListByTag(string tag); Task> GetMonitorTagList(); - Task GetMonitorHistoryCount(); - Task AddMonitorGroupNotification(MonitorGroupNotification monitorGroupNotification); - Task RemoveMonitorGroupNotification(MonitorGroupNotification monitorGroupNotification); } \ No newline at end of file diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring.Infrastructure/MonitorRunner/HttpClientRunner.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring.Infrastructure/MonitorRunner/HttpClientRunner.cs index abd857c0..b1ffe23d 100644 --- a/AlertHawk.Monitoring/AlertHawk.Monitoring.Infrastructure/MonitorRunner/HttpClientRunner.cs +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring.Infrastructure/MonitorRunner/HttpClientRunner.cs @@ -13,16 +13,18 @@ public class HttpClientRunner : IHttpClientRunner private readonly IHttpClientScreenshot _httpClientScreenshot; private readonly INotificationProducer _notificationProducer; private readonly IMonitorAlertRepository _monitorAlertRepository; + private readonly IMonitorHistoryRepository _monitorHistoryRepository; private int _daysToExpireCert; public int _retryIntervalMilliseconds = 6000; public HttpClientRunner(IMonitorRepository monitorRepository, IHttpClientScreenshot httpClientScreenshot, - INotificationProducer notificationProducer, IMonitorAlertRepository monitorAlertRepository) + INotificationProducer notificationProducer, IMonitorAlertRepository monitorAlertRepository, IMonitorHistoryRepository monitorHistoryRepository) { _monitorRepository = monitorRepository; _httpClientScreenshot = httpClientScreenshot; _notificationProducer = notificationProducer; _monitorAlertRepository = monitorAlertRepository; + _monitorHistoryRepository = monitorHistoryRepository; _retryIntervalMilliseconds = Environment.GetEnvironmentVariable("HTTP_RETRY_INTERVAL_MS") != null ? int.Parse(Environment.GetEnvironmentVariable("HTTP_RETRY_INTERVAL_MS")) : 6000; @@ -66,7 +68,7 @@ public async Task CheckUrlsAsync(MonitorHttp monitorHttp) { await _monitorRepository.UpdateMonitorStatus(monitorHttp.MonitorId, succeeded, _daysToExpireCert); - await _monitorRepository.SaveMonitorHistory(monitorHistory); + await _monitorHistoryRepository.SaveMonitorHistory(monitorHistory); if (!monitorHttp.LastStatus) { @@ -89,7 +91,7 @@ await _monitorRepository.UpdateMonitorStatus(monitorHttp.MonitorId, succeeded, { await _monitorRepository.UpdateMonitorStatus(monitorHttp.MonitorId, succeeded, _daysToExpireCert); - await _monitorRepository.SaveMonitorHistory(monitorHistory); + await _monitorHistoryRepository.SaveMonitorHistory(monitorHistory); // only send notification when goes from online into offline to avoid flood if (monitorHttp.LastStatus) @@ -126,7 +128,7 @@ await _notificationProducer.HandleFailedNotifications(monitorHttp, ResponseMessage = err.Message }; - await _monitorRepository.SaveMonitorHistory(monitorHistory); + await _monitorHistoryRepository.SaveMonitorHistory(monitorHistory); if (monitorHttp .LastStatus) // only send notification when goes from online into offline to avoid flood diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring.Infrastructure/MonitorRunner/TcpClientRunner.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring.Infrastructure/MonitorRunner/TcpClientRunner.cs index 66822372..8a59541c 100644 --- a/AlertHawk.Monitoring/AlertHawk.Monitoring.Infrastructure/MonitorRunner/TcpClientRunner.cs +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring.Infrastructure/MonitorRunner/TcpClientRunner.cs @@ -10,11 +10,13 @@ public class TcpClientRunner : ITcpClientRunner { private readonly INotificationProducer _notificationProducer; private readonly IMonitorRepository _monitorRepository; + private readonly IMonitorHistoryRepository _monitorHistoryRepository; - public TcpClientRunner(IMonitorRepository monitorRepository, INotificationProducer notificationProducer) + public TcpClientRunner(IMonitorRepository monitorRepository, INotificationProducer notificationProducer, IMonitorHistoryRepository monitorHistoryRepository) { _monitorRepository = monitorRepository; _notificationProducer = notificationProducer; + _monitorHistoryRepository = monitorHistoryRepository; } public async Task CheckTcpAsync(MonitorTcp monitorTcp) @@ -42,7 +44,7 @@ public async Task CheckTcpAsync(MonitorTcp monitorTcp) if (isConnected) { - await _monitorRepository.SaveMonitorHistory(monitorHistory); + await _monitorHistoryRepository.SaveMonitorHistory(monitorHistory); await _monitorRepository.UpdateMonitorStatus(monitorTcp.MonitorId, isConnected, 0); if (!monitorTcp.LastStatus) @@ -80,7 +82,7 @@ public async Task CheckTcpAsync(MonitorTcp monitorTcp) HttpVersion = "" }; - await _monitorRepository.SaveMonitorHistory(monitorHistory); + await _monitorHistoryRepository.SaveMonitorHistory(monitorHistory); await _monitorRepository.UpdateMonitorStatus(monitorTcp.MonitorId, isConnected, 0); if (monitorTcp.LastStatus) diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring.Infrastructure/Producers/NotificationProducer.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring.Infrastructure/Producers/NotificationProducer.cs index 47a70843..09b870df 100644 --- a/AlertHawk.Monitoring/AlertHawk.Monitoring.Infrastructure/Producers/NotificationProducer.cs +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring.Infrastructure/Producers/NotificationProducer.cs @@ -11,17 +11,17 @@ namespace AlertHawk.Monitoring.Infrastructure.Producers; public class NotificationProducer: INotificationProducer { private readonly IPublishEndpoint _publishEndpoint; - private readonly IMonitorRepository _monitorRepository; + private readonly IMonitorNotificationRepository _monitorNotificationRepository; - public NotificationProducer(IPublishEndpoint publishEndpoint, IMonitorRepository monitorRepository) + public NotificationProducer(IPublishEndpoint publishEndpoint, IMonitorNotificationRepository monitorNotificationRepository) { _publishEndpoint = publishEndpoint; - _monitorRepository = monitorRepository; + _monitorNotificationRepository = monitorNotificationRepository; } public async Task HandleFailedNotifications(MonitorHttp monitorHttp, string? reasonPhrase) { - var notificationIdList = await _monitorRepository.GetMonitorNotifications(monitorHttp.MonitorId); + var notificationIdList = await _monitorNotificationRepository.GetMonitorNotifications(monitorHttp.MonitorId); Console.WriteLine( $"sending notification Error calling {monitorHttp.UrlToCheck}, Response StatusCode: {monitorHttp.ResponseStatusCode}"); @@ -42,7 +42,7 @@ await _publishEndpoint.Publish(new public async Task HandleSuccessNotifications(MonitorHttp monitorHttp, string? reasonPhrase) { - var notificationIdList = await _monitorRepository.GetMonitorNotifications(monitorHttp.MonitorId); + var notificationIdList = await _monitorNotificationRepository.GetMonitorNotifications(monitorHttp.MonitorId); Console.WriteLine( $"sending success notification calling {monitorHttp.UrlToCheck}, Response StatusCode: {monitorHttp.ResponseStatusCode}"); @@ -63,7 +63,7 @@ await _publishEndpoint.Publish(new public async Task HandleSuccessTcpNotifications(MonitorTcp monitorTcp) { - var notificationIdList = await _monitorRepository.GetMonitorNotifications(monitorTcp.MonitorId); + var notificationIdList = await _monitorNotificationRepository.GetMonitorNotifications(monitorTcp.MonitorId); Console.WriteLine( $"sending success notification calling {monitorTcp.IP} Port: {monitorTcp.Port},"); @@ -82,7 +82,7 @@ await _publishEndpoint.Publish(new public async Task HandleFailedTcpNotifications(MonitorTcp monitorTcp) { - var notificationIdList = await _monitorRepository.GetMonitorNotifications(monitorTcp.MonitorId); + var notificationIdList = await _monitorNotificationRepository.GetMonitorNotifications(monitorTcp.MonitorId); Console.WriteLine( $"sending notification Error calling {monitorTcp.IP} Port: {monitorTcp.Port}, Response: {monitorTcp.Response}"); diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring.Infrastructure/Repositories/Class/MonitorHistoryRepository.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring.Infrastructure/Repositories/Class/MonitorHistoryRepository.cs new file mode 100644 index 00000000..8b5cc6f1 --- /dev/null +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring.Infrastructure/Repositories/Class/MonitorHistoryRepository.cs @@ -0,0 +1,75 @@ +using System.Data; +using System.Data.SqlClient; +using AlertHawk.Monitoring.Domain.Entities; +using AlertHawk.Monitoring.Domain.Interfaces.Repositories; +using Dapper; +using Microsoft.Extensions.Configuration; + +namespace AlertHawk.Monitoring.Infrastructure.Repositories.Class; + +public class MonitorHistoryRepository: RepositoryBase, IMonitorHistoryRepository +{ + private readonly string _connstring; + + public MonitorHistoryRepository(IConfiguration configuration) : base(configuration) + { + _connstring = GetConnectionString(); + } + + public async Task> GetMonitorHistoryByIdAndDays(int id, int days) + { + await using var db = new SqlConnection(_connstring); + string sql = + @$"SELECT MonitorId, Status, TimeStamp, ResponseTime FROM [MonitorHistory] WHERE MonitorId=@id AND TimeStamp >= DATEADD(day, -@days, GETUTCDATE()) ORDER BY TimeStamp DESC"; + return await db.QueryAsync(sql, new { id, days }, commandType: CommandType.Text); + } + + public async Task> GetMonitorHistoryByIdAndHours(int id, int hours) + { + await using var db = new SqlConnection(_connstring); + string sql = + @$"SELECT MonitorId, Status, TimeStamp, StatusCode, ResponseTime, HttpVersion FROM [MonitorHistory] WHERE MonitorId=@id AND TimeStamp >= DATEADD(hour, -@hours, GETUTCDATE()) ORDER BY TimeStamp DESC"; + return await db.QueryAsync(sql, new { id, hours }, commandType: CommandType.Text); + } + + public async Task SaveMonitorHistory(MonitorHistory monitorHistory) + { + await using var db = new SqlConnection(_connstring); + string sql = + @"INSERT INTO [MonitorHistory] (MonitorId, Status, TimeStamp, StatusCode, ResponseTime, HttpVersion, ResponseMessage) VALUES (@MonitorId, @Status, @TimeStamp, @StatusCode, @ResponseTime, @HttpVersion, @ResponseMessage)"; + await db.ExecuteAsync(sql, + new + { + monitorHistory.MonitorId, + monitorHistory.Status, + monitorHistory.TimeStamp, + monitorHistory.StatusCode, + monitorHistory.ResponseTime, + monitorHistory.HttpVersion, + monitorHistory.ResponseMessage + }, commandType: CommandType.Text); + } + + public async Task> GetMonitorHistory(int id) + { + await using var db = new SqlConnection(_connstring); + string sql = + @"SELECT TOP 10000 MonitorId, Status, TimeStamp, StatusCode, ResponseTime, HttpVersion, ResponseMessage FROM [MonitorHistory] WHERE MonitorId=@id ORDER BY TimeStamp DESC"; + return await db.QueryAsync(sql, new { id }, commandType: CommandType.Text); + } + + public async Task DeleteMonitorHistory(int days) + { + await using var db = new SqlConnection(_connstring); + string sql = @"DELETE FROM [MonitorHistory] WHERE TimeStamp < DATEADD(DAY, -@days, GETDATE())"; + await db.QueryAsync(sql, new { days }, commandType: CommandType.Text); + } + + public async Task GetMonitorHistoryCount() + { + await using var db = new SqlConnection(_connstring); + string sql = "SELECT COUNT(*) FROM [MonitorHistory]"; + return await db.ExecuteScalarAsync(sql, commandType: CommandType.Text); + } + +} \ No newline at end of file diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring.Infrastructure/Repositories/Class/MonitorNotificationRepository.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring.Infrastructure/Repositories/Class/MonitorNotificationRepository.cs new file mode 100644 index 00000000..67dc353d --- /dev/null +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring.Infrastructure/Repositories/Class/MonitorNotificationRepository.cs @@ -0,0 +1,43 @@ +using System.Data; +using System.Data.SqlClient; +using AlertHawk.Monitoring.Domain.Entities; +using AlertHawk.Monitoring.Domain.Interfaces.Repositories; +using Dapper; +using Microsoft.Extensions.Configuration; + +namespace AlertHawk.Monitoring.Infrastructure.Repositories.Class; + +public class MonitorNotificationRepository : RepositoryBase, IMonitorNotificationRepository +{ + private readonly string _connstring; + + public MonitorNotificationRepository(IConfiguration configuration) : base(configuration) + { + _connstring = GetConnectionString(); + } + + public async Task> GetMonitorNotifications(int id) + { + await using var db = new SqlConnection(_connstring); + string sql = @"SELECT MonitorId, NotificationId FROM [MonitorNotification] WHERE MonitorId=@id"; + return await db.QueryAsync(sql, new { id }, commandType: CommandType.Text); + } + + public async Task AddMonitorNotification(MonitorNotification monitorNotification) + { + await using var db = new SqlConnection(_connstring); + string sql = + @"INSERT INTO [MonitorNotification] (MonitorId, NotificationId) VALUES (@MonitorId, @NotificationId)"; + await db.ExecuteAsync(sql, new { monitorNotification.MonitorId, monitorNotification.NotificationId }, + commandType: CommandType.Text); + } + + public async Task RemoveMonitorNotification(MonitorNotification monitorNotification) + { + await using var db = new SqlConnection(_connstring); + string sql = + @"DELETE FROM [MonitorNotification] WHERE MonitorId=@MonitorId AND NotificationId=@NotificationId"; + await db.ExecuteAsync(sql, new { monitorNotification.MonitorId, monitorNotification.NotificationId }, + commandType: CommandType.Text); + } +} \ No newline at end of file diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring.Infrastructure/Repositories/Class/MonitorRepository.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring.Infrastructure/Repositories/Class/MonitorRepository.cs index fd596002..49857ec0 100644 --- a/AlertHawk.Monitoring/AlertHawk.Monitoring.Infrastructure/Repositories/Class/MonitorRepository.cs +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring.Infrastructure/Repositories/Class/MonitorRepository.cs @@ -46,23 +46,7 @@ public MonitorRepository(IConfiguration configuration) : base(configuration) return await db.QueryAsync(sql, new { environment }, commandType: CommandType.Text); } - public async Task AddMonitorNotification(MonitorNotification monitorNotification) - { - await using var db = new SqlConnection(_connstring); - string sql = - @"INSERT INTO [MonitorNotification] (MonitorId, NotificationId) VALUES (@MonitorId, @NotificationId)"; - await db.ExecuteAsync(sql, new { monitorNotification.MonitorId, monitorNotification.NotificationId }, - commandType: CommandType.Text); - } - public async Task RemoveMonitorNotification(MonitorNotification monitorNotification) - { - await using var db = new SqlConnection(_connstring); - string sql = - @"DELETE FROM [MonitorNotification] WHERE MonitorId=@MonitorId AND NotificationId=@NotificationId"; - await db.ExecuteAsync(sql, new { monitorNotification.MonitorId, monitorNotification.NotificationId }, - commandType: CommandType.Text); - } public async Task?> GetMonitorListByMonitorGroupIds(List groupMonitorIds, MonitorEnvironment environment) @@ -260,12 +244,6 @@ public async Task> GetMonitorListbyTag(string Tag) return await db.QueryAsync(sql, commandType: CommandType.Text); } - public async Task GetMonitorHistoryCount() - { - await using var db = new SqlConnection(_connstring); - string sql = "SELECT COUNT(*) FROM [MonitorHistory]"; - return await db.ExecuteScalarAsync(sql, commandType: CommandType.Text); - } public async Task GetMonitorById(int id) { @@ -301,14 +279,7 @@ FROM [Monitor] a inner join WHERE MonitorId = @monitorId"; return await db.QueryFirstOrDefaultAsync(sql, new { monitorId }, commandType: CommandType.Text); } - - public async Task> GetMonitorNotifications(int id) - { - await using var db = new SqlConnection(_connstring); - string sql = @"SELECT MonitorId, NotificationId FROM [MonitorNotification] WHERE MonitorId=@id"; - return await db.QueryAsync(sql, new { id }, commandType: CommandType.Text); - } - + public async Task UpdateMonitorStatus(int id, bool status, int daysToExpireCert) { await using var db = new SqlConnection(_connstring); @@ -367,54 +338,7 @@ await db.ExecuteAsync(sqlMonitorHttp, return id; } - public async Task> GetMonitorHistoryByIdAndDays(int id, int days) - { - await using var db = new SqlConnection(_connstring); - string sql = - @$"SELECT MonitorId, Status, TimeStamp, ResponseTime FROM [MonitorHistory] WHERE MonitorId=@id AND TimeStamp >= DATEADD(day, -@days, GETUTCDATE()) ORDER BY TimeStamp DESC"; - return await db.QueryAsync(sql, new { id, days }, commandType: CommandType.Text); - } - - public async Task> GetMonitorHistoryByIdAndHours(int id, int hours) - { - await using var db = new SqlConnection(_connstring); - string sql = - @$"SELECT MonitorId, Status, TimeStamp, StatusCode, ResponseTime, HttpVersion FROM [MonitorHistory] WHERE MonitorId=@id AND TimeStamp >= DATEADD(hour, -@hours, GETUTCDATE()) ORDER BY TimeStamp DESC"; - return await db.QueryAsync(sql, new { id, hours }, commandType: CommandType.Text); - } - - public async Task SaveMonitorHistory(MonitorHistory monitorHistory) - { - await using var db = new SqlConnection(_connstring); - string sql = - @"INSERT INTO [MonitorHistory] (MonitorId, Status, TimeStamp, StatusCode, ResponseTime, HttpVersion, ResponseMessage) VALUES (@MonitorId, @Status, @TimeStamp, @StatusCode, @ResponseTime, @HttpVersion, @ResponseMessage)"; - await db.ExecuteAsync(sql, - new - { - monitorHistory.MonitorId, - monitorHistory.Status, - monitorHistory.TimeStamp, - monitorHistory.StatusCode, - monitorHistory.ResponseTime, - monitorHistory.HttpVersion, - monitorHistory.ResponseMessage - }, commandType: CommandType.Text); - } - - public async Task> GetMonitorHistory(int id) - { - await using var db = new SqlConnection(_connstring); - string sql = - @"SELECT TOP 10000 MonitorId, Status, TimeStamp, StatusCode, ResponseTime, HttpVersion, ResponseMessage FROM [MonitorHistory] WHERE MonitorId=@id ORDER BY TimeStamp DESC"; - return await db.QueryAsync(sql, new { id }, commandType: CommandType.Text); - } - - public async Task DeleteMonitorHistory(int days) - { - await using var db = new SqlConnection(_connstring); - string sql = @"DELETE FROM [MonitorHistory] WHERE TimeStamp < DATEADD(DAY, -@days, GETDATE())"; - await db.QueryAsync(sql, new { days }, commandType: CommandType.Text); - } + public async Task> GetHttpMonitorByIds(List ids) { diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ControllerTests/MonitorAlertControllerTests.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ControllerTests/MonitorAlertControllerTests.cs index 14306c95..6f0f5822 100644 --- a/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ControllerTests/MonitorAlertControllerTests.cs +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ControllerTests/MonitorAlertControllerTests.cs @@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Mvc; using Moq; using Xunit; + namespace AlertHawk.Monitoring.Tests.ControllerTests; public class MonitorAlertControllerTests @@ -51,7 +52,8 @@ public async Task GetMonitorAlerts_ValidToken_ReturnsOk() //TokenUtils.SetJwtToken(validToken); // Mock this method if necessary _mockMonitorAlertService.Setup(service => - service.GetMonitorAlerts(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + service.GetMonitorAlerts(It.IsAny(), It.IsAny(), It.IsAny(), + It.IsAny())) .ReturnsAsync(monitorAlerts); // Act @@ -74,7 +76,7 @@ public async Task GetMonitorAlertsReport_InvalidToken_ReturnsBadRequest() _controller.Request.Headers["Authorization"] = invalidToken; // Act - var result = await _controller.GetMonitorAlertsReport(0, 30, ReportType.Excel); + var result = await _controller.GetMonitorAlertsReport(0, 30, MonitorEnvironment.All, ReportType.Excel); // Assert Assert.IsType(result); @@ -91,10 +93,10 @@ public async Task GetMonitorAlertsReport_InvalidReportType_ReturnsBadRequest() HttpContext = new DefaultHttpContext() }; _controller.Request.Headers["Authorization"] = validToken; - // TokenUtils.SetJwtToken(validToken); // Mock this method if necessary + // TokenUtils.SetJwtToken(validToken); // Mock this method if necessary // Act - var result = await _controller.GetMonitorAlertsReport(0, 30, (ReportType)99); // Invalid ReportType + var result = await _controller.GetMonitorAlertsReport(0, 30, MonitorEnvironment.All, (ReportType)99); // Invalid ReportType // Assert var badRequestResult = Assert.IsType(result); @@ -112,15 +114,16 @@ public async Task GetMonitorAlertsReport_ValidRequest_ReturnsFileResult() HttpContext = new DefaultHttpContext() }; _controller.Request.Headers["Authorization"] = validToken; - // TokenUtils.SetJwtToken(validToken); // Mock this method if necessary + // TokenUtils.SetJwtToken(validToken); // Mock this method if necessary _mockMonitorAlertService.Setup(service => service.GetMonitorAlertsReport(It.IsAny(), It.IsAny(), It.IsAny(), + MonitorEnvironment.All, ReportType.Excel)) .ReturnsAsync(reportStream); // Act - var result = await _controller.GetMonitorAlertsReport(0, 30, ReportType.Excel); + var result = await _controller.GetMonitorAlertsReport(0, 30, MonitorEnvironment.All, ReportType.Excel); // Assert var fileResult = Assert.IsType(result); diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ControllerTests/MonitorHistoryControllerTests.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ControllerTests/MonitorHistoryControllerTests.cs index 29f4c645..fca59eda 100644 --- a/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ControllerTests/MonitorHistoryControllerTests.cs +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ControllerTests/MonitorHistoryControllerTests.cs @@ -1,23 +1,22 @@ -using System.Collections.Generic; -using System.Threading.Tasks; using AlertHawk.Monitoring.Controllers; using AlertHawk.Monitoring.Domain.Entities; using AlertHawk.Monitoring.Domain.Interfaces.Services; -using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Moq; -using Xunit; + namespace AlertHawk.Monitoring.Tests.ControllerTests; public class MonitorHistoryControllerTests { private readonly Mock _mockMonitorService; + private readonly Mock _mockMonitorHistoryService; private readonly MonitorHistoryController _controller; public MonitorHistoryControllerTests() { _mockMonitorService = new Mock(); - _controller = new MonitorHistoryController(_mockMonitorService.Object); + _mockMonitorHistoryService = new Mock(); + _controller = new MonitorHistoryController(_mockMonitorService.Object, _mockMonitorHistoryService.Object); } [Fact] @@ -25,7 +24,7 @@ public async Task GetMonitorHistory_ReturnsOk() { // Arrange var monitorHistory = new List { new MonitorHistory() }; - _mockMonitorService.Setup(service => service.GetMonitorHistory(It.IsAny())) + _mockMonitorHistoryService.Setup(service => service.GetMonitorHistory(It.IsAny())) .ReturnsAsync(monitorHistory); // Act @@ -41,7 +40,7 @@ public async Task GetMonitorHistoryByIdDays_ReturnsOk() { // Arrange var monitorHistory = new List { new MonitorHistory() }; - _mockMonitorService.Setup(service => service.GetMonitorHistory(It.IsAny(), It.IsAny())) + _mockMonitorHistoryService.Setup(service => service.GetMonitorHistory(It.IsAny(), It.IsAny())) .ReturnsAsync(monitorHistory); // Act @@ -93,7 +92,7 @@ public async Task DeleteMonitorHistory_ReturnsOk() // Assert var okResult = Assert.IsType(result); - _mockMonitorService.Verify(service => service.DeleteMonitorHistory(7), Times.Once); + _mockMonitorHistoryService.Verify(service => service.DeleteMonitorHistory(7), Times.Once); } [Fact] @@ -101,7 +100,7 @@ public async Task GetMonitorHistoryCount_ReturnsOk() { // Arrange var count = 100L; - _mockMonitorService.Setup(service => service.GetMonitorHistoryCount()) + _mockMonitorHistoryService.Setup(service => service.GetMonitorHistoryCount()) .ReturnsAsync(count); // Act diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ControllerTests/MonitorNotificationControllerTests.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ControllerTests/MonitorNotificationControllerTests.cs index 2868abfd..9b6b7069 100644 --- a/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ControllerTests/MonitorNotificationControllerTests.cs +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ControllerTests/MonitorNotificationControllerTests.cs @@ -8,12 +8,12 @@ namespace AlertHawk.Monitoring.Tests.ControllerTests; public class MonitorNotificationControllerTests { - private readonly Mock _mockMonitorService; + private readonly Mock _mockMonitorService; private readonly MonitorNotificationController _controller; public MonitorNotificationControllerTests() { - _mockMonitorService = new Mock(); + _mockMonitorService = new Mock(); _controller = new MonitorNotificationController(_mockMonitorService.Object); } diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ControllerTests/MonitorTypeControllerTests.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ControllerTests/MonitorTypeControllerTests.cs index b0ba8b12..40cbb9cc 100644 --- a/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ControllerTests/MonitorTypeControllerTests.cs +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ControllerTests/MonitorTypeControllerTests.cs @@ -1,6 +1,31 @@ +using AlertHawk.Monitoring.Controllers; +using AlertHawk.Monitoring.Domain.Interfaces.Services; +using EasyMemoryCache; +using Moq; + namespace AlertHawk.Monitoring.Tests.ControllerTests; public class MonitorTypeControllerTests { + private readonly Mock _monitorTypeServiceMock; + private readonly Mock _cachingMock; + + public MonitorTypeControllerTests() + { + _monitorTypeServiceMock = new Mock(); + _cachingMock = new Mock(); + } + [Fact] + public async Task Should_Return_Data_From_Health_Check() + { + // Arrange + var controller = new MonitorTypeController(_monitorTypeServiceMock.Object,_cachingMock.Object); + + // Act + var result = await controller.GetMonitorType(); + + // Assert + Assert.NotNull(result); + } } \ No newline at end of file diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ServiceTests/MonitorAlertServiceTests.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ServiceTests/MonitorAlertServiceTests.cs index ccb7b247..2ef150e3 100644 --- a/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ServiceTests/MonitorAlertServiceTests.cs +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ServiceTests/MonitorAlertServiceTests.cs @@ -81,7 +81,9 @@ public async Task GetMonitorAlertsReport_ShouldReturnExcelFile_WhenReportTypeIsE .ReturnsAsync(new List { 1, 2, 3 }); // Act - var result = await _monitorAlertService.GetMonitorAlertsReport(1, 7, "jwtToken", ReportType.Excel); + var result = + await _monitorAlertService.GetMonitorAlertsReport(1, 7, "jwtToken", MonitorEnvironment.All, + ReportType.Excel); // Assert Assert.Equal(excelMemoryStream, result); @@ -95,10 +97,10 @@ public async Task GetMonitorAlertsReport_ShouldReturnEmptyMemoryStream_WhenRepor .ReturnsAsync(new List { 1, 2, 3 }); // Act - var result = await _monitorAlertService.GetMonitorAlertsReport(1, 7, "jwtToken", ReportType.Pdf); + var result = + await _monitorAlertService.GetMonitorAlertsReport(1, 7, "jwtToken", MonitorEnvironment.All, ReportType.Pdf); // Assert Assert.Empty(result.ToArray()); } - } \ No newline at end of file diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ServiceTests/MonitorGroupServiceTests.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ServiceTests/MonitorGroupServiceTests.cs index e213dbb1..52378f40 100644 --- a/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ServiceTests/MonitorGroupServiceTests.cs +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ServiceTests/MonitorGroupServiceTests.cs @@ -22,12 +22,14 @@ public class MonitorGroupServiceTests private readonly Mock _httpClientFactoryMock; private readonly Mock _httpMessageHandlerMock; private readonly MonitorGroupService _monitorGroupService; + private readonly Mock _monitorHistoryRepositoryMock; public MonitorGroupServiceTests() { _monitorGroupRepositoryMock = new Mock(); _cachingMock = new Mock(); _monitorRepositoryMock = new Mock(); + _monitorHistoryRepositoryMock = new Mock(); _httpClientFactoryMock = new Mock(); _httpMessageHandlerMock = new Mock(MockBehavior.Strict); var httpClient = new HttpClient(_httpMessageHandlerMock.Object); @@ -38,7 +40,8 @@ public MonitorGroupServiceTests() _monitorGroupRepositoryMock.Object, _cachingMock.Object, _monitorRepositoryMock.Object, - _httpClientFactoryMock.Object + _httpClientFactoryMock.Object, + _monitorHistoryRepositoryMock.Object ); } @@ -90,7 +93,8 @@ public async Task GetMonitorGroupList_ShouldReturnMonitorGroups_FromRepository() _monitorGroupRepositoryMock.Object, _cachingMock.Object, _monitorRepositoryMock.Object, - _httpClientFactoryMock.Object + _httpClientFactoryMock.Object, + _monitorHistoryRepositoryMock.Object ); // Act diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ServiceTests/MonitorHistoryServiceTests.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ServiceTests/MonitorHistoryServiceTests.cs new file mode 100644 index 00000000..63792c30 --- /dev/null +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ServiceTests/MonitorHistoryServiceTests.cs @@ -0,0 +1,69 @@ +using AlertHawk.Monitoring.Domain.Classes; +using AlertHawk.Monitoring.Domain.Entities; +using AlertHawk.Monitoring.Domain.Interfaces.MonitorRunners; +using AlertHawk.Monitoring.Domain.Interfaces.Repositories; +using AlertHawk.Monitoring.Domain.Interfaces.Services; +using EasyMemoryCache; +using EasyMemoryCache.Configuration; +using Moq; +using Monitor = AlertHawk.Monitoring.Domain.Entities.Monitor; + +namespace AlertHawk.Monitoring.Tests.ServiceTests +{ + public class MonitorHistoryServiceTests + { + private readonly Mock _monitorHistoryRepositoryMock; + private readonly Mock _cachingMock; + private readonly MonitorHistoryService _monitorHistoryService; + + public MonitorHistoryServiceTests() + { + _cachingMock = new Mock(); + _monitorHistoryRepositoryMock = new Mock(); + _monitorHistoryService = new MonitorHistoryService(_cachingMock.Object, _monitorHistoryRepositoryMock.Object); + } + + [Fact] + public async Task GetMonitorHistory_ReturnsHistory() + { + // Arrange + var history = new List { new MonitorHistory() }; + _monitorHistoryRepositoryMock.Setup(repo => repo.GetMonitorHistory(It.IsAny())).ReturnsAsync(history); + + // Act + var result = await _monitorHistoryService.GetMonitorHistory(1); + + // Assert + Assert.Equal(history, result); + } + + [Fact] + public async Task GetMonitorHistoryByDays_ReturnsHistory() + { + // Arrange + var history = new List { new MonitorHistory() }; + _monitorHistoryRepositoryMock + .Setup(repo => repo.GetMonitorHistoryByIdAndDays(It.IsAny(), It.IsAny())) + .ReturnsAsync(history); + + // Act + var result = await _monitorHistoryService.GetMonitorHistory(1, 7); + + // Assert + Assert.Equal(history, result); + } + + [Fact] + public async Task DeleteMonitorHistory_DeletesHistory() + { + // Arrange + var days = 7; + + // Act + await _monitorHistoryService.DeleteMonitorHistory(days); + + // Assert + _monitorHistoryRepositoryMock.Verify(repo => repo.DeleteMonitorHistory(days), Times.Once); + } + } +} \ No newline at end of file diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ServiceTests/MonitorNotificationServiceTests.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ServiceTests/MonitorNotificationServiceTests.cs new file mode 100644 index 00000000..c0061f69 --- /dev/null +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ServiceTests/MonitorNotificationServiceTests.cs @@ -0,0 +1,43 @@ +using AlertHawk.Monitoring.Domain.Classes; +using AlertHawk.Monitoring.Domain.Entities; +using AlertHawk.Monitoring.Domain.Interfaces.MonitorRunners; +using AlertHawk.Monitoring.Domain.Interfaces.Repositories; +using AlertHawk.Monitoring.Domain.Interfaces.Services; +using EasyMemoryCache; +using EasyMemoryCache.Configuration; +using Moq; +using Monitor = AlertHawk.Monitoring.Domain.Entities.Monitor; + +namespace AlertHawk.Monitoring.Tests.ServiceTests +{ + public class MonitorNotificationServiceTests + { + private readonly Mock _monitorNotificationRepositoryMock; + private readonly Mock _monitorGroupServiceMock; + private readonly IMonitorNotificationService _monitorNotificationService; + private readonly Mock _httpClientFactoryMock; + + public MonitorNotificationServiceTests() + { + _monitorNotificationRepositoryMock = new Mock(); + _monitorGroupServiceMock = new Mock(); + _monitorNotificationService = new MonitorNotificationService(_monitorGroupServiceMock.Object, _monitorNotificationRepositoryMock.Object); + _httpClientFactoryMock = new Mock(); + } + + [Fact] + public async Task GetMonitorNotifications_ReturnsNotifications() + { + // Arrange + var notifications = new List { new MonitorNotification() }; + _monitorNotificationRepositoryMock.Setup(repo => repo.GetMonitorNotifications(It.IsAny())) + .ReturnsAsync(notifications); + + // Act + var result = await _monitorNotificationService.GetMonitorNotifications(1); + + // Assert + Assert.Equal(notifications, result); + } + } +} \ No newline at end of file diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ServiceTests/MonitorServiceTests.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ServiceTests/MonitorServiceTests.cs index 30baf700..17cb4589 100644 --- a/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ServiceTests/MonitorServiceTests.cs +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/ServiceTests/MonitorServiceTests.cs @@ -14,65 +14,23 @@ namespace AlertHawk.Monitoring.Tests.ServiceTests public class MonitorServiceTests { private readonly Mock _monitorRepositoryMock; + private readonly Mock _monitorHistoryRepositoryMock; private readonly Mock _cachingMock; - private readonly Mock _monitorGroupServiceMock; - private readonly Mock _httpClientFactoryMock; private readonly Mock _httpClientRunnerMock; + private readonly Mock _httpClientFactoryMock; private readonly MonitorService _monitorService; - + private readonly Mock _monitorGroupServiceMock; public MonitorServiceTests() { + _httpClientFactoryMock = new Mock(); _monitorRepositoryMock = new Mock(); - _cachingMock = new Mock(); + _monitorHistoryRepositoryMock = new Mock(); _monitorGroupServiceMock = new Mock(); - _httpClientFactoryMock = new Mock(); + _cachingMock = new Mock(); _httpClientRunnerMock = new Mock(); - _monitorService = new MonitorService(_monitorRepositoryMock.Object, _cachingMock.Object, - _monitorGroupServiceMock.Object, _httpClientFactoryMock.Object, _httpClientRunnerMock.Object); - } - - [Fact] - public async Task GetMonitorNotifications_ReturnsNotifications() - { - // Arrange - var notifications = new List { new MonitorNotification() }; - _monitorRepositoryMock.Setup(repo => repo.GetMonitorNotifications(It.IsAny())).ReturnsAsync(notifications); - - // Act - var result = await _monitorService.GetMonitorNotifications(1); - - // Assert - Assert.Equal(notifications, result); - } - - [Fact] - public async Task GetMonitorHistory_ReturnsHistory() - { - // Arrange - var history = new List { new MonitorHistory() }; - _monitorRepositoryMock.Setup(repo => repo.GetMonitorHistory(It.IsAny())).ReturnsAsync(history); - - // Act - var result = await _monitorService.GetMonitorHistory(1); - - // Assert - Assert.Equal(history, result); + _monitorService = new MonitorService(_monitorRepositoryMock.Object, _cachingMock.Object, _monitorGroupServiceMock.Object, _httpClientFactoryMock.Object, _httpClientRunnerMock.Object, _monitorHistoryRepositoryMock.Object); } - - [Fact] - public async Task GetMonitorHistoryByDays_ReturnsHistory() - { - // Arrange - var history = new List { new MonitorHistory() }; - _monitorRepositoryMock.Setup(repo => repo.GetMonitorHistoryByIdAndDays(It.IsAny(), It.IsAny())).ReturnsAsync(history); - - // Act - var result = await _monitorService.GetMonitorHistory(1, 7); - - // Assert - Assert.Equal(history, result); - } - + [Fact] public async Task PauseMonitor_UpdatesRepositoryAndInvalidatesCache() { @@ -101,7 +59,7 @@ public async Task GetMonitorDashboardData_ReturnsMonitorDashboard() var monitor = new Monitor() { Id = monitorId, DaysToExpireCert = 30, Name = "Name", HeartBeatInterval = 1, Retries = 0 }; - _monitorRepositoryMock.Setup(repo => repo.GetMonitorHistoryByIdAndDays(monitorId, 90)) + _monitorHistoryRepositoryMock.Setup(repo => repo.GetMonitorHistoryByIdAndDays(monitorId, 90)) .ReturnsAsync(monitorHistory); _monitorRepositoryMock.Setup(repo => repo.GetMonitorById(monitorId)).ReturnsAsync(monitor); _cachingMock.Setup(caching => caching.GetOrSetObjectFromCacheAsync( @@ -127,7 +85,7 @@ public async Task GetMonitorDashboardData_NoHistory_ReturnsEmptyDashboard() // Arrange var monitorId = 1; var monitorHistory = new List(); - _monitorRepositoryMock.Setup(repo => repo.GetMonitorHistoryByIdAndDays(monitorId, 90)) + _monitorHistoryRepositoryMock.Setup(repo => repo.GetMonitorHistoryByIdAndDays(monitorId, 90)) .ReturnsAsync(monitorHistory); // Act @@ -158,19 +116,7 @@ public async Task GetMonitorList_ReturnsMonitorList() // Assert Assert.Equal(monitorList, result); } - - [Fact] - public async Task DeleteMonitorHistory_DeletesHistory() - { - // Arrange - var days = 7; - - // Act - await _monitorService.DeleteMonitorHistory(days); - - // Assert - _monitorRepositoryMock.Verify(repo => repo.DeleteMonitorHistory(days), Times.Once); - } + [Fact] public async Task CreateMonitorHttp_SetsHeadersJsonAndCallsRunner() @@ -258,7 +204,7 @@ public async Task CreateMonitor_SetsHeadersJsonAndCallsRepository() "value") }, MaxRedirects = 0, - UrlToCheck = null, + UrlToCheck = "http://www.google.com", Timeout = 0, HeartBeatInterval = 0, Retries = 0 diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/Startup.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/Startup.cs index 8b54cb58..517a0208 100644 --- a/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/Startup.cs +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring.Tests/Startup.cs @@ -32,10 +32,13 @@ public static void ConfigureServices(IServiceCollection services) services.AddTransient(); services.AddTransient(); services.AddTransient(); - - + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring/Controllers/MonitorAlertController.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring/Controllers/MonitorAlertController.cs index 5fe027e2..73983658 100644 --- a/AlertHawk.Monitoring/AlertHawk.Monitoring/Controllers/MonitorAlertController.cs +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring/Controllers/MonitorAlertController.cs @@ -52,8 +52,8 @@ public async Task GetMonitorAlertsByEnvironment(int? monitorId = [SwaggerOperation(Summary = "Retrieves a list of Monitor Alerts in Excel format")] [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] - [HttpGet("monitorAlertsReport/{monitorId}/{days}/{reportType}")] - public async Task GetMonitorAlertsReport(int? monitorId = 0, int? days = 30, + [HttpGet("monitorAlertsReport/{monitorId}/{days}/{environment}/{reportType}")] + public async Task GetMonitorAlertsReport(int? monitorId = 0, int? days = 30, MonitorEnvironment? environment = MonitorEnvironment.All, ReportType reportType = ReportType.Excel) { var jwtToken = TokenUtils.GetJwtToken(Request.Headers["Authorization"].ToString()); @@ -62,7 +62,7 @@ public async Task GetMonitorAlertsReport(int? monitorId = 0, int? return BadRequest("Invalid Token"); } - var stream = await _monitorAlertService.GetMonitorAlertsReport(monitorId, days, jwtToken, reportType); + var stream = await _monitorAlertService.GetMonitorAlertsReport(monitorId, days, jwtToken, environment, reportType); if (reportType == ReportType.Excel) { diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring/Controllers/MonitorHistoryController.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring/Controllers/MonitorHistoryController.cs index 72a6dda9..6636c31a 100644 --- a/AlertHawk.Monitoring/AlertHawk.Monitoring/Controllers/MonitorHistoryController.cs +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring/Controllers/MonitorHistoryController.cs @@ -12,10 +12,13 @@ namespace AlertHawk.Monitoring.Controllers public class MonitorHistoryController : ControllerBase { private readonly IMonitorService _monitorService; + private readonly IMonitorHistoryService _monitorHistoryService; - public MonitorHistoryController(IMonitorService monitorService) + + public MonitorHistoryController(IMonitorService monitorService, IMonitorHistoryService monitorHistoryService) { _monitorService = monitorService; + _monitorHistoryService = monitorHistoryService; } [SwaggerOperation(Summary = "Retrieves the history of the Monitor, limited to 10k rows")] @@ -23,7 +26,7 @@ public MonitorHistoryController(IMonitorService monitorService) [HttpGet("MonitorHistory/{id}")] public async Task GetMonitorHistory(int id) { - var result = await _monitorService.GetMonitorHistory(id); + var result = await _monitorHistoryService.GetMonitorHistory(id); return Ok(result); } @@ -32,7 +35,7 @@ public async Task GetMonitorHistory(int id) [HttpGet("MonitorHistoryByIdDays/{id}/{days}")] public async Task GetMonitorHistory(int id, int days) { - var result = await _monitorService.GetMonitorHistory(id, days); + var result = await _monitorHistoryService.GetMonitorHistory(id, days); return Ok(result); } @@ -59,16 +62,16 @@ public IActionResult GetMonitorDashboardDataList([FromBody] List ids) [HttpDelete] public async Task DeleteMonitorHistory(int days) { - await _monitorService.DeleteMonitorHistory(days); + await _monitorHistoryService.DeleteMonitorHistory(days); return Ok(); } - + [SwaggerOperation(Summary = "Monitor History count")] [ProducesResponseType(typeof(long), StatusCodes.Status200OK)] [HttpGet("GetMonitorHistoryCount")] public async Task GetMonitorHistoryCount() { - var result = await _monitorService.GetMonitorHistoryCount(); + var result = await _monitorHistoryService.GetMonitorHistoryCount(); return Ok(result); } } diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring/Controllers/MonitorNotificationController.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring/Controllers/MonitorNotificationController.cs index 8b9dc237..bd45e76c 100644 --- a/AlertHawk.Monitoring/AlertHawk.Monitoring/Controllers/MonitorNotificationController.cs +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring/Controllers/MonitorNotificationController.cs @@ -13,11 +13,11 @@ namespace AlertHawk.Monitoring.Controllers [Authorize] public class MonitorNotificationController : ControllerBase { - private readonly IMonitorService _monitorService; + private readonly IMonitorNotificationService _monitorNotificationService; - public MonitorNotificationController(IMonitorService monitorService) + public MonitorNotificationController(IMonitorNotificationService monitorNotificationService) { - _monitorService = monitorService; + _monitorNotificationService = monitorNotificationService; } [SwaggerOperation(Summary = "Retrieves a List of all Notifications by Monitor")] @@ -25,7 +25,7 @@ public MonitorNotificationController(IMonitorService monitorService) [HttpGet("monitorNotifications/{id}")] public async Task GetMonitorNotification(int id) { - var result = await _monitorService.GetMonitorNotifications(id); + var result = await _monitorNotificationService.GetMonitorNotifications(id); return Ok(result); } @@ -34,14 +34,14 @@ public async Task GetMonitorNotification(int id) [HttpPost("addMonitorNotification")] public async Task AddMonitorNotification([FromBody] MonitorNotification monitorNotification) { - var notifications = await _monitorService.GetMonitorNotifications(monitorNotification.MonitorId); + var notifications = await _monitorNotificationService.GetMonitorNotifications(monitorNotification.MonitorId); if (notifications.Any(x => x.NotificationId == monitorNotification.NotificationId)) { return BadRequest("Notification already exists for this monitor"); } - await _monitorService.AddMonitorNotification(monitorNotification); + await _monitorNotificationService.AddMonitorNotification(monitorNotification); return Ok(); } @@ -50,7 +50,7 @@ public async Task AddMonitorNotification([FromBody] MonitorNotifi [HttpPost("removeMonitorNotification")] public async Task RemoveMonitorNotification([FromBody] MonitorNotification monitorNotification) { - await _monitorService.RemoveMonitorNotification(monitorNotification); + await _monitorNotificationService.RemoveMonitorNotification(monitorNotification); return Ok(); } @@ -60,7 +60,7 @@ public async Task RemoveMonitorNotification([FromBody] MonitorNot public async Task AddMonitorGroupNotification( [FromBody] MonitorGroupNotification monitorGroupNotification) { - await _monitorService.AddMonitorGroupNotification(monitorGroupNotification); + await _monitorNotificationService.AddMonitorGroupNotification(monitorGroupNotification); return Ok(); } @@ -70,7 +70,7 @@ public async Task AddMonitorGroupNotification( public async Task RemoveMonitorGroupNotification( [FromBody] MonitorGroupNotification monitorGroupNotification) { - await _monitorService.RemoveMonitorGroupNotification(monitorGroupNotification); + await _monitorNotificationService.RemoveMonitorGroupNotification(monitorGroupNotification); return Ok(); } } diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring/Program.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring/Program.cs index afc75e4b..2982c0f2 100644 --- a/AlertHawk.Monitoring/AlertHawk.Monitoring/Program.cs +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring/Program.cs @@ -19,10 +19,15 @@ using System.Net.Security; using System.Reflection; using System.Security.Cryptography.X509Certificates; +using System.Text; using System.Text.Json; using System.Text.Json.Serialization; +using AlertHawk.Monitoring; using AlertHawk.Monitoring.Infrastructure.Utils; using Hangfire.InMemory; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Authorization; +using Microsoft.IdentityModel.Tokens; var builder = WebApplication.CreateBuilder(args); builder.WebHost.UseSentry(options => @@ -69,12 +74,49 @@ }); }); -var azureEnabled = Environment.GetEnvironmentVariable("AZURE_AD_AUTH_ENABLED", EnvironmentVariableTarget.Process) ?? - "true"; -if (azureEnabled == "true") +var issuers = configuration["Jwt:Issuers"] ?? + "issuer"; + +var audiences = configuration["Jwt:Audiences"] ?? + "aud"; + +var key = configuration["Jwt:Key"] ?? "fakeKey"; + +Console.WriteLine(issuers); + +// Add services to the container +builder.Services.AddAuthentication(options => + { + options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; + }) + .AddJwtBearer("JwtBearer", options => + { + options.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuer = true, + ValidIssuers = issuers.Split(","), + ValidateAudience = true, + ValidAudiences = audiences.Split(","), + ValidateIssuerSigningKey = false, + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)), + RequireExpirationTime = true, + ValidateLifetime = true, + ClockSkew = TimeSpan.Zero, + }; + }) + .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"), jwtBearerScheme: "AzureAd"); + +builder.Services.AddAuthorization(options => { - builder.Services.AddMicrosoftIdentityWebApiAuthentication(configuration, jwtBearerScheme: "AzureAd"); -} + var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder( + "JwtBearer", + "AzureAd" + ); + defaultAuthorizationPolicyBuilder = defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser(); + options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build(); +}); + builder.Services.AddHangfire(config => config.UseInMemoryStorage(new InMemoryStorageOptions { @@ -84,22 +126,8 @@ builder.Services.AddEasyCache(configuration.GetSection("CacheSettings").Get()); -builder.Services.AddTransient(); -builder.Services.AddTransient(); -builder.Services.AddTransient(); -builder.Services.AddTransient(); -builder.Services.AddTransient(); -builder.Services.AddTransient(); -builder.Services.AddTransient(); - -builder.Services.AddTransient(); -builder.Services.AddTransient(); -builder.Services.AddTransient(); -builder.Services.AddTransient(); -builder.Services.AddTransient(); -builder.Services.AddTransient(); -builder.Services.AddTransient(); -builder.Services.AddTransient(); +builder.Services.AddCustomServices(); +builder.Services.AddCustomRepositories(); builder.Services.AddTransient(); builder.Services.AddTransient(); diff --git a/AlertHawk.Monitoring/AlertHawk.Monitoring/ServiceCollectionExtentions.cs b/AlertHawk.Monitoring/AlertHawk.Monitoring/ServiceCollectionExtentions.cs new file mode 100644 index 00000000..4b415102 --- /dev/null +++ b/AlertHawk.Monitoring/AlertHawk.Monitoring/ServiceCollectionExtentions.cs @@ -0,0 +1,44 @@ +using System.Diagnostics.CodeAnalysis; +using AlertHawk.Monitoring.Domain.Classes; +using AlertHawk.Monitoring.Domain.Interfaces.Repositories; +using AlertHawk.Monitoring.Domain.Interfaces.Services; +using AlertHawk.Monitoring.Infrastructure.MonitorManager; +using AlertHawk.Monitoring.Infrastructure.Repositories.Class; + +namespace AlertHawk.Monitoring +{ + [ExcludeFromCodeCoverage] + public static class ServiceCollectionExtensions + { + public static IServiceCollection AddCustomServices(this IServiceCollection services) + { + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + + return services; + } + + public static IServiceCollection AddCustomRepositories(this IServiceCollection services) + { + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + + return services; + } + } +} diff --git a/AlertHawk.Notification/AlertHawk.Notification/Program.cs b/AlertHawk.Notification/AlertHawk.Notification/Program.cs index b741e58a..6bda0ccc 100644 --- a/AlertHawk.Notification/AlertHawk.Notification/Program.cs +++ b/AlertHawk.Notification/AlertHawk.Notification/Program.cs @@ -5,12 +5,16 @@ using EasyMemoryCache.Configuration; using System.Diagnostics.CodeAnalysis; using System.Reflection; +using System.Text; using AlertHawk.Notification; using AlertHawk.Notification.Domain.Interfaces.Notifiers; using AlertHawk.Notification.Helpers; using AlertHawk.Notification.Infrastructure.Notifiers; using MassTransit; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Authorization; using Microsoft.Identity.Web; +using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi.Models; using SharedModels; @@ -102,12 +106,48 @@ } ); -var azureEnabled = Environment.GetEnvironmentVariable("AZURE_AD_AUTH_ENABLED", EnvironmentVariableTarget.Process) ?? - "true"; -if (azureEnabled == "true") +var issuers = configuration["Jwt:Issuers"] ?? + "issuer"; + +var audiences = configuration["Jwt:Audiences"] ?? + "aud"; + +var key = configuration["Jwt:Key"] ?? "fakeKey"; + +Console.WriteLine(issuers); + +// Add services to the container +builder.Services.AddAuthentication(options => + { + options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; + }) + .AddJwtBearer("JwtBearer", options => + { + options.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuer = true, + ValidIssuers = issuers.Split(","), + ValidateAudience = true, + ValidAudiences = audiences.Split(","), + ValidateIssuerSigningKey = false, + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)), + RequireExpirationTime = true, + ValidateLifetime = true, + ClockSkew = TimeSpan.Zero, + }; + }) + .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"), jwtBearerScheme: "AzureAd"); + +builder.Services.AddAuthorization(options => { - builder.Services.AddMicrosoftIdentityWebApiAuthentication(configuration, jwtBearerScheme: "AzureAd"); -} + var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder( + "JwtBearer", + "AzureAd" + ); + defaultAuthorizationPolicyBuilder = defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser(); + options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build(); +}); var app = builder.Build();