Compare commits

...

2 Commits

Author SHA1 Message Date
Michele Scandura
73400b5c9f cleanup
All checks were successful
continuous-integration/drone/push Build is passing
2021-09-30 11:19:38 +01:00
Michele Scandura
94f71fc00f small tweaks
All checks were successful
continuous-integration/drone/push Build is passing
2021-09-25 21:03:11 +01:00
16 changed files with 155 additions and 53 deletions

View File

@ -10,11 +10,16 @@ using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Sledgemapper.Api.Core.Entities;
using Sentry;
using Sledgemapper.Api.Models;
using User = Sledgemapper.Api.Core.Entities.User;
namespace Sledgemapper.Api.Controllers
{
// TODO
// introduce refresh token from https://github.com/mohamadlawand087/v8-refreshtokenswithJWT
// and https://dev.to/moe23/refresh-jwt-with-refresh-tokens-in-asp-net-core-5-rest-api-step-by-step-3en5
[Route("[controller]")] // api/authmanagement
[ApiController]
public class AuthManagementController : ControllerBase
@ -117,6 +122,7 @@ namespace Sledgemapper.Api.Controllers
{
Result = true,
Token = jwtToken,
Username = existingUser.Email,
Initials = existingUser.Initials,
Id = existingUser.Id

View File

@ -2,12 +2,13 @@ using MediatR;
using Microsoft.EntityFrameworkCore;
using Sledgemapper.Api.Commands;
using Sledgemapper.Api.Infrastructure.Data;
using Sledgemapper.Shared.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Sentry;
using Session = Sledgemapper.Shared.Entities.Session;
namespace Sledgemapper.Api.Handlers
{
@ -26,18 +27,18 @@ namespace Sledgemapper.Api.Handlers
{
try
{
var user = await _dbcontext.Users.FindAsync(command.UserId);
var user = await _dbcontext.Users.FindAsync(new[] { command.UserId }, cancellationToken: cancellationToken);
_dbcontext.Attach(user);
var campaign = await _dbcontext
.Campaigns
.Where(campaign => campaign.CampaignId == command.CampaignId)
.Include(c => c.InvitedUsers)
.Include(c => c.Maps)
.Include(c => c.Owner)
.Where(campaign => campaign.OwnerId == command.UserId || campaign.InvitedUsers.Contains(user)).FirstAsync();
.Where(campaign => campaign.OwnerId == command.UserId || campaign.InvitedUsers.Contains(user)).FirstAsync(cancellationToken);
@ -49,6 +50,7 @@ namespace Sledgemapper.Api.Handlers
}
catch (Exception ex)
{
SentrySdk.CaptureException(ex);
}
return null;
}

View File

@ -8,6 +8,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Sentry;
namespace Sledgemapper.Api.Handlers
{
@ -26,27 +27,25 @@ namespace Sledgemapper.Api.Handlers
{
try
{
var user = await _dbcontext.Users.FindAsync(command.UserId);
var user = await _dbcontext.Users.FindAsync(new[] { command.UserId }, cancellationToken: cancellationToken);
_dbcontext.Attach(user);
var campaign = await _dbcontext
.Campaigns
.Where(campaign => campaign.CampaignId == command.CampaignId)
.Include(c => c.InvitedUsers)
.Include(c => c.Owner)
.Where(campaign => campaign.OwnerId == command.UserId || campaign.InvitedUsers.Contains(user)).FirstAsync();
.Where(campaign => campaign.OwnerId == command.UserId || campaign.InvitedUsers.Contains(user)).FirstAsync(cancellationToken);
//var campaign = await _dbcontext.Campaigns.Where(campaign => campaign.CampaignId == command.CampaignId && campaign.OwnerId == command.UserId).Include(campaign => campaign.InvitedUsers).FirstAsync();
var players = campaign.InvitedUsers.Select(user => new Player { Initials = user.Initials, UserName = user.UserName , UserId = new Guid(user.Id)}).ToList();
var players = campaign.InvitedUsers.Select(user => new Player { Initials = user.Initials, UserName = user.UserName, UserId = new Guid(user.Id) }).ToList();
return players;
}
catch (Exception ex)
{
SentrySdk.CaptureException(ex);
}
return null;
}

View File

@ -8,6 +8,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Sentry;
namespace Sledgemapper.Api.Handlers
{
@ -38,6 +39,7 @@ namespace Sledgemapper.Api.Handlers
}
catch (Exception ex)
{
SentrySdk.CaptureException(ex);
}
return new List<Campaign>();
}

View File

@ -4,6 +4,7 @@ using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Sentry;
using Sledgemapper.Api.Commands;
using Sledgemapper.Api.Infrastructure.Data;
@ -24,7 +25,7 @@ namespace Sledgemapper.Api.Handlers
{
try
{
var user = await _dbContext.Users.FindAsync(command.UserId);
var user = await _dbContext.Users.FindAsync(new[] { command.UserId }, cancellationToken: cancellationToken);
var campaign = await _dbContext
.Campaigns
@ -46,6 +47,7 @@ namespace Sledgemapper.Api.Handlers
}
catch (Exception ex)
{
SentrySdk.CaptureException(ex);
}
return false;

View File

@ -4,7 +4,8 @@ using Sledgemapper.Api.Infrastructure.Data;
using System;
using System.Threading;
using System.Threading.Tasks;
using Sledgemapper.Api.Core.Entities;
using Sentry;
using User = Sledgemapper.Api.Core.Entities.User;
namespace Sledgemapper.Api.Handlers
{
@ -39,8 +40,7 @@ namespace Sledgemapper.Api.Handlers
}
catch (Exception ex)
{
SentrySdk.CaptureException(ex);
}
return false;
}

View File

@ -3,6 +3,9 @@ using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Sentry;
using Sentry.AspNetCore;
using Sentry.Extensibility;
using Sledgemapper.Api.Infrastructure.Data;
namespace Sledgemapper.Api
@ -11,18 +14,64 @@ namespace Sledgemapper.Api
{
public static void Main(string[] args)
{
var host= CreateHostBuilder(args).Build();
CreateDbIfNotExists(host);
host.Run();
var host = CreateHostBuilder(args).Build();
CreateDbIfNotExists(host);
using (Sentry.SentrySdk.Init(o =>
{
o.Dsn = "https://dbd98432b84b445696dc2996e4e01c90@glitchtip.michelescandura.com/2";
o.MaxBreadcrumbs = 50;
o.Debug = true;
o.StackTraceMode = StackTraceMode.Enhanced;
o.AttachStacktrace = true;
o.Release = "1.0.0-alpha.3";
#if DEBUG
o.Environment = "dev";
#else
o.Environment = "production";
#endif
}))
// {
host.Run();
SentrySdk.CaptureMessage("Backend starting");
//}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseSentry(o =>
{
o.Dsn = "https://dbd98432b84b445696dc2996e4e01c90@glitchtip.michelescandura.com/2";
o.MaxRequestBodySize = RequestSize.Always;
o.MaxBreadcrumbs = 50;
o.Debug = true;
o.StackTraceMode = StackTraceMode.Enhanced;
o.AttachStacktrace = true;
o.Release = "1.0.0-alpha.3";
//o.TracesSampler = ctx =>
//{
// if (string.Equals(ctx.TryGetHttpRoute(), "/Home/Privacy", StringComparison.Ordinal))
// {
// // Collect fewer traces for this page
// return 0.3;
// }
// return 1;
//};
#if DEBUG
o.Environment = "dev";
#else
o.Environment = "production";
#endif
});
webBuilder.UseStartup<Startup>();
});
// public static IHostBuilder CreateHostBuilder(string[] args) =>
// Host.CreateDefaultBuilder(args)
// .ConfigureWebHostDefaults(webBuilder =>
@ -30,21 +79,19 @@ namespace Sledgemapper.Api
// webBuilder.UseStartup<Startup>();
// });
private static void CreateDbIfNotExists(IHost host)
private static void CreateDbIfNotExists(IHost host)
{
using (var scope = host.Services.CreateScope())
using var scope = host.Services.CreateScope();
var services = scope.ServiceProvider;
try
{
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<SledgemapperDbContext>();
// DbInitializer.Initialize(context);
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred creating the DB.");
}
var context = services.GetRequiredService<SledgemapperDbContext>();
// DbInitializer.Initialize(context);
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred creating the DB.");
}
}
}

