Compare commits

...

4 Commits

Author SHA1 Message Date
c669f1666f Merge pull request 'campaign' (#2) from campaign into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #2
2021-09-23 13:38:10 +00:00
Michele Scandura
6c167ed4de db issues for prod
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2021-09-23 14:34:33 +01:00
Michele Scandura
5b7ad4f2ff fix note bugs
All checks were successful
continuous-integration/drone/push Build is passing
2021-09-23 12:47:48 +01:00
Michele Scandura
3d0450efff credentials storage, bug fixing
All checks were successful
continuous-integration/drone/push Build is passing
2021-09-23 12:29:40 +01:00
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,19 +37,19 @@ 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);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Campaign>().HasOne(e=>e.Owner);
modelBuilder.Entity<Campaign>().HasMany(e=>e.InvitedUsers).WithMany(e=>e.Campaigns);
modelBuilder.Entity<Campaign>().HasOne(e => e.Owner);
modelBuilder.Entity<User>() //Use your application user class here
.ToTable( "Users" ); //Set the table name here
modelBuilder.Entity<Campaign>().HasMany(e => e.InvitedUsers).WithMany(e => e.Campaigns);
modelBuilder.Entity<User>() //Use your application user class here
.ToTable("Users"); //Set the table name here
// // Map table names
// modelBuilder.Entity<MapLog>().ToTable("MapLog", "dbo");

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"));
@ -49,29 +78,30 @@ namespace Sledgemapper.Api
// within this section we are configuring the authentication and setting the default scheme
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(jwt =>
{
var key = Encoding.ASCII.GetBytes(Configuration["JwtConfig:Secret"]);
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
IssuerSigningKey = new SymmetricSecurityKey(key), // Add the secret key to our Jwt encryption
ValidateIssuer = false,
ValidateAudience = false,
RequireExpirationTime = false,
ValidateLifetime = true
};
});
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(jwt =>
{
var key = Encoding.ASCII.GetBytes(Configuration["JwtConfig:Secret"]);
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
IssuerSigningKey = new SymmetricSecurityKey(key), // Add the secret key to our Jwt encryption
ValidateIssuer = false,
ValidateAudience = false,
RequireExpirationTime = false,
ValidateLifetime = true
};
});
services.AddDefaultIdentity<User>(options => options.SignIn.RequireConfirmedAccount = false)
.AddEntityFrameworkStores<SledgemapperDbContext>();
.AddEntityFrameworkStores<SledgemapperDbContext>();
services.AddSwaggerGen(c =>
{
@ -87,57 +117,21 @@ namespace Sledgemapper.Api
Name = "Authorization",
Type = SecuritySchemeType.ApiKey
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement {
{ new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
Array.Empty<string>()
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
Array.Empty<string>()
}
});
});
}
// 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,12 +1,12 @@
{
"ConnectionStrings": {
"WebApiDatabase": "Data Source=db/LocalDatabase.db"
},
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
{
"ConnectionStrings": {
"WebApiDatabase": "Data Source=db/sledgemapper.db"
},
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
}

View File

@ -1,12 +1,12 @@
{
"ConnectionStrings": {
"WebApiDatabase": "Data Source=db/LocalDatabase.db"
},
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
{
"ConnectionStrings": {
"WebApiDatabase": "Data Source=db/sledgemapper.db"
},
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
}

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,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");
@ -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

@ -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 @@
{
}