Compare commits
6 Commits
5c06865b1f
...
2bc20fccc8
Author | SHA1 | Date | |
---|---|---|---|
2bc20fccc8 | |||
71319c05ef | |||
bc79b507ac | |||
d5278a8be9 | |||
0aa6c1489d | |||
712ce4f4da |
@ -1,11 +1,10 @@
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Newsbot.Collector.Api.Domain;
|
||||
using Newsbot.Collector.Api.Domain.Requests;
|
||||
using Newsbot.Collector.Api.Domain.Response;
|
||||
using Newsbot.Collector.Api.Domain.Results;
|
||||
using Newsbot.Collector.Api.Services;
|
||||
using Newsbot.Collector.Domain.Dto;
|
||||
using Newsbot.Collector.Domain.Entities;
|
||||
|
||||
namespace Newsbot.Collector.Api.Controllers;
|
||||
|
||||
@ -71,6 +70,21 @@ public class AccountController : ControllerBase
|
||||
return CheckIfSuccessful(response);
|
||||
}
|
||||
|
||||
[HttpPost("addRole")]
|
||||
[Authorize(Roles = AuthorizationRoles.Administrators)]
|
||||
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)
|
||||
{
|
||||
if (!result.IsSuccessful)
|
||||
|
@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Newsbot.Collector.Api.Domain;
|
||||
using Newsbot.Collector.Domain.Models.Config;
|
||||
using Newsbot.Collector.Services.Jobs;
|
||||
|
||||
@ -24,6 +25,7 @@ public class CodeProjectController
|
||||
}
|
||||
|
||||
[HttpPost("check")]
|
||||
[Authorize(Roles = AuthorizationRoles.Administrators)]
|
||||
public void PullNow()
|
||||
{
|
||||
BackgroundJob.Enqueue<CodeProjectWatcherJob>(x => x.InitAndExecute(new CodeProjectWatcherJobOptions
|
||||
|
@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Newsbot.Collector.Api.Domain;
|
||||
using Newsbot.Collector.Domain.Models.Config;
|
||||
using Newsbot.Collector.Domain.Models.Config.Sources;
|
||||
using Newsbot.Collector.Services.Jobs;
|
||||
@ -27,6 +28,7 @@ public class RssController
|
||||
}
|
||||
|
||||
[HttpPost("check")]
|
||||
[Authorize(Roles = AuthorizationRoles.Administrators)]
|
||||
public void CheckReddit()
|
||||
{
|
||||
BackgroundJob.Enqueue<RssWatcherJob>(x => x.InitAndExecute(new RssWatcherJobOptions
|
||||
|
@ -2,6 +2,7 @@ using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Newsbot.Collector.Api.Domain;
|
||||
using Newsbot.Collector.Database.Repositories;
|
||||
using Newsbot.Collector.Domain.Consts;
|
||||
using Newsbot.Collector.Domain.Dto;
|
||||
@ -199,12 +200,14 @@ public class SourcesController : ControllerBase
|
||||
return SourceDto.Convert(item);
|
||||
}
|
||||
|
||||
[Authorize(Roles = AuthorizationRoles.Administrators)]
|
||||
[HttpPost("{id}/disable")]
|
||||
public void Disable(Guid id)
|
||||
{
|
||||
_sources.Disable(id);
|
||||
}
|
||||
|
||||
[Authorize(Roles = AuthorizationRoles.Administrators)]
|
||||
[HttpPost("{id}/enable")]
|
||||
public void Enable(Guid id)
|
||||
{
|
||||
@ -212,6 +215,7 @@ public class SourcesController : ControllerBase
|
||||
}
|
||||
|
||||
[HttpDelete("{id}")]
|
||||
[Authorize(Roles = AuthorizationRoles.Administrators)]
|
||||
public void Delete(Guid id, bool purgeOrphanedRecords)
|
||||
{
|
||||
_sources.Delete(id);
|
||||
|
@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Newsbot.Collector.Api.Domain;
|
||||
using Newsbot.Collector.Domain.Models.Config;
|
||||
using Newsbot.Collector.Domain.Models.Config.Sources;
|
||||
using Newsbot.Collector.Services.Jobs;
|
||||
@ -27,6 +28,7 @@ public class YoutubeController
|
||||
}
|
||||
|
||||
[HttpPost("check")]
|
||||
[Authorize(Policy = AuthorizationRoles.Administrators)]
|
||||
public void CheckYoutube()
|
||||
{
|
||||
BackgroundJob.Enqueue<YoutubeWatcherJob>(x => x.InitAndExecute(new YoutubeWatcherJobOptions
|
||||
|
@ -1,16 +1,19 @@
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Newsbot.Collector.Api.Authentication;
|
||||
using Newsbot.Collector.Domain.Entities;
|
||||
using Newsbot.Collector.Domain.Interfaces;
|
||||
|
||||
namespace Newsbot.Collector.Api.Controllers;
|
||||
namespace Newsbot.Collector.Api.Controllers.v1;
|
||||
|
||||
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
|
||||
[ApiController]
|
||||
[Route("api/v1/user")]
|
||||
public class UserController : Controller
|
||||
{
|
||||
private ILogger<UserController> _logger;
|
||||
private IUserSourceSubscription _subscription;
|
||||
private readonly ILogger<UserController> _logger;
|
||||
private readonly IUserSourceSubscription _subscription;
|
||||
|
||||
public UserController(ILogger<UserController> logger, IUserSourceSubscription subscription)
|
||||
{
|
||||
|
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";
|
||||
}
|
7
Newsbot.Collector.Api/Domain/Requests/NewRoleRequest.cs
Normal file
7
Newsbot.Collector.Api/Domain/Requests/NewRoleRequest.cs
Normal file
@ -0,0 +1,7 @@
|
||||
namespace Newsbot.Collector.Api.Domain.Requests;
|
||||
|
||||
public class AddRoleRequest
|
||||
{
|
||||
public string? RoleName { get; set; }
|
||||
public string? UserId { get; set; }
|
||||
}
|
32
Newsbot.Collector.Api/Filters/ApiKeyAuthAttribute.cs
Normal file
32
Newsbot.Collector.Api/Filters/ApiKeyAuthAttribute.cs
Normal file
@ -0,0 +1,32 @@
|
||||
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();
|
||||
}
|
||||
}
|
@ -10,6 +10,7 @@ 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;
|
||||
@ -39,10 +40,12 @@ Log.Information("Starting up");
|
||||
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
|
||||
builder.Services.AddScoped<IArticlesRepository, ArticlesTable>();
|
||||
builder.Services.AddScoped<IDiscordQueueRepository, DiscordQueueTable>();
|
||||
builder.Services.AddScoped<IDiscordWebHooksRepository, DiscordWebhooksTable>();
|
||||
@ -60,7 +63,7 @@ builder.Services.AddHangfire(f => f.UseMemoryStorage());
|
||||
builder.Services.AddHangfireServer();
|
||||
GlobalConfiguration.Configuration.UseSerilogLogProvider();
|
||||
|
||||
// Add Health Checks
|
||||
// Build Health Checks
|
||||
builder.Services.AddHealthChecks()
|
||||
.AddNpgSql(config.GetValue<string>(ConfigConnectionStringConst.Database) ?? "");
|
||||
|
||||
@ -75,13 +78,13 @@ builder.Services.Configure<ConnectionStrings>(config.GetSection("ConnectionStrin
|
||||
builder.Services.Configure<ConfigSectionConnectionStrings>(config.GetSection(ConfigSectionsConst.ConnectionStrings));
|
||||
builder.Services.Configure<ConfigSectionRssModel>(config.GetSection(ConfigSectionsConst.Rss));
|
||||
builder.Services.Configure<ConfigSectionYoutubeModel>(config.GetSection(ConfigSectionsConst.Youtube));
|
||||
//builder.Services.Configure<
|
||||
|
||||
// Configure JWT for auth
|
||||
// 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,
|
||||
@ -93,6 +96,7 @@ var tokenValidationParameters = new TokenValidationParameters
|
||||
};
|
||||
builder.Services.AddSingleton(tokenValidationParameters);
|
||||
|
||||
// Build the Authentication that will be used
|
||||
builder.Services.AddAuthentication(x =>
|
||||
{
|
||||
x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||
@ -104,9 +108,13 @@ builder.Services.AddAuthentication(x =>
|
||||
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",
|
||||
@ -159,7 +167,9 @@ builder.Services.AddSwaggerGen(cfg =>
|
||||
var app = builder.Build();
|
||||
|
||||
// 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.UseSwaggerUI();
|
||||
@ -167,14 +177,17 @@ if (config.GetValue<bool>("EnableSwagger"))
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
// Enable Hangfire background jobs
|
||||
app.UseHangfireDashboard();
|
||||
BackgroundJobs.SetupRecurringJobs(config);
|
||||
|
||||
//app.UseAuthorization();
|
||||
app.UseAuthorization();
|
||||
app.UseAuthentication();
|
||||
|
||||
// Add middleware
|
||||
//app.UseMiddleware<ApiKeyAuthAuthentication>();
|
||||
|
||||
// Add HealthChecks
|
||||
app.MapHealthChecks("/health", new HealthCheckOptions
|
||||
{
|
||||
Predicate = _ => true,
|
||||
@ -182,6 +195,34 @@ app.MapHealthChecks("/health", new HealthCheckOptions
|
||||
});
|
||||
app.MapControllers();
|
||||
|
||||
// Run Database Migrations if requested
|
||||
using var serviceScope = app.Services.CreateScope();
|
||||
if (config.GetValue<bool>(ConfigConst.RunDatabaseMigrationsOnStartup))
|
||||
{
|
||||
var dbContext = serviceScope.ServiceProvider.GetRequiredService<DatabaseContext>();
|
||||
dbContext.Database.Migrate();
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
Log.Warning("Database Migrations have been skipped. Make sure you run them on your own");
|
||||
}
|
||||
|
||||
// Inject the roles
|
||||
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();
|
||||
|
||||
|
||||
@ -215,4 +256,4 @@ static ILogger GetLogger(IConfiguration configuration)
|
||||
{ "service.name", "newsbot-collector-api" }
|
||||
})
|
||||
.CreateLogger();
|
||||
}
|
||||
}
|
||||
|
@ -16,6 +16,7 @@ public interface IIdentityService
|
||||
AuthenticationResult Register(string email, string password);
|
||||
AuthenticationResult Login(string email, string password);
|
||||
AuthenticationResult RefreshToken(string token, string refreshToken);
|
||||
void AddRole(string roleName, string userId);
|
||||
}
|
||||
|
||||
public class IdentityService : IIdentityService
|
||||
@ -178,6 +179,19 @@ public class IdentityService : IIdentityService
|
||||
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)
|
||||
{
|
||||
var tokenHandler = new JwtSecurityTokenHandler();
|
||||
|
@ -2,6 +2,9 @@ namespace Newsbot.Collector.Domain.Consts;
|
||||
|
||||
public class ConfigConst
|
||||
{
|
||||
public const string RunDatabaseMigrationsOnStartup = "RunDatabaseMigrationsOnStartup";
|
||||
public const string ApiKeys = "ApiKeys";
|
||||
|
||||
public const string LoggingDefault = "Logging:LogLevel:Default";
|
||||
|
||||
public const string SectionConnectionStrings = "ConnectionStrings";
|
||||
|
@ -28,12 +28,14 @@ services:
|
||||
api:
|
||||
image: newsbot.collector:latest
|
||||
environment:
|
||||
# Used for database migrations
|
||||
GOOSE_DRIVER: "postgres"
|
||||
GOOSE_DBSTRING: "host=localhost user=${PostgresUser} password=${PostgresPassword} dbname=${PostgresDatabaseName} sslmode=disable"
|
||||
|
||||
SERVER_ADDRESS: "localhost"
|
||||
|
||||
# This will run the migrations for you on API Startup.
|
||||
"RunDatabaseMigrationsOnStartup": true
|
||||
|
||||
# If this is false then /swagger/index.html will not be active on the API
|
||||
EnableSwagger: true
|
||||
|
||||
JwtSettings__Secret: "ThisNeedsToBeSecretAnd32CharactersLong"
|
||||
|
||||
Logging__LogLevel__Default: "Information"
|
||||
Logging__LogLevel__Microsoft.AspNetCore: "Warning"
|
||||
Logging__LogLevel__Hangfire: "Information"
|
||||
@ -56,6 +58,8 @@ services:
|
||||
|
||||
# If you want to collect news on Final Fantasy XIV, set this to true
|
||||
FFXIV__IsEnabled: false
|
||||
|
||||
CodeProjects__IsEnabled: true
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-f", "http://localhost:5000/health"]
|
||||
interval: "1m"
|
||||
|
Loading…
Reference in New Issue
Block a user