credentials storage, bug fixing
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Michele Scandura 2021-09-23 12:29:40 +01:00
parent 333c6c4046
commit 3d0450efff
12 changed files with 134 additions and 26 deletions

View File

@ -10,6 +10,7 @@ namespace Sledgemapper.Api.Commands
public double Timestamp { get; private set; }
public string CampaignName { get; private set; }
public string UserId { get; private set; }
public Guid CampaignId { get; private set; }
public GetCampaignPlayersCommand(string campaingName, string userId)
{
@ -17,5 +18,12 @@ namespace Sledgemapper.Api.Commands
CampaignName = campaingName;
UserId = userId;
}
public GetCampaignPlayersCommand(Guid campaignId, string userId)
{
Timestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds();
CampaignId = campaignId;
UserId = userId;
}
}
}

View File

@ -57,7 +57,7 @@ namespace Sledgemapper.Api.Controllers
[HttpGet]
[Route("{campaignName}/players")]
public async Task<List<Player>> GetPlayers(string campaignName)
public async Task<List<Player>> GetPlayers(Guid campaignName)
{
var result = await _mediator.Send(new GetCampaignPlayersCommand(campaignName, UserId));
return result;

View File

@ -29,9 +29,9 @@ namespace Sledgemapper.Api.Handlers
var user = await _dbcontext.Users.FindAsync(command.UserId);
_dbcontext.Attach(user);
var campaign = await _dbcontext.Campaigns.Where(campaign => campaign.CampaignName == command.CampaignName && campaign.OwnerId == command.UserId).Include(campaign => campaign.InvitedUsers).FirstAsync();
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 }).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)

View File

@ -5,7 +5,6 @@ using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
using Sledgemapper.Api.Models;
using Sledgemapper.Api.Commands;
using Sledgemapper.Api.Core.Entities;
using Session = Sledgemapper.Shared.Entities.Session;
@ -20,11 +19,10 @@ namespace Sledgemapper.Api.Handlers
public async Task<Session> Handle(GetMapSnapshotCommand notification, CancellationToken cancellationToken)
{
Snapshot snapshot;
double timestamp;
Session mapSession;
var session = _dbcontext.Sessions.First(m => m.SessionId == notification.MapId);
snapshot = _dbcontext.Snapshots.OrderByDescending(s => s.Timestamp).FirstOrDefault(m => m.SessionId == session.SessionId);
var snapshot = _dbcontext.Snapshots.OrderByDescending(s => s.Timestamp).FirstOrDefault(m => m.SessionId == session.SessionId);
if (snapshot is null)
{
@ -68,10 +66,6 @@ namespace Sledgemapper.Api.Handlers
var room = JsonSerializer.Deserialize<Room>(mapUpdate.Object);
mapSession.NewRoom(room);
break;
}
}

View File

@ -0,0 +1,30 @@
using Microsoft.Identity.Client.Extensions.Msal;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sledgemapper
{
public static class CacheSettings
{
// computing the root directory is not very simple on Linux and Mac, so a helper is provided
private static readonly string s_cacheFilePath =
Path.Combine(MsalCacheHelper.UserRootDirectory, "sledgemapper.scandysoft.cache");
public static readonly string CacheFileName = Path.GetFileName(s_cacheFilePath);
public static readonly string CacheDir = Path.GetDirectoryName(s_cacheFilePath);
public static readonly string KeyChainServiceName = "Scandysoft.Sledgemapper";
public static readonly string KeyChainAccountName = "MSALCache";
public static readonly string LinuxKeyRingSchema = "com.scandysoft.sledgemappertokencache";
public static readonly string LinuxKeyRingCollection = MsalCacheHelper.LinuxKeyRingDefaultCollection;
public static readonly string LinuxKeyRingLabel = "Sledgemapper API token.";
public static readonly KeyValuePair<string, string> LinuxKeyRingAttr1 = new KeyValuePair<string, string>("Version", "1");
public static readonly KeyValuePair<string, string> LinuxKeyRingAttr2 = new KeyValuePair<string, string>("ProductGroup", "MyApps");
}
}

View File

@ -4,6 +4,8 @@ using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR.Client;
using Polly;
@ -37,6 +39,8 @@ namespace Sledgemapper
var baseAddress = "http://hub.michelescandura.com:5000";
#endif
CheckLogin();
_retryPolicy = Policy
.Handle<ApiException>(ex => ex.StatusCode == HttpStatusCode.RequestTimeout)
.Or<HttpRequestException>()
@ -292,13 +296,19 @@ namespace Sledgemapper
.ConfigureAwait(false);
//_authenticateResponse = await Api.Authenticate(authenticateModel).ConfigureAwait(false);
var data = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(_authenticateResponse));
Program.helper.SaveUnencryptedTokenCache(JsonSerializer.SerializeToUtf8Bytes(_authenticateResponse));
return _authenticateResponse;
}
internal async Task Ping(Tile location)
{
if (Connection is { State: HubConnectionState.Connected })
await Connection.InvokeAsync("Ping", SessionData.SessionName, location);
await Connection.InvokeAsync("Ping", SessionData.SessionId, location);
}
public async Task<IMapApi.AuthResult> Register(RegisterModel registerModel)
@ -306,5 +316,20 @@ namespace Sledgemapper
var result = await Api.Register(registerModel).ConfigureAwait(false);
return result;
}
public void CheckLogin()
{
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
{ }
}
}
}
}

View File

