Finished adding user support and ability to update specific novels or set your last read chapter

This commit is contained in:
2022-07-17 20:34:06 -04:00
parent e4529e11c0
commit b5c4146d4d
34 changed files with 589 additions and 59 deletions

View File

@@ -84,8 +84,18 @@ public abstract class BaseRepository<TEntityType> : IRepository<TEntityType> whe
return GetAllIncludedQueryable().FirstOrDefault(predicate);
}
public virtual async Task<IEnumerable<TEntityType?>> GetWhereIncluded(IEnumerable<TEntityType> entities)
{
return await GetWhereIncluded(entities.Contains);
}
public virtual async Task<IEnumerable<TEntityType>> GetWhereIncluded(Func<TEntityType, bool> predicate)
{
return GetAllIncludedQueryable().AsEnumerable().Where(predicate);
}
public virtual async Task PersistChanges()
{
await DbContext.SaveChangesAsync();
}
}

View File

@@ -16,4 +16,6 @@ public interface IRepository<TEntityType> : IRepository where TEntityType : Base
Task<IEnumerable<TEntityType>> GetWhereIncluded(Func<TEntityType, bool> predicate);
Task<IEnumerable<TEntityType>> GetAllIncluded();
Task<IEnumerable<TEntityType>> UpsertMany(IEnumerable<TEntityType> entities, bool saveAfter=true);
Task PersistChanges();
Task<IEnumerable<TEntityType?>> GetWhereIncluded(IEnumerable<TEntityType> entities);
}

View File

@@ -0,0 +1,9 @@
using Treestar.Shared.Models.DBDomain;
namespace DBConnection.Repositories.Interfaces;
public interface IUserRepository : IRepository<User>
{
Task<User> AssignNovelsToUser(User user, List<Novel> novels);
Task<User> UpdateLastChapterRead(User user, Novel novel, int chapterRead);
}

View File

@@ -0,0 +1,49 @@
using DBConnection.Contexts;
using DBConnection.Repositories.Interfaces;
using Microsoft.EntityFrameworkCore;
using Treestar.Shared.Models.DBDomain;
namespace DBConnection.Repositories;
public class UserRepository : BaseRepository<User>, IUserRepository
{
private readonly INovelRepository _novelRepository;
public UserRepository(AppDbContext dbContext, INovelRepository novelRepository) : base(dbContext)
{
_novelRepository = novelRepository;
}
protected override IQueryable<User> GetAllIncludedQueryable()
{
return DbContext.Users.Include(u => u.WatchedNovels);
}
public async Task<User> AssignNovelsToUser(User user, List<Novel> novels)
{
var dbUser = await GetIncluded(user);
if (dbUser == null)
{
return user;
}
var dbNovels = await _novelRepository.GetWhereIncluded(novels);
var newNovels = dbNovels.Except(dbUser.WatchedNovels.Select(un => un.Novel));
var newUserNovels = newNovels.Select(n => new UserNovel
{
Novel = n,
User = dbUser
});
dbUser.WatchedNovels.AddRange(newUserNovels);
await DbContext.SaveChangesAsync();
return dbUser;
}
public async Task<User> UpdateLastChapterRead(User user, Novel novel, int chapterRead)
{
var dbUser = await GetIncluded(user);
var userNovel = dbUser.WatchedNovels.FirstOrDefault(i => i.NovelUrl == novel.Url);
userNovel.LastChapterRead = chapterRead;
await DbContext.SaveChangesAsync();
return dbUser;
}
}

View File