View File

@ -19,6 +19,8 @@
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="5.0.10" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="5.0.2" />
<PackageReference Include="Sentry" Version="3.9.3" />
<PackageReference Include="Sentry.AspNetCore" Version="3.9.3" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.2" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.12.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.10" />

View File

@ -11,10 +11,12 @@ using Microsoft.AspNetCore.SignalR.Client;
using Polly;
using Polly.Retry;
using Refit;
using Sentry;
using SharpFontInternal;
using Sledgemapper.Messages;
using Sledgemapper.Shared.Entities;
using TinyMessenger;
using Session = Sledgemapper.Shared.Entities.Session;
namespace Sledgemapper
{
@ -141,7 +143,7 @@ namespace Sledgemapper
Connection.On<Player>("NewPlayer", player =>
{
var p = SessionData.Players.FirstOrDefault(m => m.UserId == player.UserId);
if (p is null)
if (p is not null)
{
SessionData.Players.Add(player);
}
@ -299,11 +301,11 @@ namespace Sledgemapper
//_authenticateResponse = await Api.Authenticate(authenticateModel).ConfigureAwait(false);
var data = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(_authenticateResponse));
Program.helper.SaveUnencryptedTokenCache(JsonSerializer.SerializeToUtf8Bytes(_authenticateResponse));
Program.Helper.SaveUnencryptedTokenCache(JsonSerializer.SerializeToUtf8Bytes(_authenticateResponse));
await Connection.StopAsync();
State.Instance.CampaignId=Guid.Empty;
State.Instance.CampaignId = Guid.Empty;
State.Instance.CampaignName = string.Empty;
State.Instance.SessionId = Guid.Empty;
State.Instance.MapId = Guid.Empty;
@ -327,18 +329,30 @@ namespace Sledgemapper
return result;
}
public async Task ResetSignalrConnection()
{
try
{
await Connection.StopAsync();
}
catch (Exception ex)
{
SentrySdk.CaptureException(ex);
}
await Connection.StartAsync();
}
public void CheckLogin()
{
var data = Program.helper.LoadUnencryptedTokenCache();
var data = Program.Helper.LoadUnencryptedTokenCache();
if (data != null && data.Any())
{
try
{
_authenticateResponse = JsonSerializer.Deserialize<AuthenticateResponse>(Encoding.UTF8.GetString(data));
Messenger.Publish(new LoginSuccesfulMessage(this) { UserName = _authenticateResponse.Username, Initials = _authenticateResponse.Initials });
}
catch
{ }
_authenticateResponse = JsonSerializer.Deserialize<AuthenticateResponse>(Encoding.UTF8.GetString(data));
Messenger.Publish(new LoginSuccesfulMessage(this) { UserName = _authenticateResponse.Username, Initials = _authenticateResponse.Initials });
}
}
}