@ -1,13 +1,47 @@
using System;
using System.Text;
using Microsoft.Extensions.Configuration;
using Microsoft.Identity.Client;
using Microsoft.Identity.Client.Extensions.Msal;
namespace Sledgemapper
{
public static class Program
{
private static IConfiguration configuration;
public static MsalCacheHelper helper;
[STAThread]
static void Main()
{
using(Sentry.SentrySdk.Init("https://973ac1606651454ba7a19f642d0a9bc1@glitchtip.michelescandura.com/1"))
var builder = new ConfigurationBuilder()
.SetBasePath(System.IO.Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
configuration = builder.Build();
// Loading PublicClientApplicationOptions from the values set on appsettings.json
// Building StorageCreationProperties
var storageProperties =
new StorageCreationPropertiesBuilder(CacheSettings.CacheFileName, CacheSettings.CacheDir)
.WithLinuxKeyring(
CacheSettings.LinuxKeyRingSchema,
CacheSettings.LinuxKeyRingCollection,
CacheSettings.LinuxKeyRingLabel,
CacheSettings.LinuxKeyRingAttr1,
CacheSettings.LinuxKeyRingAttr2)
.WithMacKeyChain(
CacheSettings.KeyChainServiceName,
CacheSettings.KeyChainAccountName)
.Build();
// storage = Storage.Create(storageProperties);
helper = MsalCacheHelper.CreateAsync(storageProperties).Result;
using (Sentry.SentrySdk.Init("https://973ac1606651454ba7a19f642d0a9bc1@glitchtip.michelescandura.com/1"))
using (var game = new Sledgemapper())
{
Sentry.SentrySdk.CaptureEvent(new Sentry.SentryEvent() { Message = "App starting" });

View File

@ -139,7 +139,7 @@ namespace Sledgemapper
_mainWidget = new MainWidget(_communicationManager, _messenger, Window);
_communicationManager.CheckLogin();
_wallsContent = Content.LoadContentFolder<Texture2D>("walls");

View File

@ -42,7 +42,11 @@
</ItemGroup> -->
<ItemGroup>
<PackageReference Include="AsyncAwaitBestPractices" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0-preview.7.21377.19" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.0-rc.1.21451.13" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="6.0.0-rc.1.21451.13" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="6.0.0-rc.1.21451.13" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0-rc.1.21451.13" />
<PackageReference Include="Microsoft.Identity.Client.Extensions.Msal" Version="2.19.1" />
<PackageReference Include="MonoGame.Extended" Version="3.8.0" />
<PackageReference Include="MonoGame.Framework.DesktopGL" Version="3.8.0.1641" />
<PackageReference Include="MonoGame.Content.Builder.Task" Version="3.8.0.1641" />
@ -87,6 +91,11 @@
<DependentUpon>$([System.String]::Copy(%(Filename)).Replace(".Generated",".cs"))</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -25,10 +25,18 @@ namespace Sledgemapper.UI
public MainWidget(CommunicationManager communicationManager, TinyMessengerHub messenger, GameWindow window)
{
BuildUI();
CommunicationManager = communicationManager;
Window = window;
Messenger = messenger;
Messenger.Subscribe<LoginSuccesfulMessage>(OnLoginSuccesfulMessage);
Messenger.Subscribe<SignalrConnectionUpdateMessage>(OnSignalrConnectionUpdateMessage);
Messenger.Subscribe<MapOpenedMessage>(OnMapOpenedMessage);
Messenger.Subscribe<CenterOnTileMessage>(OnCenterOnTileMessage);
Messenger.Subscribe<CampaignSelectedMessage>(OnCampaignSelectedMessage);
Messenger.Subscribe<ErrorMessage>(OnErrorMessage);
MenuConnectLogin.Selected += OnMenuConnectLoginSelected;
MenuConnectSync.Selected += OnMenuConnectSyncSelected;
MenuFileLoad.Selected += OnMenuFileLoadSelected;
@ -62,12 +70,7 @@ namespace Sledgemapper.UI
BtnToolbarRoom.Click += OnBtnToolbarRoomClicked;
BtnToolbarDelete.Click += OnBtnToolbarDeleteClicked;
Messenger.Subscribe<LoginSuccesfulMessage>(OnLoginSuccesfulMessage);
Messenger.Subscribe<SignalrConnectionUpdateMessage>(OnSignalrConnectionUpdateMessage);
Messenger.Subscribe<MapOpenedMessage>(OnMapOpenedMessage);
Messenger.Subscribe<CenterOnTileMessage>(OnCenterOnTileMessage);
Messenger.Subscribe<CampaignSelectedMessage>(OnCampaignSelectedMessage);
Messenger.Subscribe<ErrorMessage>(OnErrorMessage);
}
private void CenterOnSelectedTile()

View File

@ -32,11 +32,13 @@ namespace Sledgemapper.UI
private void BtnLoadCampaign_Click(object sender, EventArgs e)
{
State.Instance.MapName = _selectedMap;
State.Instance.MapId = _selectedMapId;
// var map = CommunicationManager.Api.GetMap(State.Instance.CampaignId, State.Instance.MapId);
Messenger.Publish(new MapOpenedMessage(this, _selectedMap, _selectedMapId));
this.GetContainingWindow().Close();
if (!string.IsNullOrWhiteSpace(_selectedMap) && _selectedMapId!=Guid.Empty)
{
State.Instance.MapName = _selectedMap;
State.Instance.MapId = _selectedMapId;
Messenger.Publish(new MapOpenedMessage(this, _selectedMap, _selectedMapId));
this.GetContainingWindow().Close();
}
}
public async Task<bool> LoadMaps()

View File

@ -0,0 +1,3 @@
{
}