@@ -9,9 +9,11 @@ namespace Treestar.Shared.AccessLayers;
public abstract class ApiAccessLayer
{
private readonly HttpClient _httpClient;
private readonly IAccessLayerAuthenticationProvider _authenticationProvider;
protected ApiAccessLayer(string apiBaseUrl)
protected ApiAccessLayer(string apiBaseUrl, IAccessLayerAuthenticationProvider authenticationProvider)
{
_authenticationProvider = authenticationProvider;
var handler = new HttpClientHandler()
{
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
@@ -22,6 +24,7 @@ public abstract class ApiAccessLayer
private async Task<HttpResponseWrapper> SendRequest(HttpRequestMessage message)
{
await _authenticationProvider.AddAuthentication(message);
var response = await _httpClient.SendAsync(message);
return new HttpResponseWrapper()
{

View File

@@ -0,0 +1,6 @@
namespace Treestar.Shared.AccessLayers;
public interface IAccessLayerAuthenticationProvider
{
Task AddAuthentication(HttpRequestMessage request);
}

View File

@@ -0,0 +1,32 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
namespace Treestar.Shared.Authentication.JwtBearer;
public static class JWTAuthenticationExtension
{
public static void AddJwtBearerAuth(this IServiceCollection services, IConfiguration configuration)
{
var jwtAuthOptions = configuration.GetRequiredSection(JwtBearerAuthenticationOptions.ConfigrationSection)
.Get<JwtBearerAuthenticationOptions>();
services.AddAuthentication(opt =>
{
opt.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(opt =>
{
opt.Authority = jwtAuthOptions.Authority;
opt.Audience = jwtAuthOptions.Audience;
opt.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = ClaimTypes.Name,
ValidateAudience = !string.IsNullOrEmpty(jwtAuthOptions.Audience),
ValidateIssuer = true,
ValidateIssuerSigningKey = true,
ValidateLifetime = true
};
});
}
}

View File

@@ -0,0 +1,8 @@
namespace Treestar.Shared.Authentication.JwtBearer;
public class JwtBearerAuthenticationOptions
{
public const string ConfigrationSection = "JwtBearerAuthOptions";
public string Authority { get; set; } = null!;
public string? Audience { get; set; }
}

View File

@@ -0,0 +1,45 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using WebNovelPortal.Authentication;
namespace Treestar.Shared.Authentication.OIDC;
public static class AuthenticationExtension
{
public static void AddOIDCAuth(this IServiceCollection services, IConfiguration configuration)
{
var oidcConfig = configuration.GetRequiredSection(OpenIdConnectAuthenticationOptions.ConfigurationSection)
.Get<OpenIdConnectAuthenticationOptions>();
services.AddAuthentication(opt =>
{
opt.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
opt.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(opt =>
{
opt.Authority = oidcConfig.Authority;
opt.ClientId = oidcConfig.ClientId;
opt.ClientSecret = oidcConfig.ClientSecret;
opt.ResponseType = OpenIdConnectResponseType.Code;
opt.GetClaimsFromUserInfoEndpoint = false;
opt.SaveTokens = true;
opt.UseTokenLifetime = true;
foreach (var scope in oidcConfig.Scopes.Split(" "))
{
opt.Scope.Add(scope);
}
opt.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = ClaimTypes.Name
};
});
}
}

View File

@@ -0,0 +1,10 @@
namespace WebNovelPortal.Authentication;
public class OpenIdConnectAuthenticationOptions
{
public const string ConfigurationSection = "OIDCAuthOptions";
public string Authority { get; set; }
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string Scopes { get; set; }
}

View File

@@ -17,5 +17,23 @@ namespace Treestar.Shared.Models.DBDomain
public NovelStatus Status { get; set; }
public DateTime LastUpdated { get; set; }
public DateTime DatePosted { get; set; }
protected bool Equals(Novel other)
{
return Url == other.Url;
}
public override bool Equals(object? obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Novel) obj);
}
public override int GetHashCode()
{
return Url.GetHashCode();
}
}
}

View File

@@ -10,5 +10,23 @@ namespace Treestar.Shared.Models.DBDomain
public int Id { get; set; }
public string Email { get; set; }
public List<UserNovel> WatchedNovels { get; set; }
protected bool Equals(User other)
{
return Id == other.Id;
}
public override bool Equals(object? obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((User) obj);
}
public override int GetHashCode()
{
return Id;
}
}
}

View File

@@ -10,5 +10,23 @@ namespace Treestar.Shared.Models.DBDomain
[JsonIgnore]
public User User { get; set; }
public int LastChapterRead { get; set; }
protected bool Equals(UserNovel other)
{
return UserId == other.UserId && NovelUrl == other.NovelUrl;
}
public override bool Equals(object? obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((UserNovel) obj);
}
public override int GetHashCode()
{
return HashCode.Combine(UserId, NovelUrl);
}
}
}

View File

@@ -7,14 +7,26 @@
</PropertyGroup>
<ItemGroup>
<Folder Include="BlazorComponents" />
<Folder Include="Interfaces" />
<Folder Include="Utility" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.7" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="6.0.7" />
<PackageReference Include="Microsoft.AspNetCore.WebUtilities" Version="2.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Abstractions" Version="6.0.7" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
</ItemGroup>
<ItemGroup>
<Reference Include="Microsoft.Extensions.Configuration.Abstractions">
<HintPath>..\..\..\..\..\usr\share\dotnet\shared\Microsoft.AspNetCore.App\6.0.0\Microsoft.Extensions.Configuration.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.DependencyInjection.Abstractions">
<HintPath>..\..\..\..\..\usr\share\dotnet\shared\Microsoft.AspNetCore.App\6.0.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll</HintPath>
</Reference>
</ItemGroup>
</Project>

View File

@@ -8,13 +8,13 @@ namespace WebNovelPortal.AccessLayers;
public class WebApiAccessLayer : ApiAccessLayer
{
public WebApiAccessLayer(string apiBaseUrl) : base(apiBaseUrl)
public WebApiAccessLayer(string apiBaseUrl, IAccessLayerAuthenticationProvider authenticationProvider) : base(apiBaseUrl, authenticationProvider)
{
}
public async Task<List<Novel>?> GetNovels()
public async Task<List<UserNovel>?> GetNovels()
{
return (await SendRequest<List<Novel>>("novel", HttpMethod.Get)).ResponseObject;
return (await SendRequest<List<UserNovel>>("novel", HttpMethod.Get)).ResponseObject;
}
public async Task<Novel?> RequestNovelScrape(string url)
@@ -23,9 +23,9 @@ public class WebApiAccessLayer : ApiAccessLayer
new ScrapeNovelRequest {NovelUrl = url})).ResponseObject;
}
public async Task<Novel?> GetNovel(string guid)
public async Task<UserNovel?> GetNovel(string guid)
{
return (await SendRequest<Novel?>($"novel/{guid}", HttpMethod.Get)).ResponseObject;
return (await SendRequest<UserNovel?>($"novel/{guid}", HttpMethod.Get)).ResponseObject;
}
public async Task<ScrapeNovelsResponse?> ScrapeNovels(List<string> novelUrls)
@@ -33,4 +33,13 @@ public class WebApiAccessLayer : ApiAccessLayer
return (await SendRequest<ScrapeNovelsResponse>("novel/scrapeNovels", HttpMethod.Post, null,
new ScrapeNovelsRequest {NovelUrls = novelUrls})).ResponseObject;
}
public async Task UpdateLastChapterRead(Novel novel, int chapter)
{
await SendRequest("novel/updateLastChapterRead", HttpMethod.Patch, new Dictionary<string, string>
{
{"novelGuid", novel.Guid.ToString()},
{"chapter", chapter.ToString()}
}, null);
}
}

View File

@@ -1,6 +1,7 @@
<Router AppAssembly="@typeof(App).Assembly">
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)"/>
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)"/>
<FocusOnNavigate RouteData="@routeData" Selector="h1"/>
</Found>
<NotFound>
@@ -9,4 +10,5 @@
<p role="alert">Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</Router>
</CascadingAuthenticationState>

View File

@@ -0,0 +1,29 @@
using System.Net.Http.Headers;
using System.Text.Json;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Treestar.Shared.AccessLayers;
namespace WebNovelPortal.Authentication;
public class BlazorAccessLayerAuthProvider : IAccessLayerAuthenticationProvider
{
private readonly IHttpContextAccessor _httpContextAccessor;
public BlazorAccessLayerAuthProvider(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public async Task AddAuthentication(HttpRequestMessage request)
{
var idToken = await _httpContextAccessor.HttpContext.GetTokenAsync(OpenIdConnectParameterNames.IdToken);
if (!string.IsNullOrEmpty(idToken))
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", idToken);
}
}
}

View File

