From 763321f6b0c9e5d1472de1a442925963149adc0d Mon Sep 17 00:00:00 2001 From: "roi.ezra" Date: Tue, 21 May 2024 09:45:39 +0300 Subject: [PATCH] added more logging --- Mundialito/Configuration/JwtTokenSettings.cs | 13 +++++++ Mundialito/Controllers/BetsController.cs | 14 ++++---- Mundialito/Controllers/GamesController.cs | 36 +++++++++---------- .../Controllers/GeneralBetsController.cs | 29 ++++++++------- Mundialito/Controllers/StadiumsController.cs | 3 +- Mundialito/Controllers/TeamsController.cs | 4 +-- Mundialito/Controllers/UsersController.cs | 18 ++++------ Mundialito/Logic/BetValidator.cs | 10 +++--- Mundialito/Logic/BetsResolver.cs | 12 +++---- Mundialito/Logic/IAdminManagment.cs | 9 ----- Mundialito/Logic/LoggedUserProvider.cs | 28 --------------- Mundialito/Logic/RandomResults.cs | 26 ++++++++------ Mundialito/Logic/TokenService.cs | 22 ++++++------ Mundialito/Mail/EmailSender.cs | 17 +++++---- Mundialito/Program.cs | 3 +- 15 files changed, 112 insertions(+), 132 deletions(-) create mode 100644 Mundialito/Configuration/JwtTokenSettings.cs delete mode 100644 Mundialito/Logic/IAdminManagment.cs delete mode 100644 Mundialito/Logic/LoggedUserProvider.cs diff --git a/Mundialito/Configuration/JwtTokenSettings.cs b/Mundialito/Configuration/JwtTokenSettings.cs new file mode 100644 index 0000000..19adf1e --- /dev/null +++ b/Mundialito/Configuration/JwtTokenSettings.cs @@ -0,0 +1,13 @@ + +namespace Mundialito.Configuration; + +public class JwtTokenSettings +{ + public const string Key = "JwtTokenSettings"; + + public string? ValidIssuer { get; set; } + public string? ValidAudience { get; set; } + public string? SymmetricSecurityKey { get; set; } + public string? JwtRegisteredClaimNamesSub { get; set; } + +} \ No newline at end of file diff --git a/Mundialito/Controllers/BetsController.cs b/Mundialito/Controllers/BetsController.cs index 44091d7..a5da272 100644 --- a/Mundialito/Controllers/BetsController.cs +++ b/Mundialito/Controllers/BetsController.cs @@ -58,7 +58,6 @@ public ActionResult GetBetById(int id) var item = betsRepository.GetBet(id); if (item == null) return NotFound(new ErrorMessage{ Message = string.Format("Bet with id '{0}' not found", id)}); - return Ok(new BetViewModel(item, dateTimeProvider.UTCNow)); } @@ -94,7 +93,7 @@ public async Task> PostBet(NewBetModel bet) return BadRequest(new ErrorMessage{ Message = e.Message}); } var res = betsRepository.InsertBet(newBet); - Trace.TraceInformation("Posting new Bet: {0}", newBet); + logger.LogInformation("Posting new Bet from {}", user.UserName); betsRepository.Save(); bet.BetId = res.BetId; AddLog(ActionType.CREATE, string.Format("Posting new Bet: {0}", res)); @@ -102,6 +101,7 @@ public async Task> PostBet(NewBetModel bet) { SendBetMail(newBet, user); } + logger.LogInformation("Bet os user {} was saved", user.UserName); return Ok(bet); } @@ -130,13 +130,14 @@ public async Task> UpdateBet(int id, UpdateBetModel be } catch (Exception e) { return BadRequest(new ErrorMessage{ Message = e.Message}); } + logger.LogInformation("Updating bet from {}", user.UserName); betsRepository.Save(); - Trace.TraceInformation("Updating Bet: {0}", betToUpdate); AddLog(ActionType.UPDATE, string.Format("Updating Bet: {0}", betToUpdate)); if (ShouldSendMail()) { SendBetMail(betToUpdate, user); } + logger.LogInformation("Bet {} of {} was updated", id, user.UserName); return Ok(new NewBetModel(id, bet)); } @@ -156,10 +157,11 @@ public async Task DeleteBet(int id) } catch (Exception e) { return BadRequest(new ErrorMessage{ Message = e.Message}); } + logger.LogInformation("Deleting bet {} of {}", id, user.UserName); betsRepository.DeleteBet(id); betsRepository.Save(); - Trace.TraceInformation("Deleting Bet {0}", id); AddLog(ActionType.DELETE, string.Format("Deleting Bet: {0}", id)); + logger.LogInformation("Bet {} of {} was deleted", id, user.UserName); return Ok(); } @@ -172,7 +174,7 @@ private void AddLog(ActionType actionType, String message) } catch (Exception e) { - Trace.TraceError("Exception during log. Exception: {0}", e.Message); + logger.LogError("Exception during log. Exception: {0}", e.Message); } } @@ -197,7 +199,7 @@ private void SendBetMail(Bet bet, MundialitoUser user) } catch (Exception ex) { - Trace.TraceError("Exception during mail sending. Exception: {0}", ex.Message); + logger.LogError("Exception during mail sending. Exception: {0}", ex.Message); } } } diff --git a/Mundialito/Controllers/GamesController.cs b/Mundialito/Controllers/GamesController.cs index a75c578..34a0cba 100644 --- a/Mundialito/Controllers/GamesController.cs +++ b/Mundialito/Controllers/GamesController.cs @@ -77,10 +77,8 @@ public ActionResult> GetGameBets(int id) var game = gamesRepository.GetGame(id); if (game == null) return NotFound(new ErrorMessage{ Message = string.Format("Game with id '{0}' not found", id)}); - if (game.IsOpen(dateTimeProvider.UTCNow)) return BadRequest(new ErrorMessage{ Message = String.Format("Game '{0}' is stil open for betting", id)}); - return Ok(betsRepository.GetGameBets(id).Select(item => new BetViewModel(item, dateTimeProvider.UTCNow)).OrderByDescending(bet => bet.Points)); } @@ -89,15 +87,13 @@ public async Task> GetGameUserBet(int id) { var user = await userManager.FindByNameAsync(httpContextAccessor.HttpContext?.User.Identity.Name); if (user == null) - { return Unauthorized(); - } var game = GetGameByID(id); var uid = user.Id; var item = betsRepository.GetGameBets(id).SingleOrDefault(bet => bet.User.Id == uid); if (item == null) { - Trace.TraceInformation("No bet found for game {0} and user {1}, creating empty Bet", game.Result, uid); + logger.LogInformation("No bet found for game {0} and user {1}, creating empty Bet", game.Result, uid); return Ok(new BetViewModel() { BetId = -1, HomeScore = null, AwayScore = null, IsOpenForBetting = true, IsResolved = false, Game = new BetGame() { GameId = id } }); } return Ok(new BetViewModel(item, dateTimeProvider.UTCNow)); @@ -119,13 +115,15 @@ public ActionResult PostGame(NewGameModel game) { return BadRequest(new ErrorMessage{ Message = "Home team and Away team can not be the same team"}); } - var newGame = new Game(); - newGame.HomeTeamId = game.HomeTeam.TeamId; - newGame.AwayTeamId = game.AwayTeam.TeamId; - newGame.StadiumId = game.Stadium.StadiumId; - newGame.Date = game.Date; + var newGame = new Game + { + HomeTeamId = game.HomeTeam.TeamId, + AwayTeamId = game.AwayTeam.TeamId, + StadiumId = game.Stadium.StadiumId, + Date = game.Date + }; var res = gamesRepository.InsertGame(newGame); - Trace.TraceInformation("Posting new Game: {0}", game); + logger.LogInformation("Posting new Game: {0}", game); gamesRepository.Save(); game.GameId = res.GameId; game.IsOpen = true; @@ -145,7 +143,7 @@ public ActionResult PutGame(int id, PutGameModel game) if (item.IsOpen(dateTimeProvider.UTCNow) && (game.HomeScore != null || game.AwayScore != null || game.CornersMark != null || game.CardsMark != null)) return BadRequest(new ErrorMessage{ Message = "Open game can not be updated with results"}); - + logger.LogInformation("Resolving bet {} with {}", id, game); item.AwayScore = game.AwayScore; item.HomeScore = game.HomeScore; item.CardsMark = game.CardsMark; @@ -155,10 +153,11 @@ public ActionResult PutGame(int id, PutGameModel game) if (item.IsBetResolved(dateTimeProvider.UTCNow)) { AddLog(ActionType.UPDATE, String.Format("Will resolve bets of game {0}", item.GameId)); - Trace.TraceInformation("Will reoslve Game {0} bets", id); + logger.LogInformation("Will reoslve Game {0} bets", id); betsResolver.ResolveBets(item); } AddLog(ActionType.UPDATE, String.Format("Updating Game {0}", item)); + logger.LogInformation("Bet {} was resolved", id); return Ok(new PutGameModelResult(item, dateTimeProvider.UTCNow)); } @@ -169,10 +168,11 @@ public IActionResult DeleteGame(int id) var game = gamesRepository.GetGame(id); if (game == null) return NotFound(new ErrorMessage{ Message = string.Format("No such game with id '{0}'", id)}); - Trace.TraceInformation("Deleting Game {0}", id); + logger.LogInformation("Deleting Game {0}", id); gamesRepository.DeleteGame(id); gamesRepository.Save(); AddLog(ActionType.DELETE, String.Format("Deleting Game {0}", id)); + logger.LogInformation("Game {0} was deleted", id); return Ok(); } @@ -194,7 +194,7 @@ private void AddLog(ActionType actionType, String message) } catch (Exception e) { - Trace.TraceError("Exception during log. Exception: {0}", e.Message); + logger.LogError("Exception during log. Exception: {0}", e.Message); } } @@ -207,9 +207,10 @@ private void AddMonkeyBet(Game res) { if (task.Result == null) { - Trace.TraceError("Monkey user {0} was not found, will not add monkey bet", monkeyUserName); + logger.LogError("Monkey user {0} was not found, will not add monkey bet", monkeyUserName); return; } + logger.LogInformation("Adding monkey user bet"); var randomResults = new RandomResults(); var result = randomResults.GetRandomResult(); betsRepository.InsertBet(new Bet() @@ -222,10 +223,9 @@ private void AddMonkeyBet(Game res) CornersMark = randomResults.GetRandomMark() }); betsRepository.Save(); + logger.LogInformation("Monkey bet was saved"); } ); - - } } } diff --git a/Mundialito/Controllers/GeneralBetsController.cs b/Mundialito/Controllers/GeneralBetsController.cs index dc90897..0d753e3 100644 --- a/Mundialito/Controllers/GeneralBetsController.cs +++ b/Mundialito/Controllers/GeneralBetsController.cs @@ -67,7 +67,6 @@ public ActionResult GetUserGeneralBet(string username) var item = generalBetsRepository.GetUserGeneralBet(username); if (item == null) return NotFound(string.Format("User '{0}' dosen't have a general bet yet", username)); - return Ok(new GeneralBetViewModel(item, tournamentTimesUtils.GetGeneralBetsCloseTime())); } @@ -76,9 +75,7 @@ public ActionResult GetGeneralBetById(int id) { var item = generalBetsRepository.GetGeneralBet(id); if (item == null) - { return NotFound(new ErrorMessage { Message = string.Format("General Bet with id '{0}' not found", id)}); - } return Ok(new GeneralBetViewModel(item, tournamentTimesUtils.GetGeneralBetsCloseTime())); } @@ -94,31 +91,31 @@ public async Task> PostBet(NewGeneralBetModel n } var user = await userManager.FindByNameAsync(httpContextAccessor.HttpContext?.User.Identity.Name); if (user == null) - { return Unauthorized(); - } - var generalBet = new GeneralBet(); - generalBet.User = user; - generalBet.WinningTeamId = newBet.WinningTeamId; - generalBet.GoldBootPlayerId = newBet.GoldenBootPlayerId; + var generalBet = new GeneralBet + { + User = user, + WinningTeamId = newBet.WinningTeamId, + GoldBootPlayerId = newBet.GoldenBootPlayerId + }; var res = generalBetsRepository.InsertGeneralBet(generalBet); - Trace.TraceInformation("Posting new General Bet: {0}", generalBet); + logger.LogInformation("Posting new general bet {} from {}", generalBet, user.UserName); generalBetsRepository.Save(); newBet.GeneralBetId = res.GeneralBetId; AddLog(ActionType.CREATE, String.Format("Posting new Generel Bet: {0}", res)); + logger.LogInformation("Saved general bet of {}", user.UserName); return Ok(newBet); } [HttpPut] + [Authorize] public async Task> UpdateBet(int id, UpdateGenralBetModel bet) { if (dateTimeProvider.UTCNow > tournamentTimesUtils.GetGeneralBetsCloseTime()) return BadRequest("General bets are already closed for betting"); var user = await userManager.FindByNameAsync(httpContextAccessor.HttpContext?.User.Identity.Name); if (user == null) - { return Unauthorized(); - } var betToUpdate = generalBetsRepository.GetGeneralBet(id); if (betToUpdate.User.Id != user.Id) { @@ -127,8 +124,9 @@ public async Task> UpdateBet(int id, UpdateGe } betToUpdate.WinningTeamId = bet.WinningTeamId; betToUpdate.GoldBootPlayerId = bet.GoldenBootPlayerId; + logger.LogInformation("Updating general bet of {} with {}", user.UserName, betToUpdate); generalBetsRepository.Save(); - Trace.TraceInformation("Updating General Bet: {0}", betToUpdate); + logger.LogInformation("Updated general bet of {}", user.UserName); AddLog(ActionType.UPDATE, String.Format("Updating new Generel Bet: {0}", betToUpdate)); return bet; } @@ -149,9 +147,10 @@ public IActionResult ResolveGeneralBet(int id, ResolveGeneralBetModel resolvedBe AddLog(ActionType.ERROR, string.Format("General Bet '{0}' dosen't exits", id)); return NotFound(new ErrorMessage { Message = string.Format("General Bet '{0}' dosen't exits", id)}); } - Trace.TraceInformation("Resolved General Bet '{0}' with data: {1}", id, resolvedBet); + logger.LogInformation("Resolving general bet {0} with data: {1}", id, resolvedBet); item.Resolve(resolvedBet.PlayerIsRight, resolvedBet.TeamIsRight); generalBetsRepository.Save(); + logger.LogInformation("Resolved general bet {0}", id); AddLog(ActionType.UPDATE, String.Format("Resolved Generel Bet: {0}", item)); return Ok(); } @@ -180,7 +179,7 @@ private void AddLog(ActionType actionType, String message) } catch (Exception e) { - Trace.TraceError("Exception during log. Exception: {0}", e.Message); + logger.LogError("Exception during log. Exception: {0}", e.Message); } } } diff --git a/Mundialito/Controllers/StadiumsController.cs b/Mundialito/Controllers/StadiumsController.cs index 9d4cb5e..816f4fc 100644 --- a/Mundialito/Controllers/StadiumsController.cs +++ b/Mundialito/Controllers/StadiumsController.cs @@ -63,9 +63,10 @@ public Stadium PutStadium(int id, Stadium stadium) [Authorize(Roles = "Admin")] public void DeleteStadium(int id) { - Trace.TraceInformation("Deleting Stadium {0}", id); + logger.LogInformation("Deleting Stadium {0}", id); stadiumsRepository.DeleteStadium(id); stadiumsRepository.Save(); + logger.LogInformation("Deleted Stadium {0}", id); } } diff --git a/Mundialito/Controllers/TeamsController.cs b/Mundialito/Controllers/TeamsController.cs index 317202c..44a3ca3 100644 --- a/Mundialito/Controllers/TeamsController.cs +++ b/Mundialito/Controllers/TeamsController.cs @@ -32,7 +32,6 @@ public IEnumerable GetAllTeams() public ActionResult GetTeamById(int id) { var item = teamsRepository.GetTeam(id); - if (item == null) return NotFound(new ErrorMessage{ Message = string.Format("Team with id '{0}' not found", id)}); return Ok(item); @@ -71,9 +70,10 @@ public Team PutTeam(int id, Team team) [Authorize(Roles = "Admin")] public void DeleteTeam(int id) { - Trace.TraceInformation("Deleting Team {0}", id); + logger.LogInformation("Deleting Team {0}", id); teamsRepository.DeleteTeam(id); teamsRepository.Save(); + logger.LogInformation("Deleted Team {0}", id); } } diff --git a/Mundialito/Controllers/UsersController.cs b/Mundialito/Controllers/UsersController.cs index 79c7666..f91395b 100644 --- a/Mundialito/Controllers/UsersController.cs +++ b/Mundialito/Controllers/UsersController.cs @@ -57,16 +57,12 @@ public async Task> GetUserByUsername(String username) { var user = await userManager.FindByNameAsync(username); if (user == null) - { return NotFound(new ErrorMessage { Message = string.Format("No such user '{0}'", username) }); - } var userModel = new UserModel(user); betsRepository.GetUserBets(user.UserName).Where(bet => httpContextAccessor.HttpContext?.User.Identity.Name == username || !bet.IsOpenForBetting(dateTimeProvider.UTCNow)).ToList().ForEach(bet => userModel.AddBet(new BetViewModel(bet, dateTimeProvider.UTCNow))); var generalBet = generalBetsRepository.GetUserGeneralBet(username); if (generalBet != null) - { userModel.SetGeneralBet(new GeneralBetViewModel(generalBet, tournamentTimesUtils.GetGeneralBetsCloseTime())); - } return await IsAdmin(userModel); } @@ -80,6 +76,7 @@ public async Task> GetMe() [Authorize(Roles = "Admin")] public IActionResult GeneratePrivateKey(string email) { + logger.LogInformation("Generating private key for {}", email); return Ok(PrivateKeyValidator.GeneratePrivateKey(email)); } @@ -89,10 +86,9 @@ public async Task MakeAdmin(String id) { var user = await userManager.FindByIdAsync(id); if (user == null) - { return NotFound(new ErrorMessage { Message = "User not found" }); - } user.Role = Role.Admin; + logger.LogInformation("Makeing user {} admin", user.UserName); var result = await userManager.UpdateAsync(user); if (!result.Succeeded) { @@ -100,6 +96,7 @@ public async Task MakeAdmin(String id) return BadRequest(ModelState); } AddLog(ActionType.UPDATE, string.Format("Made user {0} admin", id)); + logger.LogInformation("User {} is now admin", user.UserName); return Ok(); } @@ -107,18 +104,17 @@ public async Task MakeAdmin(String id) [Authorize(Roles = "Admin")] public async Task DeleteUser(String id) { - Trace.TraceInformation("Deleting user {0} by {1}", id, httpContextAccessor.HttpContext?.User.Identity.Name); var user = await userManager.FindByIdAsync(id); if (user == null) - { return NotFound(new ErrorMessage { Message = "User not found" }); - } + logger.LogInformation("Deleting user {0} by {1}", id, user.UserName); var result = await userManager.DeleteAsync(user); if (!result.Succeeded) { ModelState.AddModelError("", "Cannot delete user"); return BadRequest(ModelState); } + logger.LogInformation("Deleted user {0}", id); AddLog(ActionType.DELETE, string.Format("Deleted user: {0}", id)); return Ok(); } @@ -127,9 +123,7 @@ private async Task> IsAdmin(UserModel param) { var user = await userManager.FindByIdAsync(param.Id); if (user == null) - { return NotFound(); - } param.IsAdmin = user.Role == Role.Admin; return Ok(param); } @@ -143,7 +137,7 @@ private void AddLog(ActionType actionType, String message) } catch (Exception e) { - Trace.TraceError("Exception during log. Exception: {0}", e.Message); + logger.LogInformation("Exception during log. Exception: {0}", e.Message); } } diff --git a/Mundialito/Logic/BetValidator.cs b/Mundialito/Logic/BetValidator.cs index bfcef85..0c33e1f 100644 --- a/Mundialito/Logic/BetValidator.cs +++ b/Mundialito/Logic/BetValidator.cs @@ -7,20 +7,22 @@ namespace Mundialito.Logic; public class BetValidator : IBetValidator { - private const String ObjectType = "Bet"; + private const string ObjectType = "Bet"; private readonly IGamesRepository gamesRepository; private readonly IBetsRepository betsRepository; private readonly IDateTimeProvider dateTimeProvider; private readonly IActionLogsRepository actionLogsRepository; private readonly IHttpContextAccessor httpContextAccessor; + private readonly ILogger logger; - public BetValidator(IGamesRepository gamesRepository, IBetsRepository betsRepository, IDateTimeProvider dateTimeProvider, IActionLogsRepository actionLogsRepository, IHttpContextAccessor httpContextAccessor) + public BetValidator(ILogger logger, IGamesRepository gamesRepository, IBetsRepository betsRepository, IDateTimeProvider dateTimeProvider, IActionLogsRepository actionLogsRepository, IHttpContextAccessor httpContextAccessor) { this.httpContextAccessor = httpContextAccessor; this.gamesRepository = gamesRepository; this.betsRepository = betsRepository; this.dateTimeProvider = dateTimeProvider; this.actionLogsRepository = actionLogsRepository; + this.logger = logger; } public void ValidateNewBet(Bet bet) @@ -56,7 +58,7 @@ public void ValidateUpdateBet(Bet bet) AddLog(ActionType.ERROR, string.Format("Bet {0} dosen't exist", bet.BetId)); throw new Exception(string.Format("Bet {0} dosen't exist", bet.BetId)); } - if (String.IsNullOrEmpty(bet.UserId)) + if (string.IsNullOrEmpty(bet.UserId)) { AddLog(ActionType.ERROR, string.Format("Updated bet {0} must have user", bet.BetId)); throw new Exception(string.Format("Updated bet {0} must have user", bet.BetId)); @@ -105,7 +107,7 @@ private void AddLog(ActionType actionType, String message) } catch (Exception e) { - Trace.TraceError("Exception during log. Exception: {0}", e.Message); + logger.LogError("Exception during log. Exception: {0}", e.Message); } } } diff --git a/Mundialito/Logic/BetsResolver.cs b/Mundialito/Logic/BetsResolver.cs index 3ca1a80..75c2287 100644 --- a/Mundialito/Logic/BetsResolver.cs +++ b/Mundialito/Logic/BetsResolver.cs @@ -2,31 +2,31 @@ using Mundialito.DAL.Bets; using Mundialito.DAL.Games; using System.Diagnostics; -using System.Security.Claims; namespace Mundialito.Logic; public class BetsResolver : IBetsResolver { - private const String ObjectType = "Bet"; + private const string ObjectType = "Bet"; private readonly IBetsRepository betsRepository; private readonly IDateTimeProvider dateTimeProvider; private readonly IActionLogsRepository actionLogsRepository; private readonly IHttpContextAccessor httpContextAccessor; + private readonly ILogger logger; - public BetsResolver(IBetsRepository betsRepository, IDateTimeProvider dateTimeProvider, IActionLogsRepository actionLogsRepository, IHttpContextAccessor httpContextAccessor) + public BetsResolver(ILogger logger, IBetsRepository betsRepository, IDateTimeProvider dateTimeProvider, IActionLogsRepository actionLogsRepository, IHttpContextAccessor httpContextAccessor) { this.httpContextAccessor= httpContextAccessor; this.betsRepository = betsRepository; this.dateTimeProvider = dateTimeProvider; this.actionLogsRepository = actionLogsRepository; + this.logger = logger; } public void ResolveBets(Game game) { if (!game.IsBetResolved(dateTimeProvider.UTCNow)) throw new ArgumentException(string.Format("Game {0} is not resolved yet", game.GameId)); - var bets = betsRepository.GetGameBets(game.GameId); foreach (Bet bet in bets) { @@ -60,7 +60,7 @@ public void ResolveBets(Game game) else bet.CornersWin = false; bet.Points = points; - Trace.TraceInformation("{0} of {1} got {2} points", bet, game, points); + logger.LogInformation("{0} of {1} got {2} points", bet.BetId, game.GameId, points); AddLog(ActionType.UPDATE, String.Format("Resolved bet {0} with points {1}", bet, points)); } if (bets.Count() > 0) @@ -77,7 +77,7 @@ private void AddLog(ActionType actionType, String message) } catch (Exception e) { - Trace.TraceError("Exception during log. Exception: {0}", e.Message); + logger.LogError("Exception during log. Exception: {0}", e.Message); } } } diff --git a/Mundialito/Logic/IAdminManagment.cs b/Mundialito/Logic/IAdminManagment.cs deleted file mode 100644 index fe17846..0000000 --- a/Mundialito/Logic/IAdminManagment.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Mundialito.Logic; - -public interface IAdminManagment -{ - void MakeAdmin(string userId); - - bool IsAdmin(string userId); -} - diff --git a/Mundialito/Logic/LoggedUserProvider.cs b/Mundialito/Logic/LoggedUserProvider.cs deleted file mode 100644 index 91ae247..0000000 --- a/Mundialito/Logic/LoggedUserProvider.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System.Security.Claims; -using Microsoft.AspNetCore.Identity; -using Mundialito.DAL.Accounts; - -namespace Mundialito.Logic; - -public class LoggedUserProvider : ILoggedUserProvider -{ - private IHttpContextAccessor httpContextAccessor; - private UserManager userManager; - - public LoggedUserProvider(IHttpContextAccessor httpContextAccessor, UserManager userManager) - { - this.httpContextAccessor = httpContextAccessor; - this.userManager = userManager; - - } - - public String UserId - { - get { return httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;} - } - - public String UserName - { - get { return httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.Name).Value;} - } -} diff --git a/Mundialito/Logic/RandomResults.cs b/Mundialito/Logic/RandomResults.cs index 4a1e372..8a3b1b6 100644 --- a/Mundialito/Logic/RandomResults.cs +++ b/Mundialito/Logic/RandomResults.cs @@ -13,18 +13,22 @@ public string GetRandomMark() public KeyValuePair GetRandomResult() { - Dictionary weightsWithZero = new Dictionary(); - weightsWithZero.Add(0, 0.3f); - weightsWithZero.Add(1, 0.4f); - weightsWithZero.Add(2, 0.35f); - weightsWithZero.Add(3, 0.20f); - weightsWithZero.Add(4, 0.1f); + Dictionary weightsWithZero = new Dictionary + { + { 0, 0.3f }, + { 1, 0.4f }, + { 2, 0.35f }, + { 3, 0.20f }, + { 4, 0.1f } + }; - Dictionary weightsNoZero = new Dictionary(); - weightsNoZero.Add(1, 0.4f); - weightsNoZero.Add(2, 0.35f); - weightsNoZero.Add(3, 0.20f); - weightsNoZero.Add(4, 0.1f); + Dictionary weightsNoZero = new Dictionary + { + { 1, 0.4f }, + { 2, 0.35f }, + { 3, 0.20f }, + { 4, 0.1f } + }; var mark = GetRandomMark(); switch (mark) { diff --git a/Mundialito/Logic/TokenService.cs b/Mundialito/Logic/TokenService.cs index 8ba6ee2..f1368d6 100644 --- a/Mundialito/Logic/TokenService.cs +++ b/Mundialito/Logic/TokenService.cs @@ -3,6 +3,8 @@ using System.Security.Claims; using System.Text; using Mundialito.DAL.Accounts; +using Microsoft.Extensions.Options; +using Mundialito.Configuration; namespace Mundialito.Logic; @@ -10,10 +12,12 @@ public class TokenService { private const int ExpirationMinutes = 60 * 24 * 60; private readonly ILogger _logger; + private readonly JwtTokenSettings _config; - public TokenService(ILogger logger) + public TokenService(ILogger logger, IOptions config) { _logger = logger; + _config = config.Value; } public string CreateToken(MundialitoUser user) @@ -25,17 +29,15 @@ public string CreateToken(MundialitoUser user) expiration ); var tokenHandler = new JwtSecurityTokenHandler(); - _logger.LogInformation("JWT Token created"); - return tokenHandler.WriteToken(token); } private JwtSecurityToken CreateJwtToken(List claims, SigningCredentials credentials, DateTime expiration) => new( - new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetSection("JwtTokenSettings")["ValidIssuer"], - new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetSection("JwtTokenSettings")["ValidAudience"], + _config.ValidIssuer, + _config.ValidAudience, claims, expires: expiration, signingCredentials: credentials @@ -43,8 +45,8 @@ private JwtSecurityToken CreateJwtToken(List claims, SigningCredentials c private List CreateClaims(MundialitoUser user) { - var jwtSub = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetSection("JwtTokenSettings")["JwtRegisteredClaimNamesSub"]; - + var jwtSub = _config.JwtRegisteredClaimNamesSub; + _logger.LogInformation("Creating claims for {}", user.UserName); try { var claims = new List @@ -57,20 +59,18 @@ private List CreateClaims(MundialitoUser user) new Claim(ClaimTypes.Email, user.Email), new Claim(ClaimTypes.Role, user.Role.ToString()) }; - return claims; } catch (Exception e) { - Console.WriteLine(e); + _logger.LogError("Failed to create claim: {}", e.Message); throw; } } private SigningCredentials CreateSigningCredentials() { - var symmetricSecurityKey = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetSection("JwtTokenSettings")["SymmetricSecurityKey"]; - + var symmetricSecurityKey = _config.SymmetricSecurityKey; return new SigningCredentials( new SymmetricSecurityKey( Encoding.UTF8.GetBytes(symmetricSecurityKey) diff --git a/Mundialito/Mail/EmailSender.cs b/Mundialito/Mail/EmailSender.cs index 0f8c3bd..09ab88a 100644 --- a/Mundialito/Mail/EmailSender.cs +++ b/Mundialito/Mail/EmailSender.cs @@ -7,8 +7,8 @@ namespace Mundialito.Mail; public class EmailSender : IEmailSender { - private readonly Config _config; - private readonly ILogger _logger; + private readonly Config _config; + private readonly ILogger _logger; public EmailSender(ILogger logger, IOptions config) { @@ -20,12 +20,15 @@ public async void SendEmail(string toEmail, string subject, string messsage) { try { - string connectionString = _config.EmailConnectionString; - // TODO: Skip if empty - _logger.LogInformation($"Will send mail to {toEmail} with connection string {connectionString}"); - EmailClient emailClient = new EmailClient(connectionString); + if (string.IsNullOrEmpty(_config.EmailConnectionString)) + { + _logger.LogInformation("Not sending mail as connection string is not defined in config"); + return; + } + _logger.LogInformation($"Will send mail to {toEmail} with connection string {_config.EmailConnectionString}"); + EmailClient emailClient = new EmailClient(_config.EmailConnectionString); EmailSendOperation emailSendOperation = await emailClient.SendAsync( - Azure.WaitUntil.Completed, + WaitUntil.Completed, _config.FromAddress, toEmail, subject, null, diff --git a/Mundialito/Program.cs b/Mundialito/Program.cs index e61333a..f9c0d58 100644 --- a/Mundialito/Program.cs +++ b/Mundialito/Program.cs @@ -2,7 +2,6 @@ using System.Text.Json.Serialization; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Identity; -using Microsoft.Extensions.Logging.ApplicationInsights; using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi.Models; using Mundialito.Configuration; @@ -25,6 +24,7 @@ // Add services to the container. // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.Configure(builder.Configuration.GetSection(Config.Key)); +builder.Services.Configure(builder.Configuration.GetSection(JwtTokenSettings.Key)); builder.Services.AddControllers().AddJsonOptions(opt => { opt.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); @@ -111,7 +111,6 @@ builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); -builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped();