From 3d0450efff55e26a38e397f836678440af1b3819 Mon Sep 17 00:00:00 2001 From: Michele Scandura Date: Thu, 23 Sep 2021 12:29:40 +0100 Subject: [PATCH 1/3] credentials storage, bug fixing --- .../Commands/GetCampaignPlayersCommand.cs | 8 +++++ .../Controllers/CampaignController.cs | 2 +- .../GetCampaignPlayersCommandHandler.cs | 4 +-- .../Handlers/GetMapSnapshotCommandHandler.cs | 8 +---- Sledgemapper/CacheSettings.cs | 30 ++++++++++++++++ Sledgemapper/CommunicationManager.cs | 27 +++++++++++++- Sledgemapper/Program.cs | 36 ++++++++++++++++++- Sledgemapper/Sledgemapper.cs | 2 +- Sledgemapper/Sledgemapper.csproj | 11 +++++- Sledgemapper/UI/MainWidget.Custom.cs | 17 +++++---- Sledgemapper/UI/MapList.Custom.cs | 12 ++++--- Sledgemapper/appsettings.json | 3 ++ 12 files changed, 134 insertions(+), 26 deletions(-) create mode 100644 Sledgemapper/CacheSettings.cs create mode 100644 Sledgemapper/appsettings.json diff --git a/Sledgemapper.Api/Commands/GetCampaignPlayersCommand.cs b/Sledgemapper.Api/Commands/GetCampaignPlayersCommand.cs index 01fa504..0b733f7 100644 --- a/Sledgemapper.Api/Commands/GetCampaignPlayersCommand.cs +++ b/Sledgemapper.Api/Commands/GetCampaignPlayersCommand.cs @@ -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; + } } } \ No newline at end of file diff --git a/Sledgemapper.Api/Controllers/CampaignController.cs b/Sledgemapper.Api/Controllers/CampaignController.cs index 6c0313f..a09e5af 100644 --- a/Sledgemapper.Api/Controllers/CampaignController.cs +++ b/Sledgemapper.Api/Controllers/CampaignController.cs @@ -57,7 +57,7 @@ namespace Sledgemapper.Api.Controllers [HttpGet] [Route("{campaignName}/players")] - public async Task> GetPlayers(string campaignName) + public async Task> GetPlayers(Guid campaignName) { var result = await _mediator.Send(new GetCampaignPlayersCommand(campaignName, UserId)); return result; diff --git a/Sledgemapper.Api/Handlers/GetCampaignPlayersCommandHandler.cs b/Sledgemapper.Api/Handlers/GetCampaignPlayersCommandHandler.cs index 7b606c5..23c801d 100644 --- a/Sledgemapper.Api/Handlers/GetCampaignPlayersCommandHandler.cs +++ b/Sledgemapper.Api/Handlers/GetCampaignPlayersCommandHandler.cs @@ -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) diff --git a/Sledgemapper.Api/Handlers/GetMapSnapshotCommandHandler.cs b/Sledgemapper.Api/Handlers/GetMapSnapshotCommandHandler.cs index e304fa0..14ad035 100644 --- a/Sledgemapper.Api/Handlers/GetMapSnapshotCommandHandler.cs +++ b/Sledgemapper.Api/Handlers/GetMapSnapshotCommandHandler.cs @@ -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 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(mapUpdate.Object); mapSession.NewRoom(room); break; - - - - } } diff --git a/Sledgemapper/CacheSettings.cs b/Sledgemapper/CacheSettings.cs new file mode 100644 index 0000000..3dd06a5 --- /dev/null +++ b/Sledgemapper/CacheSettings.cs @@ -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 LinuxKeyRingAttr1 = new KeyValuePair("Version", "1"); + public static readonly KeyValuePair LinuxKeyRingAttr2 = new KeyValuePair("ProductGroup", "MyApps"); + } +} diff --git a/Sledgemapper/CommunicationManager.cs b/Sledgemapper/CommunicationManager.cs index 5ad52d6..ec61b0e 100644 --- a/Sledgemapper/CommunicationManager.cs +++ b/Sledgemapper/CommunicationManager.cs @@ -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(ex => ex.StatusCode == HttpStatusCode.RequestTimeout) .Or() @@ -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 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(Encoding.UTF8.GetString(data)); + Messenger.Publish(new LoginSuccesfulMessage(this) { UserName = _authenticateResponse.Username, Initials = _authenticateResponse.Initials }); + } + catch + { } + } + } } } \ No newline at end of file diff --git a/Sledgemapper/Program.cs b/Sledgemapper/Program.cs index 7eb1839..58eada1 100644 --- a/Sledgemapper/Program.cs +++ b/Sledgemapper/Program.cs @@ -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" }); diff --git a/Sledgemapper/Sledgemapper.cs b/Sledgemapper/Sledgemapper.cs index 1d960db..efec31b 100644 --- a/Sledgemapper/Sledgemapper.cs +++ b/Sledgemapper/Sledgemapper.cs @@ -139,7 +139,7 @@ namespace Sledgemapper _mainWidget = new MainWidget(_communicationManager, _messenger, Window); - + _communicationManager.CheckLogin(); _wallsContent = Content.LoadContentFolder("walls"); diff --git a/Sledgemapper/Sledgemapper.csproj b/Sledgemapper/Sledgemapper.csproj index cfb4b66..7cbb026 100644 --- a/Sledgemapper/Sledgemapper.csproj +++ b/Sledgemapper/Sledgemapper.csproj @@ -42,7 +42,11 @@ --> - + + + + + @@ -87,6 +91,11 @@ $([System.String]::Copy(%(Filename)).Replace(".Generated",".cs")) + + + PreserveNewest + + \ No newline at end of file diff --git a/Sledgemapper/UI/MainWidget.Custom.cs b/Sledgemapper/UI/MainWidget.Custom.cs index 361e63b..d8d1ebb 100644 --- a/Sledgemapper/UI/MainWidget.Custom.cs +++ b/Sledgemapper/UI/MainWidget.Custom.cs @@ -25,10 +25,18 @@ namespace Sledgemapper.UI public MainWidget(CommunicationManager communicationManager, TinyMessengerHub messenger, GameWindow window) { BuildUI(); - CommunicationManager = communicationManager; Window = window; Messenger = messenger; + + Messenger.Subscribe(OnLoginSuccesfulMessage); + Messenger.Subscribe(OnSignalrConnectionUpdateMessage); + Messenger.Subscribe(OnMapOpenedMessage); + Messenger.Subscribe(OnCenterOnTileMessage); + Messenger.Subscribe(OnCampaignSelectedMessage); + Messenger.Subscribe(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(OnLoginSuccesfulMessage); - Messenger.Subscribe(OnSignalrConnectionUpdateMessage); - Messenger.Subscribe(OnMapOpenedMessage); - Messenger.Subscribe(OnCenterOnTileMessage); - Messenger.Subscribe(OnCampaignSelectedMessage); - Messenger.Subscribe(OnErrorMessage); + } private void CenterOnSelectedTile() diff --git a/Sledgemapper/UI/MapList.Custom.cs b/Sledgemapper/UI/MapList.Custom.cs index 58cd13c..e779da8 100644 --- a/Sledgemapper/UI/MapList.Custom.cs +++ b/Sledgemapper/UI/MapList.Custom.cs @@ -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 LoadMaps() diff --git a/Sledgemapper/appsettings.json b/Sledgemapper/appsettings.json new file mode 100644 index 0000000..544b7b4 --- /dev/null +++ b/Sledgemapper/appsettings.json @@ -0,0 +1,3 @@ +{ + +} \ No newline at end of file From 5b7ad4f2ff29efae303cae9fe8ea4ad296467a17 Mon Sep 17 00:00:00 2001 From: Michele Scandura Date: Thu, 23 Sep 2021 12:47:48 +0100 Subject: [PATCH 2/3] fix note bugs --- Sledgemapper.Api/Handlers/NewNoteCommandHandler.cs | 2 +- Sledgemapper.Shared/Entities/Note.cs | 14 +++++++++++++- Sledgemapper/Sledgemapper.cs | 2 +- 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/Sledgemapper.Api/Handlers/NewNoteCommandHandler.cs b/Sledgemapper.Api/Handlers/NewNoteCommandHandler.cs index 6390422..8be5287 100644 --- a/Sledgemapper.Api/Handlers/NewNoteCommandHandler.cs +++ b/Sledgemapper.Api/Handlers/NewNoteCommandHandler.cs @@ -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; } diff --git a/Sledgemapper.Shared/Entities/Note.cs b/Sledgemapper.Shared/Entities/Note.cs index 6dac5bb..a89257f 100644 --- a/Sledgemapper.Shared/Entities/Note.cs +++ b/Sledgemapper.Shared/Entities/Note.cs @@ -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; } } diff --git a/Sledgemapper/Sledgemapper.cs b/Sledgemapper/Sledgemapper.cs index efec31b..fe3864d 100644 --- a/Sledgemapper/Sledgemapper.cs +++ b/Sledgemapper/Sledgemapper.cs @@ -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), From 6c167ed4de3855b424b3e03d3ec94f904e90fc88 Mon Sep 17 00:00:00 2001 From: Michele Scandura Date: Thu, 23 Sep 2021 14:34:33 +0100 Subject: [PATCH 3/3] db issues for prod --- .../Data/SledgemapperDbContext.cs | 12 +- Sledgemapper.Api/Startup.cs | 156 +++++++++--------- Sledgemapper.Api/appsettings.Development.json | 20 +-- Sledgemapper.Api/appsettings.Production.json | 20 +-- Sledgemapper/CommunicationManager.cs | 5 +- Sledgemapper/UI/LoginRegisterWindow.Custom.cs | 2 +- 6 files changed, 105 insertions(+), 110 deletions(-) diff --git a/Sledgemapper.Api/Infrastructure/Data/SledgemapperDbContext.cs b/Sledgemapper.Api/Infrastructure/Data/SledgemapperDbContext.cs index 265d446..195b192 100644 --- a/Sledgemapper.Api/Infrastructure/Data/SledgemapperDbContext.cs +++ b/Sledgemapper.Api/Infrastructure/Data/SledgemapperDbContext.cs @@ -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().HasOne(e=>e.Owner); - -modelBuilder.Entity().HasMany(e=>e.InvitedUsers).WithMany(e=>e.Campaigns); + modelBuilder.Entity().HasOne(e => e.Owner); - modelBuilder.Entity() //Use your application user class here - .ToTable( "Users" ); //Set the table name here + modelBuilder.Entity().HasMany(e => e.InvitedUsers).WithMany(e => e.Campaigns); + + modelBuilder.Entity() //Use your application user class here + .ToTable("Users"); //Set the table name here // // Map table names // modelBuilder.Entity().ToTable("MapLog", "dbo"); diff --git a/Sledgemapper.Api/Startup.cs b/Sledgemapper.Api/Startup.cs index 84bf827..0928fd3 100644 --- a/Sledgemapper.Api/Startup.cs +++ b/Sledgemapper.Api/Startup.cs @@ -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"); }); } // 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(options => { options.UseSqlite("Data Source=db/sledgemapper.db"); options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); }); + services.AddDbContext(options => + { + options.UseSqlite("Data Source=db/sledgemapper.db"); + options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); + }); services.Configure(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(options => options.SignIn.RequireConfirmedAccount = false) - .AddEntityFrameworkStores(); + .AddEntityFrameworkStores(); 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() + c.AddSecurityRequirement(new OpenApiSecurityRequirement + { + { + new OpenApiSecurityScheme + { + Reference = new OpenApiReference + { + Type = ReferenceType.SecurityScheme, + Id = "Bearer" + } + }, + Array.Empty() } - }); - }); - - - - } - - // 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"); + }); }); } } -} +} \ No newline at end of file diff --git a/Sledgemapper.Api/appsettings.Development.json b/Sledgemapper.Api/appsettings.Development.json index 996eb73..f66b5e3 100644 --- a/Sledgemapper.Api/appsettings.Development.json +++ b/Sledgemapper.Api/appsettings.Development.json @@ -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" + } } - } } diff --git a/Sledgemapper.Api/appsettings.Production.json b/Sledgemapper.Api/appsettings.Production.json index 996eb73..f66b5e3 100644 --- a/Sledgemapper.Api/appsettings.Production.json +++ b/Sledgemapper.Api/appsettings.Production.json @@ -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" + } } - } } diff --git a/Sledgemapper/CommunicationManager.cs b/Sledgemapper/CommunicationManager.cs index ec61b0e..36adb4b 100644 --- a/Sledgemapper/CommunicationManager.cs +++ b/Sledgemapper/CommunicationManager.cs @@ -35,11 +35,12 @@ 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(); + CheckLogin(); _retryPolicy = Policy .Handle(ex => ex.StatusCode == HttpStatusCode.RequestTimeout) diff --git a/Sledgemapper/UI/LoginRegisterWindow.Custom.cs b/Sledgemapper/UI/LoginRegisterWindow.Custom.cs index 73dee30..de7d04e 100644 --- a/Sledgemapper/UI/LoginRegisterWindow.Custom.cs +++ b/Sledgemapper/UI/LoginRegisterWindow.Custom.cs @@ -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