View File

@ -3,13 +3,14 @@ using System.Text;
using Microsoft.Extensions.Configuration;
using Microsoft.Identity.Client;
using Microsoft.Identity.Client.Extensions.Msal;
using Sentry;
namespace Sledgemapper
{
public static class Program
{
private static IConfiguration configuration;
public static MsalCacheHelper helper;
private static IConfiguration _configuration;
public static MsalCacheHelper Helper { get; private set; }
[STAThread]
static void Main()
@ -18,7 +19,7 @@ namespace Sledgemapper
.SetBasePath(System.IO.Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
configuration = builder.Build();
_configuration = builder.Build();
// Loading PublicClientApplicationOptions from the values set on appsettings.json
@ -39,9 +40,26 @@ namespace Sledgemapper
.Build();
// storage = Storage.Create(storageProperties);
helper = MsalCacheHelper.CreateAsync(storageProperties).Result;
Helper = MsalCacheHelper.CreateAsync(storageProperties).Result;
using (Sentry.SentrySdk.Init("https://973ac1606651454ba7a19f642d0a9bc1@glitchtip.michelescandura.com/1"))
using (Sentry.SentrySdk.Init(o =>
{
o.Dsn = "https://973ac1606651454ba7a19f642d0a9bc1@glitchtip.michelescandura.com/1";
//o.Dsn = "https://3a58b39d3d38447a83b647fdb1c68160@o1020733.ingest.sentry.io/5986244";
o.MaxBreadcrumbs = 50;
o.Debug = true;
o.StackTraceMode = StackTraceMode.Enhanced;
o.AttachStacktrace = true;
o.Release = "1.0.0-alpha.3";
o.TracesSampleRate = 1.0;
#if DEBUG
o.Environment = "dev";
#else
o.Environment="production";
#endif
o.ServerName = Settings.Instance.MachineName;
}))
using (var game = new Sledgemapper())
{
Sentry.SentrySdk.CaptureEvent(new Sentry.SentryEvent() { Message = "App starting" });

View File

@ -879,7 +879,7 @@ namespace Sledgemapper
var items = _sessionData.Lines.Values.Union<BaseMapEntity>(_sessionData.Rooms.Values)
.OrderBy(t => t.Timestamp).ToArray();
for (var i = 0; i < items.Count(); i++)
for (var i = 0; i < items.Length; i++)
{
var item = items.ElementAt(i);
if (IsMapElementOffscreen(item)) continue;

View File

@ -140,7 +140,7 @@ namespace Sledgemapper.UI
{
var button = ((TextButton)sender);
Container container = button.Parent;
while (!(container is Window))
while (container is not Window)
{
container = container.Parent;
}

View File

@ -235,6 +235,7 @@ namespace Sledgemapper.UI
MenuCampaignPlayers.Enabled = false;
lblCampaign.Text = "n/a";
lblMap.Text = "n/a";
//await CommunicationManager.ResetSignalrConnection();
CommunicationManager.SessionData.MapEntityAdded -= OnMapEntityAdded;
CommunicationManager.SessionData.MapEntityDeleted -= OnMapEntityDeleted;
lblUsername.Text = $"{obj.Initials}";
@ -267,6 +268,15 @@ namespace Sledgemapper.UI
var serverMap = await CommunicationManager.Api.GetMap(State.Instance.CampaignId, State.Instance.MapId);
if (CommunicationManager.Connection.State != HubConnectionState.Connected)
{
try
{
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
await CommunicationManager.Connection.StartAsync();
UpdateConnectionState(CommunicationManager.Connection);
}

View File

@ -64,7 +64,6 @@ namespace Sledgemapper.UI
private void OnMapSelected(object sender, EventArgs e)
{
var item = sender as ListItem;
var localContent = item.GetParentContentInWindow<Widget>();
var list = item.Parent as Grid;
for (var i = 0; i < list.ChildrenCount; i++)

File diff suppressed because one or more lines are too long

0
legacyDb/test Normal file
View File