@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
@@ -13,17 +14,21 @@ namespace WebNovelPortal.Controllers
public class AccountController : ControllerBase
{
[HttpGet]
[Route("account/login")]
public async Task Login()
[Route("login")]
public async Task Login(string redirect="/")
{
await HttpContext.ChallengeAsync();
await HttpContext.ChallengeAsync(new AuthenticationProperties
{
RedirectUri = redirect
});
}
[HttpGet]
[Route("account/logout")]
[Route("logout")]
public async Task Logout()
{
await HttpContext.SignOutAsync();
Response.Redirect("/");
}
}
}

View File

@@ -0,0 +1,17 @@
@page "/Auth0InfoDump"
@using Microsoft.AspNetCore.Authentication
@using Microsoft.IdentityModel.Protocols.OpenIdConnect
<h3>Auth0InfoDump</h3>
<b>IdToken: </b> @IdToken
@code {
[Inject] private IHttpContextAccessor _contextAccessor { get; set; }
private string IdToken { get; set; }
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
var context = _contextAccessor.HttpContext;
IdToken = await context.GetTokenAsync(OpenIdConnectParameterNames.IdToken);
}
}

View File

@@ -7,20 +7,35 @@
<LoadingDisplay/>
return;
}
@if (!authenticated)
{
<div>you must login</div>
return;
}
<input @bind="NovelUrl" disabled="@awaitingRequest"/><button disabled="@IsDisabled()" onclick="@(() => RequestNovelScrape(NovelUrl))">Scrape</button><br/>
<button onclick="@UpdateNovels" disabled="@IsDisabled()">Update Novels</button>
<NovelList Novels="@novels"/>
<NovelList Novels="@novels" InputDisabled="awaitingRequest" HandleUpdateNovelRequest="UpdateNovel"/>
@code {
[Inject]
WebApiAccessLayer api { get; set; }
[CascadingParameter]
Task<AuthenticationState> AuthenticationStateTask { get; set; }
string NovelUrl { get; set; }
List<Novel> novels = new List<Novel>();
List<UserNovel> novels = new List<UserNovel>();
protected bool loading = true;
protected bool awaitingRequest = false;
protected bool authenticated = false;
protected override async Task OnInitializedAsync()
{
authenticated = (await AuthenticationStateTask).User.Identity.IsAuthenticated;
SetLoading(authenticated);
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
if (firstRender && authenticated)
{
await RefreshNovels();
}
@@ -45,9 +60,17 @@
async Task UpdateNovels()
{
SetAwaitingRequest(true);
var res = await api.ScrapeNovels(novels.Select(i => i.Url).ToList());
SetAwaitingRequest(false);
var res = await api.ScrapeNovels(novels.Select(i => i.Novel.Url).ToList());
await RefreshNovels();
SetAwaitingRequest(false);
}
async Task UpdateNovel(Novel novel)
{
SetAwaitingRequest(true);
var res = await api.RequestNovelScrape(novel.Url);
await RefreshNovels();
SetAwaitingRequest(false);
}
bool IsDisabled()

View File

@@ -7,20 +7,24 @@
}
else
{
<h3><a href="@Novel.Url">@(Novel.Title)</a></h3>
<h4>Author: <a href="@Novel.Author?.Url">@(Novel.Author?.Name ?? "Anonymous")</a></h4>
<h4>Date Posted: @Novel.DatePosted</h4>
<h4>Date Updated: @Novel.LastUpdated</h4>
<h3><a href="@Novel.Novel.Url">@(Novel.Novel.Title)</a></h3>
<h4>Author: <a href="@Novel.Novel.Author?.Url">@(Novel.Novel.Author?.Name ?? "Anonymous")</a></h4>
<h4>Date Posted: @Novel.Novel.DatePosted</h4>
<h4>Date Updated: @Novel.Novel.LastUpdated</h4>
<h4>Tags</h4>
<ul>
@foreach (var tag in Novel.Tags)
@foreach (var tag in Novel.Novel.Tags)
{
<li>@tag.TagValue</li>
}
</ul>
<h4>Chapters</h4>
<h4>Chapters (Read <input @bind="currentLastChapter" /> / @Novel.Novel.Chapters.Count())</h4>
@if (currentLastChapter != originalLastChapter)
{
<button disabled="@awaitingRequest" @onclick="@UpdateLastReadChapter">Save</button>
}
<ol>
@foreach (var chapter in Novel.Chapters.OrderBy(i => i.ChapterNumber))
@foreach (var chapter in Novel.Novel.Chapters.OrderBy(i => i.ChapterNumber))
{
<li><a href="@chapter.Url">@chapter.Name</a></li>
}
@@ -32,16 +36,40 @@ else
public string? NovelId { get; set; }
[Inject]
public WebApiAccessLayer api { get; set; }
Novel? Novel { get; set; }
UserNovel? Novel { get; set; }
int originalLastChapter;
int currentLastChapter;
bool awaitingRequest;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
Novel = await api.GetNovel(NovelId);
StateHasChanged();
await UpdateNovelDetails();
}
await base.OnAfterRenderAsync(firstRender);
}
private async Task UpdateNovelDetails()
{
Novel = await api.GetNovel(NovelId);
originalLastChapter = Novel.LastChapterRead;
currentLastChapter = originalLastChapter;
StateHasChanged();
}
private async Task UpdateLastReadChapter()
{
SetAwaitingRequest(true);
await api.UpdateLastChapterRead(Novel.Novel, currentLastChapter);
await UpdateNovelDetails();
SetAwaitingRequest(false);
}
private void SetAwaitingRequest(bool enabled)
{
awaitingRequest = enabled;
StateHasChanged();
}
}

