Merge pull request 'campaign' (#2) from campaign into master
All checks were successful
continuous-integration/drone/push Build is passing

Reviewed-on: #2
This commit is contained in:
michele 2021-09-23 13:38:10 +00:00
commit c669f1666f
19 changed files with 253 additions and 138 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

@ -18,7 +18,7 @@ namespace Sledgemapper.Api.Handlers
{
await CheckAuthorization(command);
var jsonString = JsonSerializer.Serialize(command.Note);
var session = await SaveLog(command, "N", "W", jsonString, cancellationToken);
var session = await SaveLog(command, "N", "N", jsonString, cancellationToken);
await Mediator.Publish(new NewNoteNotification(session, command.Note, command.UserId), cancellationToken);
return true;
}

View File

@ -37,7 +37,7 @@ namespace Sledgemapper.Api.Infrastructure.Data
// options.MigrationsAssembly(Assembly.GetExecutingAssembly().FullName);
// });
optionsBuilder.UseSqlite("Filename=Sledgemapper.db").UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
optionsBuilder.UseSqlite("Filename=db/sledgemapper.db").UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
base.OnConfiguring(optionsBuilder);
}

View File

@ -1,30 +1,57 @@
using System;
using System.Text;
using MediatR;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Sledgemapper.Api.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using System.Text;
using Sledgemapper.Api.Hubs;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json;
using Sledgemapper.Api.Core.Entities;
using Sledgemapper.Api.Hubs;
using Sledgemapper.Api.Infrastructure.Data;
namespace Sledgemapper.Api
{
public class Startup
{
private readonly IWebHostEnvironment _env;
public IConfiguration Configuration { get; }
public Startup(IWebHostEnvironment env, IConfiguration configuration)
{
Configuration = configuration;
_env = env;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, SledgemapperDbContext dataContext)
{
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); });
dataContext.Database.Migrate();
app.UseRouting();
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
app.UseEndpoints(endpoints => { endpoints.MapHub<SledgemapperHub>("/sledgemapperhub"); });
}
// This method gets called by the runtime. Use this method to add services to the container.
@ -34,14 +61,16 @@ namespace Sledgemapper.Api
services.AddControllers().AddNewtonsoftJson(o =>
{
o.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
}); ;
});
services.AddSignalR();
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
services.AddMediatR(typeof(Startup));
services.AddDbContext<SledgemapperDbContext>(options => { options.UseSqlite("Data Source=db/sledgemapper.db"); options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); });
services.AddDbContext<SledgemapperDbContext>(options =>
{
options.UseSqlite("Data Source=db/sledgemapper.db");
options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
});
services.Configure<JwtConfig>(Configuration.GetSection("JwtConfig"));
@ -61,7 +90,8 @@ namespace Sledgemapper.Api
jwt.SaveToken = true;
jwt.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true, // this will validate the 3rd part of the jwt token using the secret that we added in the appsettings and verify we have generated the jwt token
ValidateIssuerSigningKey =
true, // this will validate the 3rd part of the jwt token using the secret that we added in the appsettings and verify we have generated the jwt token
IssuerSigningKey = new SymmetricSecurityKey(key), // Add the secret key to our Jwt encryption
ValidateIssuer = false,
ValidateAudience = false,
@ -87,8 +117,10 @@ namespace Sledgemapper.Api
Name = "Authorization",
Type = SecuritySchemeType.ApiKey
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement {
{ new OpenApiSecurityScheme
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
@ -100,44 +132,6 @@ namespace Sledgemapper.Api
}
});
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, SledgemapperDbContext dataContext)
{
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
dataContext.Database.Migrate();
app.UseRouting();
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<SledgemapperHub>("/sledgemapperhub");
});
}
}
}

View File

@ -1,6 +1,6 @@
{
{
"ConnectionStrings": {
"WebApiDatabase": "Data Source=db/LocalDatabase.db"
"WebApiDatabase": "Data Source=db/sledgemapper.db"
},
"Logging": {
"LogLevel": {

View File

@ -1,6 +1,6 @@
{
{
"ConnectionStrings": {
"WebApiDatabase": "Data Source=db/LocalDatabase.db"
"WebApiDatabase": "Data Source=db/sledgemapper.db"
},
"Logging": {
"LogLevel": {

View File

@ -1,9 +1,21 @@
namespace Sledgemapper.Shared.Entities
namespace Sledgemapper.Shared.Entities
{
public class Note :BaseMapEntity
{
public Note(){}
public Note(Note n)
{
X=n.X;
Y=n.Y;
Text=n.Text;
ID = n.ID;
Rotation = n.Rotation;
Timestamp = n.Timestamp;
}
public string Text { get; set; }
}

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;
@ -33,10 +35,13 @@ namespace Sledgemapper
_queue = new ChannelsQueue(Messenger);
#if DEBUG
var baseAddress = "http://localhost:5000";
baseAddress = "http://hub.michelescandura.com:5001";
#else
var baseAddress = "http://hub.michelescandura.com:5000";
var baseAddress = "http://hub.michelescandura.com:5001";
#endif
CheckLogin();
_retryPolicy = Policy
.Handle<ApiException>(ex => ex.StatusCode == HttpStatusCode.RequestTimeout)
.Or<HttpRequestException>()
@ -292,13 +297,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 +317,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,12 +1,46 @@
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()
{
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())
{

View File

@ -139,7 +139,7 @@ namespace Sledgemapper
_mainWidget = new MainWidget(_communicationManager, _messenger, Window);
_communicationManager.CheckLogin();
_wallsContent = Content.LoadContentFolder<Texture2D>("walls");
@ -255,7 +255,7 @@ namespace Sledgemapper
else
{
_sessionData.Notes.TryGetValue(_state.SelectedNote.ToString(), out var n);
_state.SelectedNote = n;
_state.SelectedNote = new Note(n);
var viewNoteButton = new TextButton
{
Text = "View Note", Width = 80, Height = 20, Padding = new Thickness(2),

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

@ -21,7 +21,7 @@ namespace Sledgemapper.UI
_messenger = messenger;
#if DEBUG
TxtEmail.Text = "michele.scandura@outlook.com";
TxtEmail.Text = "michele.scandura@sloutlook.com";
TxtPassword.Text = "slePharland!79";
#endif

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

@ -31,13 +31,15 @@ namespace Sledgemapper.UI
}
private void BtnLoadCampaign_Click(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(_selectedMap) && _selectedMapId!=Guid.Empty)
{
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();
}
}
public async Task<bool> LoadMaps()
{

View File

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