Compare commits
No commits in common. "5b8f0beb6ecdda9e8a23d9658d36ed0195d46476" and "5c06865b1fdc18c1527d78a69618741786880074" have entirely different histories.
5b8f0beb6e
...
5c06865b1f
@ -3,7 +3,7 @@ using Newsbot.Collector.Domain.Consts;
|
|||||||
using Newsbot.Collector.Domain.Models.Config;
|
using Newsbot.Collector.Domain.Models.Config;
|
||||||
using Newsbot.Collector.Services.Jobs;
|
using Newsbot.Collector.Services.Jobs;
|
||||||
|
|
||||||
namespace Newsbot.Collector.Api.Startup;
|
namespace Newsbot.Collector.Api;
|
||||||
|
|
||||||
public static class BackgroundJobs
|
public static class BackgroundJobs
|
||||||
{
|
{
|
@ -1,20 +1,21 @@
|
|||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Identity;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Newsbot.Collector.Api.Domain;
|
|
||||||
using Newsbot.Collector.Api.Domain.Requests;
|
using Newsbot.Collector.Api.Domain.Requests;
|
||||||
using Newsbot.Collector.Api.Domain.Response;
|
using Newsbot.Collector.Api.Domain.Response;
|
||||||
using Newsbot.Collector.Api.Domain.Results;
|
using Newsbot.Collector.Api.Domain.Results;
|
||||||
using Newsbot.Collector.Api.Services;
|
using Newsbot.Collector.Api.Services;
|
||||||
|
using Newsbot.Collector.Domain.Dto;
|
||||||
|
using Newsbot.Collector.Domain.Entities;
|
||||||
|
|
||||||
namespace Newsbot.Collector.Api.Controllers.v1;
|
namespace Newsbot.Collector.Api.Controllers;
|
||||||
|
|
||||||
[ApiController]
|
[ApiController]
|
||||||
[Route("/api/v1/account")]
|
[Route("/api/account")]
|
||||||
public class IdentityController : ControllerBase
|
public class AccountController : ControllerBase
|
||||||
{
|
{
|
||||||
private IIdentityService _identityService;
|
private IIdentityService _identityService;
|
||||||
|
|
||||||
public IdentityController(IIdentityService identityService)
|
public AccountController(IIdentityService identityService)
|
||||||
{
|
{
|
||||||
_identityService = identityService;
|
_identityService = identityService;
|
||||||
}
|
}
|
||||||
@ -70,21 +71,6 @@ public class IdentityController : ControllerBase
|
|||||||
return CheckIfSuccessful(response);
|
return CheckIfSuccessful(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost("addRole")]
|
|
||||||
[Authorize(Roles = Authorization.AdministratorsRole)]
|
|
||||||
public ActionResult AddRole([FromBody] AddRoleRequest request)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
_identityService.AddRole(request.RoleName ?? "", request.UserId ?? "");
|
|
||||||
return new OkResult();
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
return new BadRequestResult();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private ActionResult CheckIfSuccessful(AuthenticationResult result)
|
private ActionResult CheckIfSuccessful(AuthenticationResult result)
|
||||||
{
|
{
|
||||||
if (!result.IsSuccessful)
|
if (!result.IsSuccessful)
|
@ -3,7 +3,6 @@ using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using Newsbot.Collector.Api.Domain;
|
|
||||||
using Newsbot.Collector.Domain.Models.Config;
|
using Newsbot.Collector.Domain.Models.Config;
|
||||||
using Newsbot.Collector.Services.Jobs;
|
using Newsbot.Collector.Services.Jobs;
|
||||||
|
|
||||||
@ -25,7 +24,6 @@ public class CodeProjectController
|
|||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost("check")]
|
[HttpPost("check")]
|
||||||
[Authorize(Roles = Authorization.AdministratorsRole)]
|
|
||||||
public void PullNow()
|
public void PullNow()
|
||||||
{
|
{
|
||||||
BackgroundJob.Enqueue<CodeProjectWatcherJob>(x => x.InitAndExecute(new CodeProjectWatcherJobOptions
|
BackgroundJob.Enqueue<CodeProjectWatcherJob>(x => x.InitAndExecute(new CodeProjectWatcherJobOptions
|
||||||
|
@ -3,7 +3,6 @@ using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using Newsbot.Collector.Api.Domain;
|
|
||||||
using Newsbot.Collector.Domain.Models.Config;
|
using Newsbot.Collector.Domain.Models.Config;
|
||||||
using Newsbot.Collector.Domain.Models.Config.Sources;
|
using Newsbot.Collector.Domain.Models.Config.Sources;
|
||||||
using Newsbot.Collector.Services.Jobs;
|
using Newsbot.Collector.Services.Jobs;
|
||||||
@ -28,7 +27,6 @@ public class RssController
|
|||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost("check")]
|
[HttpPost("check")]
|
||||||
[Authorize(Roles = Authorization.AdministratorsRole)]
|
|
||||||
public void CheckReddit()
|
public void CheckReddit()
|
||||||
{
|
{
|
||||||
BackgroundJob.Enqueue<RssWatcherJob>(x => x.InitAndExecute(new RssWatcherJobOptions
|
BackgroundJob.Enqueue<RssWatcherJob>(x => x.InitAndExecute(new RssWatcherJobOptions
|
||||||
|
@ -2,7 +2,6 @@ using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using Newsbot.Collector.Api.Domain;
|
|
||||||
using Newsbot.Collector.Database.Repositories;
|
using Newsbot.Collector.Database.Repositories;
|
||||||
using Newsbot.Collector.Domain.Consts;
|
using Newsbot.Collector.Domain.Consts;
|
||||||
using Newsbot.Collector.Domain.Dto;
|
using Newsbot.Collector.Domain.Dto;
|
||||||
@ -200,14 +199,12 @@ public class SourcesController : ControllerBase
|
|||||||
return SourceDto.Convert(item);
|
return SourceDto.Convert(item);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Authorize(Roles = Authorization.AdministratorsRole)]
|
|
||||||
[HttpPost("{id}/disable")]
|
[HttpPost("{id}/disable")]
|
||||||
public void Disable(Guid id)
|
public void Disable(Guid id)
|
||||||
{
|
{
|
||||||
_sources.Disable(id);
|
_sources.Disable(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Authorize(Roles = Authorization.AdministratorsRole)]
|
|
||||||
[HttpPost("{id}/enable")]
|
[HttpPost("{id}/enable")]
|
||||||
public void Enable(Guid id)
|
public void Enable(Guid id)
|
||||||
{
|
{
|
||||||
@ -215,7 +212,6 @@ public class SourcesController : ControllerBase
|
|||||||
}
|
}
|
||||||
|
|
||||||
[HttpDelete("{id}")]
|
[HttpDelete("{id}")]
|
||||||
[Authorize(Roles = Authorization.AdministratorsRole)]
|
|
||||||
public void Delete(Guid id, bool purgeOrphanedRecords)
|
public void Delete(Guid id, bool purgeOrphanedRecords)
|
||||||
{
|
{
|
||||||
_sources.Delete(id);
|
_sources.Delete(id);
|
||||||
|
@ -3,7 +3,6 @@ using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using Newsbot.Collector.Api.Domain;
|
|
||||||
using Newsbot.Collector.Domain.Models.Config;
|
using Newsbot.Collector.Domain.Models.Config;
|
||||||
using Newsbot.Collector.Domain.Models.Config.Sources;
|
using Newsbot.Collector.Domain.Models.Config.Sources;
|
||||||
using Newsbot.Collector.Services.Jobs;
|
using Newsbot.Collector.Services.Jobs;
|
||||||
@ -28,7 +27,6 @@ public class YoutubeController
|
|||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost("check")]
|
[HttpPost("check")]
|
||||||
[Authorize(Policy = Authorization.AdministratorsRole)]
|
|
||||||
public void CheckYoutube()
|
public void CheckYoutube()
|
||||||
{
|
{
|
||||||
BackgroundJob.Enqueue<YoutubeWatcherJob>(x => x.InitAndExecute(new YoutubeWatcherJobOptions
|
BackgroundJob.Enqueue<YoutubeWatcherJob>(x => x.InitAndExecute(new YoutubeWatcherJobOptions
|
||||||
|
@ -1,19 +1,16 @@
|
|||||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|
||||||
using Microsoft.AspNetCore.Authorization;
|
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Newsbot.Collector.Api.Authentication;
|
using Newsbot.Collector.Api.Authentication;
|
||||||
using Newsbot.Collector.Domain.Entities;
|
using Newsbot.Collector.Domain.Entities;
|
||||||
using Newsbot.Collector.Domain.Interfaces;
|
using Newsbot.Collector.Domain.Interfaces;
|
||||||
|
|
||||||
namespace Newsbot.Collector.Api.Controllers.v1;
|
namespace Newsbot.Collector.Api.Controllers;
|
||||||
|
|
||||||
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
|
|
||||||
[ApiController]
|
[ApiController]
|
||||||
[Route("api/v1/user")]
|
[Route("api/v1/user")]
|
||||||
public class UserController : Controller
|
public class UserController : Controller
|
||||||
{
|
{
|
||||||
private readonly ILogger<UserController> _logger;
|
private ILogger<UserController> _logger;
|
||||||
private readonly IUserSourceSubscription _subscription;
|
private IUserSourceSubscription _subscription;
|
||||||
|
|
||||||
public UserController(ILogger<UserController> logger, IUserSourceSubscription subscription)
|
public UserController(ILogger<UserController> logger, IUserSourceSubscription subscription)
|
||||||
{
|
{
|
||||||
|
@ -1,12 +0,0 @@
|
|||||||
namespace Newsbot.Collector.Api.Domain;
|
|
||||||
|
|
||||||
public static class Authorization
|
|
||||||
{
|
|
||||||
public const string AdministratorPolicy = "Administrator";
|
|
||||||
public const string AdministratorClaim = "administrator";
|
|
||||||
|
|
||||||
public const string AdministratorsRole = AdministratorPolicy;
|
|
||||||
|
|
||||||
public const string UserPolicy = "User";
|
|
||||||
public const string UsersRole = UserPolicy;
|
|
||||||
}
|
|
@ -1,7 +0,0 @@
|
|||||||
namespace Newsbot.Collector.Api.Domain.Requests;
|
|
||||||
|
|
||||||
public class AddRoleRequest
|
|
||||||
{
|
|
||||||
public string? RoleName { get; set; }
|
|
||||||
public string? UserId { get; set; }
|
|
||||||
}
|
|
@ -1,32 +0,0 @@
|
|||||||
using Microsoft.AspNetCore.Mvc;
|
|
||||||
using Microsoft.AspNetCore.Mvc.Filters;
|
|
||||||
using Newsbot.Collector.Domain.Consts;
|
|
||||||
|
|
||||||
namespace Newsbot.Collector.Api.Filters;
|
|
||||||
|
|
||||||
[AttributeUsage(AttributeTargets.Class| AttributeTargets.Method)]
|
|
||||||
public class ApiKeyAuthAttribute : Attribute, IAsyncActionFilter
|
|
||||||
{
|
|
||||||
private const string ApiKeyHeaderName = "X-API-KEY";
|
|
||||||
|
|
||||||
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
|
|
||||||
{
|
|
||||||
if (!context.HttpContext.Request.Headers.TryGetValue(ApiKeyHeaderName, out var foundKey))
|
|
||||||
{
|
|
||||||
context.Result = new BadRequestResult();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
var config = context.HttpContext.RequestServices.GetRequiredService<IConfiguration>();
|
|
||||||
var apiKeys = config.GetValue<string[]>(ConfigConst.ApiKeys);
|
|
||||||
|
|
||||||
foreach (var key in apiKeys ?? Array.Empty<string?>())
|
|
||||||
{
|
|
||||||
if (key != foundKey) continue;
|
|
||||||
await next();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
context.Result = new BadRequestResult();
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,13 +1,26 @@
|
|||||||
|
using System.Text;
|
||||||
using Hangfire;
|
using Hangfire;
|
||||||
using Hangfire.MemoryStorage;
|
using Hangfire.MemoryStorage;
|
||||||
using HealthChecks.UI.Client;
|
using HealthChecks.UI.Client;
|
||||||
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||||
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
|
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
|
||||||
using Newsbot.Collector.Api.Startup;
|
using Microsoft.AspNetCore.Identity;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.IdentityModel.Tokens;
|
||||||
|
using Microsoft.OpenApi.Models;
|
||||||
|
using Newsbot.Collector.Api;
|
||||||
|
using Newsbot.Collector.Api.Authentication;
|
||||||
|
using Newsbot.Collector.Api.Services;
|
||||||
|
using Newsbot.Collector.Database;
|
||||||
|
using Newsbot.Collector.Database.Repositories;
|
||||||
using Newsbot.Collector.Domain.Consts;
|
using Newsbot.Collector.Domain.Consts;
|
||||||
|
using Newsbot.Collector.Domain.Entities;
|
||||||
|
using Newsbot.Collector.Domain.Interfaces;
|
||||||
using Newsbot.Collector.Domain.Models;
|
using Newsbot.Collector.Domain.Models;
|
||||||
using Newsbot.Collector.Domain.Models.Config;
|
using Newsbot.Collector.Domain.Models.Config;
|
||||||
using Newsbot.Collector.Domain.Models.Config.Sources;
|
using Newsbot.Collector.Domain.Models.Config.Sources;
|
||||||
using Serilog;
|
using Serilog;
|
||||||
|
using Serilog.Events;
|
||||||
using ILogger = Serilog.ILogger;
|
using ILogger = Serilog.ILogger;
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
@ -23,38 +36,130 @@ Log.Logger = GetLogger(config);
|
|||||||
Log.Information("Starting up");
|
Log.Information("Starting up");
|
||||||
|
|
||||||
// configure Entity Framework
|
// configure Entity Framework
|
||||||
// Allow the controllers to access all the table repositories based on the interface
|
var dbconn = config.GetConnectionString("Database");
|
||||||
DatabaseStartup.BuildDatabase(builder.Services, config);
|
builder.Services.AddDbContext<DatabaseContext>(o => o.UseNpgsql(dbconn ?? ""));
|
||||||
DatabaseStartup.InjectTableClasses(builder.Services);
|
|
||||||
DatabaseStartup.InjectIdentityService(builder.Services);
|
builder.Services.AddIdentity<IdentityUser, IdentityRole>()
|
||||||
|
.AddRoles<IdentityRole>()
|
||||||
|
.AddEntityFrameworkStores<DatabaseContext>();
|
||||||
|
|
||||||
|
builder.Services.AddScoped<IArticlesRepository, ArticlesTable>();
|
||||||
|
builder.Services.AddScoped<IDiscordQueueRepository, DiscordQueueTable>();
|
||||||
|
builder.Services.AddScoped<IDiscordWebHooksRepository, DiscordWebhooksTable>();
|
||||||
|
builder.Services.AddScoped<IIconsRepository, IconsTable>();
|
||||||
|
builder.Services.AddScoped<ISourcesRepository, SourcesTable>();
|
||||||
|
builder.Services.AddScoped<IDiscordNotificationRepository, DiscordNotificationTable>();
|
||||||
|
builder.Services.AddScoped<IUserSourceSubscription, UserSourceSubscriptionTable>();
|
||||||
|
builder.Services.AddScoped<IRefreshTokenRepository, RefreshTokenTable>();
|
||||||
|
|
||||||
|
// Configure Identity
|
||||||
|
builder.Services.AddScoped<IIdentityService, IdentityService>();
|
||||||
|
|
||||||
// Configure Hangfire
|
// Configure Hangfire
|
||||||
builder.Services.AddHangfire(f => f.UseMemoryStorage());
|
builder.Services.AddHangfire(f => f.UseMemoryStorage());
|
||||||
builder.Services.AddHangfireServer();
|
builder.Services.AddHangfireServer();
|
||||||
GlobalConfiguration.Configuration.UseSerilogLogProvider();
|
GlobalConfiguration.Configuration.UseSerilogLogProvider();
|
||||||
|
|
||||||
// Build Health Checks
|
// Add Health Checks
|
||||||
builder.Services.AddHealthChecks()
|
builder.Services.AddHealthChecks()
|
||||||
.AddNpgSql(config.GetValue<string>(ConfigConnectionStringConst.Database) ?? "");
|
.AddNpgSql(config.GetValue<string>(ConfigConnectionStringConst.Database) ?? "");
|
||||||
|
|
||||||
|
|
||||||
builder.Services.AddControllers();
|
builder.Services.AddControllers();
|
||||||
|
|
||||||
SwaggerStartup.ConfigureSwagger(builder.Services);
|
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
||||||
|
builder.Services.AddEndpointsApiExplorer();
|
||||||
|
builder.Services.AddSwaggerGen();
|
||||||
|
|
||||||
builder.Services.Configure<ConnectionStrings>(config.GetSection("ConnectionStrings"));
|
builder.Services.Configure<ConnectionStrings>(config.GetSection("ConnectionStrings"));
|
||||||
builder.Services.Configure<ConfigSectionConnectionStrings>(config.GetSection(ConfigSectionsConst.ConnectionStrings));
|
builder.Services.Configure<ConfigSectionConnectionStrings>(config.GetSection(ConfigSectionsConst.ConnectionStrings));
|
||||||
builder.Services.Configure<ConfigSectionRssModel>(config.GetSection(ConfigSectionsConst.Rss));
|
builder.Services.Configure<ConfigSectionRssModel>(config.GetSection(ConfigSectionsConst.Rss));
|
||||||
builder.Services.Configure<ConfigSectionYoutubeModel>(config.GetSection(ConfigSectionsConst.Youtube));
|
builder.Services.Configure<ConfigSectionYoutubeModel>(config.GetSection(ConfigSectionsConst.Youtube));
|
||||||
|
//builder.Services.Configure<
|
||||||
|
|
||||||
|
// Configure JWT for auth
|
||||||
|
var jwtSettings = new JwtSettings();
|
||||||
|
config.Bind(nameof(jwtSettings), jwtSettings);
|
||||||
|
builder.Services.AddSingleton(jwtSettings);
|
||||||
|
|
||||||
|
var tokenValidationParameters = new TokenValidationParameters
|
||||||
|
{
|
||||||
|
ValidateIssuerSigningKey = true,
|
||||||
|
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSettings.Secret ?? "")),
|
||||||
|
ValidateIssuer = false,
|
||||||
|
ValidateAudience = false,
|
||||||
|
RequireExpirationTime = false,
|
||||||
|
ValidateLifetime = true
|
||||||
|
};
|
||||||
|
builder.Services.AddSingleton(tokenValidationParameters);
|
||||||
|
|
||||||
|
builder.Services.AddAuthentication(x =>
|
||||||
|
{
|
||||||
|
x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||||
|
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||||
|
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||||
|
}).AddJwtBearer(x =>
|
||||||
|
{
|
||||||
|
x.SaveToken = true;
|
||||||
|
x.TokenValidationParameters = tokenValidationParameters;
|
||||||
|
});
|
||||||
|
|
||||||
|
builder.Services.AddSwaggerGen(cfg =>
|
||||||
|
{
|
||||||
|
|
||||||
|
cfg.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme
|
||||||
|
{
|
||||||
|
Description = "The API key to access the API",
|
||||||
|
Type = SecuritySchemeType.ApiKey,
|
||||||
|
Name = "x-api-key",
|
||||||
|
In = ParameterLocation.Header,
|
||||||
|
Scheme = "ApiKeyScheme"
|
||||||
|
});
|
||||||
|
|
||||||
|
cfg.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
|
||||||
|
{
|
||||||
|
Description = "JWT Authorization Header using the bearer scheme",
|
||||||
|
Name = "Authorization",
|
||||||
|
In = ParameterLocation.Header,
|
||||||
|
Type = SecuritySchemeType.ApiKey
|
||||||
|
});
|
||||||
|
|
||||||
|
cfg.AddSecurityRequirement(new OpenApiSecurityRequirement
|
||||||
|
{
|
||||||
|
//{
|
||||||
|
// new OpenApiSecurityScheme
|
||||||
|
// {
|
||||||
|
// Reference = new OpenApiReference
|
||||||
|
// {
|
||||||
|
// Type = ReferenceType.SecurityScheme,
|
||||||
|
// Id = "ApiKey"
|
||||||
|
// },
|
||||||
|
// In = ParameterLocation.Header
|
||||||
|
// },
|
||||||
|
// new List<string>()
|
||||||
|
//},
|
||||||
|
{
|
||||||
|
new OpenApiSecurityScheme
|
||||||
|
{
|
||||||
|
Reference = new OpenApiReference
|
||||||
|
{
|
||||||
|
Type = ReferenceType.SecurityScheme,
|
||||||
|
Id = "Bearer"
|
||||||
|
},
|
||||||
|
Scheme = "oauth2",
|
||||||
|
Name = "Bearer",
|
||||||
|
In = ParameterLocation.Header
|
||||||
|
},
|
||||||
|
new List<string>()
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
IdentityStartup.DefineJwtRequirements(builder.Services, config);
|
|
||||||
|
|
||||||
var app = builder.Build();
|
var app = builder.Build();
|
||||||
|
|
||||||
// Configure the HTTP request pipeline.
|
// Configure the HTTP request pipeline.
|
||||||
|
if (config.GetValue<bool>("EnableSwagger"))
|
||||||
// Enable Swagger if requested based on config
|
|
||||||
if (config.GetValue<bool>(ConfigConst.EnableSwagger))
|
|
||||||
{
|
{
|
||||||
app.UseSwagger();
|
app.UseSwagger();
|
||||||
app.UseSwaggerUI();
|
app.UseSwaggerUI();
|
||||||
@ -62,17 +167,14 @@ if (config.GetValue<bool>(ConfigConst.EnableSwagger))
|
|||||||
|
|
||||||
app.UseHttpsRedirection();
|
app.UseHttpsRedirection();
|
||||||
|
|
||||||
// Enable Hangfire background jobs
|
|
||||||
app.UseHangfireDashboard();
|
app.UseHangfireDashboard();
|
||||||
BackgroundJobs.SetupRecurringJobs(config);
|
BackgroundJobs.SetupRecurringJobs(config);
|
||||||
|
|
||||||
app.UseAuthorization();
|
//app.UseAuthorization();
|
||||||
app.UseAuthentication();
|
app.UseAuthentication();
|
||||||
|
|
||||||
// Add middleware
|
|
||||||
//app.UseMiddleware<ApiKeyAuthAuthentication>();
|
//app.UseMiddleware<ApiKeyAuthAuthentication>();
|
||||||
|
|
||||||
// Add HealthChecks
|
|
||||||
app.MapHealthChecks("/health", new HealthCheckOptions
|
app.MapHealthChecks("/health", new HealthCheckOptions
|
||||||
{
|
{
|
||||||
Predicate = _ => true,
|
Predicate = _ => true,
|
||||||
@ -80,21 +182,6 @@ app.MapHealthChecks("/health", new HealthCheckOptions
|
|||||||
});
|
});
|
||||||
app.MapControllers();
|
app.MapControllers();
|
||||||
|
|
||||||
// Run Database Migrations if requested
|
|
||||||
using var serviceScope = app.Services.CreateScope();
|
|
||||||
if (config.GetValue<bool>(ConfigConst.RunDatabaseMigrationsOnStartup))
|
|
||||||
{
|
|
||||||
await DatabaseStartup.RunDatabaseMigrationsAsync(serviceScope);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
Log.Warning("Database Migrations have been skipped. Make sure you run them on your own");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Inject the roles
|
|
||||||
await DatabaseStartup.InjectIdentityRolesAsync(serviceScope);
|
|
||||||
|
|
||||||
// Start the application
|
|
||||||
app.Run();
|
app.Run();
|
||||||
|
|
||||||
|
|
||||||
@ -128,4 +215,4 @@ static ILogger GetLogger(IConfiguration configuration)
|
|||||||
{ "service.name", "newsbot-collector-api" }
|
{ "service.name", "newsbot-collector-api" }
|
||||||
})
|
})
|
||||||
.CreateLogger();
|
.CreateLogger();
|
||||||
}
|
}
|
@ -16,7 +16,6 @@ public interface IIdentityService
|
|||||||
AuthenticationResult Register(string email, string password);
|
AuthenticationResult Register(string email, string password);
|
||||||
AuthenticationResult Login(string email, string password);
|
AuthenticationResult Login(string email, string password);
|
||||||
AuthenticationResult RefreshToken(string token, string refreshToken);
|
AuthenticationResult RefreshToken(string token, string refreshToken);
|
||||||
void AddRole(string roleName, string userId);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public class IdentityService : IIdentityService
|
public class IdentityService : IIdentityService
|
||||||
@ -179,19 +178,6 @@ public class IdentityService : IIdentityService
|
|||||||
return GenerateJwtToken(user.Result);
|
return GenerateJwtToken(user.Result);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void AddRole(string roleName, string userId)
|
|
||||||
{
|
|
||||||
var user = _userManager.FindByIdAsync(userId);
|
|
||||||
user.Wait();
|
|
||||||
|
|
||||||
if (user.Result is null)
|
|
||||||
{
|
|
||||||
throw new Exception("User was not found");
|
|
||||||
}
|
|
||||||
|
|
||||||
_userManager.AddToRoleAsync(user.Result, roleName);
|
|
||||||
}
|
|
||||||
|
|
||||||
private ClaimsPrincipal? CheckTokenSigner(string token)
|
private ClaimsPrincipal? CheckTokenSigner(string token)
|
||||||
{
|
{
|
||||||
var tokenHandler = new JwtSecurityTokenHandler();
|
var tokenHandler = new JwtSecurityTokenHandler();
|
||||||
|
@ -1,61 +0,0 @@
|
|||||||
using Microsoft.AspNetCore.Identity;
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using Newsbot.Collector.Api.Domain;
|
|
||||||
using Newsbot.Collector.Api.Services;
|
|
||||||
using Newsbot.Collector.Database;
|
|
||||||
using Newsbot.Collector.Database.Repositories;
|
|
||||||
using Newsbot.Collector.Domain.Interfaces;
|
|
||||||
|
|
||||||
namespace Newsbot.Collector.Api.Startup;
|
|
||||||
|
|
||||||
public class DatabaseStartup
|
|
||||||
{
|
|
||||||
public static void BuildDatabase(IServiceCollection services, IConfiguration config)
|
|
||||||
{
|
|
||||||
var dbconn = config.GetConnectionString("Database");
|
|
||||||
services.AddDbContext<DatabaseContext>(o => o.UseNpgsql(dbconn ?? ""));
|
|
||||||
|
|
||||||
// Add identity to our ef connection
|
|
||||||
services.AddIdentity<IdentityUser, IdentityRole>()
|
|
||||||
.AddRoles<IdentityRole>()
|
|
||||||
.AddEntityFrameworkStores<DatabaseContext>();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void InjectTableClasses(IServiceCollection services)
|
|
||||||
{
|
|
||||||
services.AddScoped<IArticlesRepository, ArticlesTable>();
|
|
||||||
services.AddScoped<IDiscordQueueRepository, DiscordQueueTable>();
|
|
||||||
services.AddScoped<IDiscordWebHooksRepository, DiscordWebhooksTable>();
|
|
||||||
services.AddScoped<IIconsRepository, IconsTable>();
|
|
||||||
services.AddScoped<ISourcesRepository, SourcesTable>();
|
|
||||||
services.AddScoped<IDiscordNotificationRepository, DiscordNotificationTable>();
|
|
||||||
services.AddScoped<IUserSourceSubscription, UserSourceSubscriptionTable>();
|
|
||||||
services.AddScoped<IRefreshTokenRepository, RefreshTokenTable>();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void InjectIdentityService(IServiceCollection services)
|
|
||||||
{
|
|
||||||
// Configure Identity
|
|
||||||
services.AddScoped<IIdentityService, IdentityService>();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static async Task RunDatabaseMigrationsAsync(IServiceScope serviceScope)
|
|
||||||
{
|
|
||||||
var dbContext = serviceScope.ServiceProvider.GetRequiredService<DatabaseContext>();
|
|
||||||
await dbContext.Database.MigrateAsync();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static async Task InjectIdentityRolesAsync(IServiceScope serviceScope)
|
|
||||||
{
|
|
||||||
var roleManager = serviceScope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
|
|
||||||
if (!await roleManager.RoleExistsAsync(Authorization.AdministratorsRole))
|
|
||||||
{
|
|
||||||
await roleManager.CreateAsync(new IdentityRole(Authorization.AdministratorsRole));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!await roleManager.RoleExistsAsync(Authorization.UsersRole))
|
|
||||||
{
|
|
||||||
await roleManager.CreateAsync(new IdentityRole(Authorization.UsersRole));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,50 +0,0 @@
|
|||||||
using System.Text;
|
|
||||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|
||||||
using Microsoft.IdentityModel.Tokens;
|
|
||||||
using Newsbot.Collector.Api.Domain;
|
|
||||||
using Newsbot.Collector.Domain.Models.Config;
|
|
||||||
|
|
||||||
namespace Newsbot.Collector.Api.Startup;
|
|
||||||
|
|
||||||
public static class IdentityStartup
|
|
||||||
{
|
|
||||||
public static void DefineJwtRequirements(IServiceCollection services, IConfiguration config)
|
|
||||||
{
|
|
||||||
// Configure JWT for auth and load it into DI so we can use it in the controllers
|
|
||||||
|
|
||||||
var jwtSettings = new JwtSettings();
|
|
||||||
config.Bind(nameof(jwtSettings), jwtSettings);
|
|
||||||
services.AddSingleton(jwtSettings);
|
|
||||||
|
|
||||||
// Configure how the Token Validation will be handled
|
|
||||||
var tokenValidationParameters = new TokenValidationParameters
|
|
||||||
{
|
|
||||||
ValidateIssuerSigningKey = true,
|
|
||||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSettings.Secret ?? "")),
|
|
||||||
ValidateIssuer = false,
|
|
||||||
ValidateAudience = false,
|
|
||||||
RequireExpirationTime = false,
|
|
||||||
ValidateLifetime = true
|
|
||||||
};
|
|
||||||
services.AddSingleton(tokenValidationParameters);
|
|
||||||
|
|
||||||
// Build the Authentication that will be used
|
|
||||||
services.AddAuthentication(x =>
|
|
||||||
{
|
|
||||||
x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
|
|
||||||
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
|
||||||
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
|
||||||
}).AddJwtBearer(x =>
|
|
||||||
{
|
|
||||||
x.SaveToken = true;
|
|
||||||
x.TokenValidationParameters = tokenValidationParameters;
|
|
||||||
});
|
|
||||||
|
|
||||||
// Build the Authorization Policy that the users will conform to.
|
|
||||||
services.AddAuthorization(options =>
|
|
||||||
{
|
|
||||||
options.AddPolicy(Authorization.AdministratorPolicy,
|
|
||||||
b => b.RequireClaim(Authorization.AdministratorClaim, "true"));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,67 +0,0 @@
|
|||||||
using Microsoft.OpenApi.Models;
|
|
||||||
|
|
||||||
namespace Newsbot.Collector.Api.Startup;
|
|
||||||
|
|
||||||
public static class SwaggerStartup
|
|
||||||
{
|
|
||||||
public static void ConfigureSwagger(IServiceCollection services)
|
|
||||||
{
|
|
||||||
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
|
||||||
services.AddEndpointsApiExplorer();
|
|
||||||
services.AddSwaggerGen();
|
|
||||||
|
|
||||||
services.AddEndpointsApiExplorer();
|
|
||||||
services.AddSwaggerGen();
|
|
||||||
|
|
||||||
// Configure swagger authentication
|
|
||||||
services.AddSwaggerGen(cfg =>
|
|
||||||
{
|
|
||||||
cfg.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme
|
|
||||||
{
|
|
||||||
Description = "The API key to access the API",
|
|
||||||
Type = SecuritySchemeType.ApiKey,
|
|
||||||
Name = "x-api-key",
|
|
||||||
In = ParameterLocation.Header,
|
|
||||||
Scheme = "ApiKeyScheme"
|
|
||||||
});
|
|
||||||
|
|
||||||
cfg.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
|
|
||||||
{
|
|
||||||
Description = "JWT Authorization Header using the bearer scheme",
|
|
||||||
Name = "Authorization",
|
|
||||||
In = ParameterLocation.Header,
|
|
||||||
Type = SecuritySchemeType.ApiKey
|
|
||||||
});
|
|
||||||
|
|
||||||
cfg.AddSecurityRequirement(new OpenApiSecurityRequirement
|
|
||||||
{
|
|
||||||
//{
|
|
||||||
// new OpenApiSecurityScheme
|
|
||||||
// {
|
|
||||||
// Reference = new OpenApiReference
|
|
||||||
// {
|
|
||||||
// Type = ReferenceType.SecurityScheme,
|
|
||||||
// Id = "ApiKey"
|
|
||||||
// },
|
|
||||||
// In = ParameterLocation.Header
|
|
||||||
// },
|
|
||||||
// new List<string>()
|
|
||||||
//},
|
|
||||||
{
|
|
||||||
new OpenApiSecurityScheme
|
|
||||||
{
|
|
||||||
Reference = new OpenApiReference
|
|
||||||
{
|
|
||||||
Type = ReferenceType.SecurityScheme,
|
|
||||||
Id = "Bearer"
|
|
||||||
},
|
|
||||||
Scheme = "oauth2",
|
|
||||||
Name = "Bearer",
|
|
||||||
In = ParameterLocation.Header
|
|
||||||
},
|
|
||||||
new List<string>()
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
@ -2,9 +2,6 @@ namespace Newsbot.Collector.Domain.Consts;
|
|||||||
|
|
||||||
public class ConfigConst
|
public class ConfigConst
|
||||||
{
|
{
|
||||||
public const string RunDatabaseMigrationsOnStartup = "RunDatabaseMigrationsOnStartup";
|
|
||||||
public const string ApiKeys = "ApiKeys";
|
|
||||||
|
|
||||||
public const string LoggingDefault = "Logging:LogLevel:Default";
|
public const string LoggingDefault = "Logging:LogLevel:Default";
|
||||||
|
|
||||||
public const string SectionConnectionStrings = "ConnectionStrings";
|
public const string SectionConnectionStrings = "ConnectionStrings";
|
||||||
|
@ -28,14 +28,12 @@ services:
|
|||||||
api:
|
api:
|
||||||
image: newsbot.collector:latest
|
image: newsbot.collector:latest
|
||||||
environment:
|
environment:
|
||||||
# This will run the migrations for you on API Startup.
|
# Used for database migrations
|
||||||
"RunDatabaseMigrationsOnStartup": true
|
GOOSE_DRIVER: "postgres"
|
||||||
|
GOOSE_DBSTRING: "host=localhost user=${PostgresUser} password=${PostgresPassword} dbname=${PostgresDatabaseName} sslmode=disable"
|
||||||
# If this is false then /swagger/index.html will not be active on the API
|
|
||||||
EnableSwagger: true
|
SERVER_ADDRESS: "localhost"
|
||||||
|
|
||||||
JwtSettings__Secret: "ThisNeedsToBeSecretAnd32CharactersLong"
|
|
||||||
|
|
||||||
Logging__LogLevel__Default: "Information"
|
Logging__LogLevel__Default: "Information"
|
||||||
Logging__LogLevel__Microsoft.AspNetCore: "Warning"
|
Logging__LogLevel__Microsoft.AspNetCore: "Warning"
|
||||||
Logging__LogLevel__Hangfire: "Information"
|
Logging__LogLevel__Hangfire: "Information"
|
||||||
@ -58,8 +56,6 @@ services:
|
|||||||
|
|
||||||
# If you want to collect news on Final Fantasy XIV, set this to true
|
# If you want to collect news on Final Fantasy XIV, set this to true
|
||||||
FFXIV__IsEnabled: false
|
FFXIV__IsEnabled: false
|
||||||
|
|
||||||
CodeProjects__IsEnabled: true
|
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD", "curl", "-f", "http://localhost:5000/health"]
|
test: ["CMD", "curl", "-f", "http://localhost:5000/health"]
|
||||||
interval: "1m"
|
interval: "1m"
|
||||||
|
@ -1,5 +0,0 @@
|
|||||||
{
|
|
||||||
"sdk": {
|
|
||||||
"version": "7.0.100"
|
|
||||||
}
|
|
||||||
}
|
|
Loading…
Reference in New Issue
Block a user