View File

@@ -1,18 +1,24 @@
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Newtonsoft.Json;
using Treestar.Shared.AccessLayers;
using Treestar.Shared.Authentication.OIDC;
using WebNovelPortal.AccessLayers;
using WebNovelPortal.Authentication;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddScoped(fac => new WebApiAccessLayer(builder.Configuration["WebAPIUrl"]));
builder.Services.AddScoped<IAccessLayerAuthenticationProvider, BlazorAccessLayerAuthProvider>();
builder.Services.AddScoped(fac => new WebApiAccessLayer(builder.Configuration["WebAPIUrl"], fac.GetRequiredService<IAccessLayerAuthenticationProvider>()));
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddHttpContextAccessor();
builder.Services.AddControllers().AddNewtonsoftJson(opt =>
{
opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
builder.Services.AddOIDCAuth(builder.Configuration);
var app = builder.Build();
@@ -30,6 +36,9 @@ app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");
app.MapControllers();

View File

@@ -0,0 +1,21 @@
<AuthorizeView>
<Authorized>
Hello, @(LoggedInName)!
<a href="api/Account/logout">Log out</a>
</Authorized>
<NotAuthorized>
<a href="api/account/login?redirect=/">Log in</a>
</NotAuthorized>
</AuthorizeView>
@code {
[CascadingParameter]
Task<AuthenticationState> AuthenticationState { get; set; }
private string LoggedInName { get; set; }
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
LoggedInName = (await AuthenticationState).User.Identity.Name;
}
}

View File

@@ -1,4 +1,5 @@
@using Microsoft.AspNetCore.Components
@using WebNovelPortal.AccessLayers
<h1>Novels</h1>
<table>
@@ -12,16 +13,19 @@
{
<tr>
<td>
<a href="@($"/novel/{novel.Guid}")">@novel.Title</a>
<a href="@($"/novel/{novel.Novel.Guid}")">@novel.Novel.Title</a>
</td>
<td>
<a href="@novel.Author?.Url">@(novel.Author?.Name ?? "Anonymous")</a>
<a href="@novel.Novel.Author?.Url">@(novel.Novel.Author?.Name ?? "Anonymous")</a>
</td>
<td>
@novel.Chapters.Count
@novel.Novel.Chapters.Count
</td>
<td>
@novel.LastUpdated
@novel.Novel.LastUpdated
</td>
<td>
<button disabled="@InputDisabled" @onclick="@(()=>HandleUpdateNovelRequest.InvokeAsync(novel.Novel))">Update</button>
</td>
</tr>
}
@@ -29,5 +33,13 @@
@code {
[Parameter]
public List<Novel> Novels { get; set; }
public List<UserNovel> Novels { get; set; }
[Parameter]
public EventCallback<Novel> HandleUpdateNovelRequest { get; set; }
[Parameter]
public bool InputDisabled { get; set; }
[Inject]
private WebApiAccessLayer Api { get; set; }
}

View File

@@ -9,7 +9,7 @@
<main>
<div class="top-row px-4">
<a href="https://docs.microsoft.com/aspnet/" target="_blank">About</a>
<LoginDisplay/>
</div>
<article class="content px-4">

View File

@@ -7,6 +7,7 @@
article {
flex: 1 1 auto;
width: 100%;
}
main {

View File

@@ -5,10 +5,10 @@
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<UserSecretsId>32b7cf85-871e-439d-88a2-f8ff5186dafd</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<Folder Include="Authentication" />
<Folder Include="Controllers" />
<Folder Include="Data" />
</ItemGroup>
@@ -18,6 +18,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="6.0.7" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="6.0.7" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="6.0.7" />
</ItemGroup>

View File

@@ -5,6 +5,12 @@
"Microsoft.AspNetCore": "Warning"
}
},
"OIDCAuthOptions": {
"Authority": "authority_here",
"ClientId": "clientid_here",
"ClientSecret": "clientsecret_here",
"Scopes": "openid profile email"
},
"AllowedHosts": "*",
"WebAPIUrl": "https://localhost:7137/api/"
}

