Compare commits
No commits in common. "3697093df1b111ce71909df89646b1105d39fedb" and "2bc20fccc82f9998ec2994c396d3c71518c5a88d" have entirely different histories.
3697093df1
...
2bc20fccc8
@ -3,7 +3,7 @@ using Newsbot.Collector.Domain.Consts;
|
||||
using Newsbot.Collector.Domain.Models.Config;
|
||||
using Newsbot.Collector.Services.Jobs;
|
||||
|
||||
namespace Newsbot.Collector.Api.Startup;
|
||||
namespace Newsbot.Collector.Api;
|
||||
|
||||
public static class BackgroundJobs
|
||||
{
|
@ -6,15 +6,15 @@ using Newsbot.Collector.Api.Domain.Response;
|
||||
using Newsbot.Collector.Api.Domain.Results;
|
||||
using Newsbot.Collector.Api.Services;
|
||||
|
||||
namespace Newsbot.Collector.Api.Controllers.v1;
|
||||
namespace Newsbot.Collector.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("/api/v1/account")]
|
||||
public class IdentityController : ControllerBase
|
||||
[Route("/api/account")]
|
||||
public class AccountController : ControllerBase
|
||||
{
|
||||
private IIdentityService _identityService;
|
||||
|
||||
public IdentityController(IIdentityService identityService)
|
||||
public AccountController(IIdentityService identityService)
|
||||
{
|
||||
_identityService = identityService;
|
||||
}
|
||||
@ -71,7 +71,7 @@ public class IdentityController : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPost("addRole")]
|
||||
[Authorize(Roles = Authorization.AdministratorsRole)]
|
||||
[Authorize(Roles = AuthorizationRoles.Administrators)]
|
||||
public ActionResult AddRole([FromBody] AddRoleRequest request)
|
||||
{
|
||||
try
|
@ -25,7 +25,7 @@ public class CodeProjectController
|
||||
}
|
||||
|
||||
[HttpPost("check")]
|
||||
[Authorize(Roles = Authorization.AdministratorsRole)]
|
||||
[Authorize(Roles = AuthorizationRoles.Administrators)]
|
||||
public void PullNow()
|
||||
{
|
||||
BackgroundJob.Enqueue<CodeProjectWatcherJob>(x => x.InitAndExecute(new CodeProjectWatcherJobOptions
|
||||
|
@ -28,7 +28,7 @@ public class RssController
|
||||
}
|
||||
|
||||
[HttpPost("check")]
|
||||
[Authorize(Roles = Authorization.AdministratorsRole)]
|
||||
[Authorize(Roles = AuthorizationRoles.Administrators)]
|
||||
public void CheckReddit()
|
||||
{
|
||||
BackgroundJob.Enqueue<RssWatcherJob>(x => x.InitAndExecute(new RssWatcherJobOptions
|
||||
|
@ -200,14 +200,14 @@ public class SourcesController : ControllerBase
|
||||
return SourceDto.Convert(item);
|
||||
}
|
||||
|
||||
[Authorize(Roles = Authorization.AdministratorsRole)]
|
||||
[Authorize(Roles = AuthorizationRoles.Administrators)]
|
||||
[HttpPost("{id}/disable")]
|
||||
public void Disable(Guid id)
|
||||
{
|
||||
_sources.Disable(id);
|
||||
}
|
||||
|
||||
[Authorize(Roles = Authorization.AdministratorsRole)]
|
||||
[Authorize(Roles = AuthorizationRoles.Administrators)]
|
||||
[HttpPost("{id}/enable")]
|
||||
public void Enable(Guid id)
|
||||
{
|
||||
@ -215,7 +215,7 @@ public class SourcesController : ControllerBase
|
||||
}
|
||||
|
||||
[HttpDelete("{id}")]
|
||||
[Authorize(Roles = Authorization.AdministratorsRole)]
|
||||
[Authorize(Roles = AuthorizationRoles.Administrators)]
|
||||
public void Delete(Guid id, bool purgeOrphanedRecords)
|
||||
{
|
||||
_sources.Delete(id);
|
||||
|
@ -28,7 +28,7 @@ public class YoutubeController
|
||||
}
|
||||
|
||||
[HttpPost("check")]
|
||||
[Authorize(Policy = Authorization.AdministratorsRole)]
|
||||
[Authorize(Policy = AuthorizationRoles.Administrators)]
|
||||
public void CheckYoutube()
|
||||
{
|
||||
BackgroundJob.Enqueue<YoutubeWatcherJob>(x => x.InitAndExecute(new YoutubeWatcherJobOptions
|
||||
|
@ -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;
|
||||
}
|
6
Newsbot.Collector.Api/Domain/AuthorizationRoles.cs
Normal file
6
Newsbot.Collector.Api/Domain/AuthorizationRoles.cs
Normal file
@ -0,0 +1,6 @@
|
||||
namespace Newsbot.Collector.Api.Domain;
|
||||
|
||||
public class AuthorizationRoles
|
||||
{
|
||||
public const string Administrators = "Administrators";
|
||||
}
|
@ -1,13 +1,27 @@
|
||||
using System.Text;
|
||||
using Hangfire;
|
||||
using Hangfire.MemoryStorage;
|
||||
using HealthChecks.UI.Client;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
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.Domain;
|
||||
using Newsbot.Collector.Api.Services;
|
||||
using Newsbot.Collector.Database;
|
||||
using Newsbot.Collector.Database.Repositories;
|
||||
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.Config;
|
||||
using Newsbot.Collector.Domain.Models.Config.Sources;
|
||||
using Serilog;
|
||||
using Serilog.Events;
|
||||
using ILogger = Serilog.ILogger;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
@ -23,10 +37,26 @@ Log.Logger = GetLogger(config);
|
||||
Log.Information("Starting up");
|
||||
|
||||
// configure Entity Framework
|
||||
var dbconn = config.GetConnectionString("Database");
|
||||
builder.Services.AddDbContext<DatabaseContext>(o => o.UseNpgsql(dbconn ?? ""));
|
||||
|
||||
// Configure how Identity will be managed
|
||||
builder.Services.AddIdentity<IdentityUser, IdentityRole>()
|
||||
.AddRoles<IdentityRole>()
|
||||
.AddEntityFrameworkStores<DatabaseContext>();
|
||||
|
||||
// Allow the controllers to access all the table repositories based on the interface
|
||||
DatabaseStartup.BuildDatabase(builder.Services, config);
|
||||
DatabaseStartup.InjectTableClasses(builder.Services);
|
||||
DatabaseStartup.InjectIdentityService(builder.Services);
|
||||
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
|
||||
builder.Services.AddHangfire(f => f.UseMemoryStorage());
|
||||
@ -40,14 +70,99 @@ builder.Services.AddHealthChecks()
|
||||
|
||||
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<ConfigSectionConnectionStrings>(config.GetSection(ConfigSectionsConst.ConnectionStrings));
|
||||
builder.Services.Configure<ConfigSectionRssModel>(config.GetSection(ConfigSectionsConst.Rss));
|
||||
builder.Services.Configure<ConfigSectionYoutubeModel>(config.GetSection(ConfigSectionsConst.Youtube));
|
||||
|
||||
IdentityStartup.DefineJwtRequirements(builder.Services, 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);
|
||||
builder.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
|
||||
};
|
||||
builder.Services.AddSingleton(tokenValidationParameters);
|
||||
|
||||
// Build the Authentication that will be used
|
||||
builder.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.
|
||||
builder.Services.AddAuthorization(options =>
|
||||
options.AddPolicy(Authorization.AdministratorPolicy, b => b.RequireClaim( Authorization.AdministratorClaim, "true") ));
|
||||
|
||||
// Configure swagger authentication
|
||||
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>()
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
@ -84,7 +199,9 @@ app.MapControllers();
|
||||
using var serviceScope = app.Services.CreateScope();
|
||||
if (config.GetValue<bool>(ConfigConst.RunDatabaseMigrationsOnStartup))
|
||||
{
|
||||
await DatabaseStartup.RunDatabaseMigrationsAsync(serviceScope);
|
||||
var dbContext = serviceScope.ServiceProvider.GetRequiredService<DatabaseContext>();
|
||||
dbContext.Database.Migrate();
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
@ -92,7 +209,18 @@ else
|
||||
}
|
||||
|
||||
// Inject the roles
|
||||
await DatabaseStartup.InjectIdentityRolesAsync(serviceScope);
|
||||
var roleManager = serviceScope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
|
||||
if (!await roleManager.RoleExistsAsync("Administrators"))
|
||||
{
|
||||
var adminRole = new IdentityRole("Administrators");
|
||||
await roleManager.CreateAsync(adminRole);
|
||||
}
|
||||
|
||||
if (!await roleManager.RoleExistsAsync("Users"))
|
||||
{
|
||||
var userRole = new IdentityRole("Users");
|
||||
await roleManager.CreateAsync(userRole);
|
||||
}
|
||||
|
||||
// Start the application
|
||||
app.Run();
|
||||
|
@ -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>()
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
@ -1,5 +0,0 @@
|
||||
{
|
||||
"sdk": {
|
||||
"version": "7.0.100"
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user