View File

@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Treestar.Shared.Models.DBDomain;
using WebNovelPortalAPI.Middleware;
namespace WebNovelPortalAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class AuthorizedController : ControllerBase
{
protected int UserId
{
get
{
return (int) (HttpContext.Items[EnsureUserCreatedMiddleware.UserIdItemName] ?? 0);
}
}
public AuthorizedController()
{
}
}
}

View File

@@ -5,6 +5,7 @@ using System.Threading.Tasks;
using DBConnection;
using DBConnection.Repositories;
using DBConnection.Repositories.Interfaces;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Treestar.Shared.Models.DBDomain;
@@ -18,15 +19,18 @@ namespace WebNovelPortalAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class NovelController : ControllerBase
[Authorize]
public class NovelController : AuthorizedController
{
private readonly INovelRepository _novelRepository;
private readonly IUserRepository _userRepository;
private readonly IEnumerable<IScraper> _scrapers;
public NovelController(IEnumerable<IScraper> scrapers, INovelRepository novelRepository)
public NovelController(IEnumerable<IScraper> scrapers, INovelRepository novelRepository, IUserRepository userRepository)
{
_scrapers = scrapers;
_novelRepository = novelRepository;
_userRepository = userRepository;
}
private async Task<Novel?> ScrapeNovel(string url)
@@ -45,17 +49,27 @@ namespace WebNovelPortalAPI.Controllers
return _scrapers.FirstOrDefault(i => i.MatchesUrl(novelUrl));
}
[HttpGet]
[Route("{guid:guid}")]
public async Task<Novel?> GetNovel(Guid guid)
private async Task<User> GetUser()
{
return await _novelRepository.GetNovel(guid);
return await _userRepository.GetIncluded(u => u.Id == UserId);
}
[HttpGet]
public async Task<List<Novel>> GetNovels()
[Route("{guid:guid}")]
public async Task<UserNovel?> GetNovel(Guid guid)
{
return (await _novelRepository.GetAllIncluded()).ToList();
var user = await GetUser();
var novel = await _novelRepository.GetNovel(guid);
return user.WatchedNovels.FirstOrDefault(un => un.NovelUrl == novel.Url);
}
[HttpGet]
public async Task<List<UserNovel>> GetNovels()
{
var user = await GetUser();
var novels = user.WatchedNovels.Select(i => i.Novel);
(await _novelRepository.GetWhereIncluded(novels)).ToList();
return user.WatchedNovels.ToList();
}
[HttpPost]
@@ -75,11 +89,12 @@ namespace WebNovelPortalAPI.Controllers
failures[novelUrl] = e;
}
}
IEnumerable<Novel> successfulUploads;
List<Novel> successfulUploads;
try
{
successfulUploads = await _novelRepository.UpsertMany(successfulScrapes);
successfulUploads = (await _novelRepository.UpsertMany(successfulScrapes, true)).ToList();
var user = await GetUser();
await _userRepository.AssignNovelsToUser(user, successfulUploads);
}
catch (Exception e)
{
@@ -99,7 +114,9 @@ namespace WebNovelPortalAPI.Controllers
try
{
var novel = await ScrapeNovel(request.NovelUrl);
var dbNovel = await _novelRepository.Upsert(novel);
var dbNovel = await _novelRepository.Upsert(novel, false);
var user = await GetUser();
await _userRepository.AssignNovelsToUser(user, new List<Novel> {novel});
return Ok(dbNovel);
}
catch (NoMatchingScraperException e)
@@ -111,5 +128,15 @@ namespace WebNovelPortalAPI.Controllers
return StatusCode(500, e);
}
}
[HttpPatch]
[Route("updateLastChapterRead")]
public async Task<IActionResult> UpdateLastChapterRead(Guid novelGuid, int chapter)
{
var user = await GetUser();
var novel = await _novelRepository.GetNovel(novelGuid);
await _userRepository.UpdateLastChapterRead(user, novel, chapter);
return Ok();
}
}
}

View File

@@ -0,0 +1,32 @@
using System.Security.Claims;
using DBConnection.Repositories.Interfaces;
using Microsoft.AspNetCore.Mvc.Filters;
using Treestar.Shared.Models.DBDomain;
namespace WebNovelPortalAPI.Middleware;
public class EnsureUserCreatedMiddleware : IMiddleware
{
private readonly IUserRepository _userRepository;
public const string UserIdItemName = "userId";
public EnsureUserCreatedMiddleware(IUserRepository userRepository)
{
_userRepository = userRepository;
}
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
if (!context.User.Identity.IsAuthenticated)
{
await next(context);
return;
}
var userEmail = context.User.Claims.FirstOrDefault(i => i.Type == ClaimTypes.Email)?.Value;
var dbUser = await _userRepository.GetIncluded(u => u.Email == userEmail) ?? await _userRepository.Upsert(new User
{
Email = userEmail
});
context.Items[UserIdItemName] = dbUser.Id;
await next(context);
}
}

View File

@@ -2,8 +2,11 @@ using DBConnection;
using DBConnection.Contexts;
using DBConnection.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json;
using Treestar.Shared.Authentication.JwtBearer;
using WebNovelPortalAPI.Extensions;
using WebNovelPortalAPI.Middleware;
using WebNovelPortalAPI.Scrapers;
var builder = WebApplication.CreateBuilder(args);
@@ -11,13 +14,40 @@ var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddDbServices(builder.Configuration);
builder.Services.AddScrapers();
builder.Services.AddJwtBearerAuth(builder.Configuration);
builder.Services.AddScoped<EnsureUserCreatedMiddleware>();
builder.Services.AddControllers().AddNewtonsoftJson(opt =>
{
opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSwaggerGen(opt =>
{
opt.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Description = "Bearer token",
Name = "Authorization",
Type = SecuritySchemeType.Http,
BearerFormat = "JWT",
Scheme = "bearer"
});
opt.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type=ReferenceType.SecurityScheme,
Id="Bearer"
}
},
new string[]{}
}
});
});
var app = builder.Build();
app.UpdateDatabase<AppDbContext>();
@@ -30,8 +60,9 @@ if (app.Environment.IsDevelopment())
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.UseMiddleware<EnsureUserCreatedMiddleware>();
app.MapControllers();
app.Run();

View File

@@ -5,10 +5,12 @@
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<UserSecretsId>dd5e7c53-e576-4442-ae30-c496ec2070a5</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="HtmlAgilityPack" Version="1.11.43" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.7" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="6.0.7" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0.7" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.7" />

View File

@@ -9,6 +9,10 @@
"Sqlite": "Data Source=test_db",
"PostgresSql": "placeholder"
},
"JwtBearerAuthOptions": {
"Authority": "placeholder",
"Audience": ""
},
"DatabaseProvider": "Sqlite",
"AllowedHosts": "*"
}