Finished adding user support and ability to update specific novels or set your last read chapter
This commit is contained in:
@@ -84,8 +84,18 @@ public abstract class BaseRepository<TEntityType> : IRepository<TEntityType> whe
|
|||||||
return GetAllIncludedQueryable().FirstOrDefault(predicate);
|
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)
|
public virtual async Task<IEnumerable<TEntityType>> GetWhereIncluded(Func<TEntityType, bool> predicate)
|
||||||
{
|
{
|
||||||
return GetAllIncludedQueryable().AsEnumerable().Where(predicate);
|
return GetAllIncludedQueryable().AsEnumerable().Where(predicate);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public virtual async Task PersistChanges()
|
||||||
|
{
|
||||||
|
await DbContext.SaveChangesAsync();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -16,4 +16,6 @@ public interface IRepository<TEntityType> : IRepository where TEntityType : Base
|
|||||||
Task<IEnumerable<TEntityType>> GetWhereIncluded(Func<TEntityType, bool> predicate);
|
Task<IEnumerable<TEntityType>> GetWhereIncluded(Func<TEntityType, bool> predicate);
|
||||||
Task<IEnumerable<TEntityType>> GetAllIncluded();
|
Task<IEnumerable<TEntityType>> GetAllIncluded();
|
||||||
Task<IEnumerable<TEntityType>> UpsertMany(IEnumerable<TEntityType> entities, bool saveAfter=true);
|
Task<IEnumerable<TEntityType>> UpsertMany(IEnumerable<TEntityType> entities, bool saveAfter=true);
|
||||||
|
Task PersistChanges();
|
||||||
|
Task<IEnumerable<TEntityType?>> GetWhereIncluded(IEnumerable<TEntityType> entities);
|
||||||
}
|
}
|
||||||
9
DBConnection/Repositories/Interfaces/IUserRepository.cs
Normal file
9
DBConnection/Repositories/Interfaces/IUserRepository.cs
Normal 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);
|
||||||
|
}
|
||||||
49
DBConnection/Repositories/UserRepository.cs
Normal file
49
DBConnection/Repositories/UserRepository.cs
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,9 +9,11 @@ namespace Treestar.Shared.AccessLayers;
|
|||||||
public abstract class ApiAccessLayer
|
public abstract class ApiAccessLayer
|
||||||
{
|
{
|
||||||
private readonly HttpClient _httpClient;
|
private readonly HttpClient _httpClient;
|
||||||
|
private readonly IAccessLayerAuthenticationProvider _authenticationProvider;
|
||||||
|
|
||||||
protected ApiAccessLayer(string apiBaseUrl)
|
protected ApiAccessLayer(string apiBaseUrl, IAccessLayerAuthenticationProvider authenticationProvider)
|
||||||
{
|
{
|
||||||
|
_authenticationProvider = authenticationProvider;
|
||||||
var handler = new HttpClientHandler()
|
var handler = new HttpClientHandler()
|
||||||
{
|
{
|
||||||
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
|
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
|
||||||
@@ -22,6 +24,7 @@ public abstract class ApiAccessLayer
|
|||||||
|
|
||||||
private async Task<HttpResponseWrapper> SendRequest(HttpRequestMessage message)
|
private async Task<HttpResponseWrapper> SendRequest(HttpRequestMessage message)
|
||||||
{
|
{
|
||||||
|
await _authenticationProvider.AddAuthentication(message);
|
||||||
var response = await _httpClient.SendAsync(message);
|
var response = await _httpClient.SendAsync(message);
|
||||||
return new HttpResponseWrapper()
|
return new HttpResponseWrapper()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
namespace Treestar.Shared.AccessLayers;
|
||||||
|
|
||||||
|
public interface IAccessLayerAuthenticationProvider
|
||||||
|
{
|
||||||
|
Task AddAuthentication(HttpRequestMessage request);
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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; }
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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; }
|
||||||
|
}
|
||||||
@@ -17,5 +17,23 @@ namespace Treestar.Shared.Models.DBDomain
|
|||||||
public NovelStatus Status { get; set; }
|
public NovelStatus Status { get; set; }
|
||||||
public DateTime LastUpdated { get; set; }
|
public DateTime LastUpdated { get; set; }
|
||||||
public DateTime DatePosted { 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();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -10,5 +10,23 @@ namespace Treestar.Shared.Models.DBDomain
|
|||||||
public int Id { get; set; }
|
public int Id { get; set; }
|
||||||
public string Email { get; set; }
|
public string Email { get; set; }
|
||||||
public List<UserNovel> WatchedNovels { 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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -10,5 +10,23 @@ namespace Treestar.Shared.Models.DBDomain
|
|||||||
[JsonIgnore]
|
[JsonIgnore]
|
||||||
public User User { get; set; }
|
public User User { get; set; }
|
||||||
public int LastChapterRead { 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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -7,14 +7,26 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
<Folder Include="BlazorComponents" />
|
||||||
<Folder Include="Interfaces" />
|
<Folder Include="Interfaces" />
|
||||||
<Folder Include="Utility" />
|
<Folder Include="Utility" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<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.AspNetCore.WebUtilities" Version="2.2.0" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Abstractions" Version="6.0.7" />
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Abstractions" Version="6.0.7" />
|
||||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
|
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
|
||||||
</ItemGroup>
|
</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>
|
</Project>
|
||||||
|
|||||||
@@ -8,13 +8,13 @@ namespace WebNovelPortal.AccessLayers;
|
|||||||
|
|
||||||
public class WebApiAccessLayer : ApiAccessLayer
|
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)
|
public async Task<Novel?> RequestNovelScrape(string url)
|
||||||
@@ -23,9 +23,9 @@ public class WebApiAccessLayer : ApiAccessLayer
|
|||||||
new ScrapeNovelRequest {NovelUrl = url})).ResponseObject;
|
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)
|
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,
|
return (await SendRequest<ScrapeNovelsResponse>("novel/scrapeNovels", HttpMethod.Post, null,
|
||||||
new ScrapeNovelsRequest {NovelUrls = novelUrls})).ResponseObject;
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,12 +1,14 @@
|
|||||||
<Router AppAssembly="@typeof(App).Assembly">
|
<CascadingAuthenticationState>
|
||||||
<Found Context="routeData">
|
<Router AppAssembly="@typeof(App).Assembly">
|
||||||
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)"/>
|
<Found Context="routeData">
|
||||||
<FocusOnNavigate RouteData="@routeData" Selector="h1"/>
|
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)"/>
|
||||||
</Found>
|
<FocusOnNavigate RouteData="@routeData" Selector="h1"/>
|
||||||
<NotFound>
|
</Found>
|
||||||
<PageTitle>Not found</PageTitle>
|
<NotFound>
|
||||||
<LayoutView Layout="@typeof(MainLayout)">
|
<PageTitle>Not found</PageTitle>
|
||||||
<p role="alert">Sorry, there's nothing at this address.</p>
|
<LayoutView Layout="@typeof(MainLayout)">
|
||||||
</LayoutView>
|
<p role="alert">Sorry, there's nothing at this address.</p>
|
||||||
</NotFound>
|
</LayoutView>
|
||||||
</Router>
|
</NotFound>
|
||||||
|
</Router>
|
||||||
|
</CascadingAuthenticationState>
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ using System.Collections.Generic;
|
|||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Microsoft.AspNetCore.Authentication;
|
using Microsoft.AspNetCore.Authentication;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
@@ -13,17 +14,21 @@ namespace WebNovelPortal.Controllers
|
|||||||
public class AccountController : ControllerBase
|
public class AccountController : ControllerBase
|
||||||
{
|
{
|
||||||
[HttpGet]
|
[HttpGet]
|
||||||
[Route("account/login")]
|
[Route("login")]
|
||||||
public async Task Login()
|
public async Task Login(string redirect="/")
|
||||||
{
|
{
|
||||||
await HttpContext.ChallengeAsync();
|
await HttpContext.ChallengeAsync(new AuthenticationProperties
|
||||||
|
{
|
||||||
|
RedirectUri = redirect
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpGet]
|
[HttpGet]
|
||||||
[Route("account/logout")]
|
[Route("logout")]
|
||||||
public async Task Logout()
|
public async Task Logout()
|
||||||
{
|
{
|
||||||
await HttpContext.SignOutAsync();
|
await HttpContext.SignOutAsync();
|
||||||
|
Response.Redirect("/");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
17
WebNovelPortal/Pages/Auth0InfoDump.razor
Normal file
17
WebNovelPortal/Pages/Auth0InfoDump.razor
Normal 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -7,20 +7,35 @@
|
|||||||
<LoadingDisplay/>
|
<LoadingDisplay/>
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
@if (!authenticated)
|
||||||
|
{
|
||||||
|
<div>you must login</div>
|
||||||
|
return;
|
||||||
|
}
|
||||||
<input @bind="NovelUrl" disabled="@awaitingRequest"/><button disabled="@IsDisabled()" onclick="@(() => RequestNovelScrape(NovelUrl))">Scrape</button><br/>
|
<input @bind="NovelUrl" disabled="@awaitingRequest"/><button disabled="@IsDisabled()" onclick="@(() => RequestNovelScrape(NovelUrl))">Scrape</button><br/>
|
||||||
<button onclick="@UpdateNovels" disabled="@IsDisabled()">Update Novels</button>
|
<button onclick="@UpdateNovels" disabled="@IsDisabled()">Update Novels</button>
|
||||||
<NovelList Novels="@novels"/>
|
<NovelList Novels="@novels" InputDisabled="awaitingRequest" HandleUpdateNovelRequest="UpdateNovel"/>
|
||||||
|
|
||||||
@code {
|
@code {
|
||||||
[Inject]
|
[Inject]
|
||||||
WebApiAccessLayer api { get; set; }
|
WebApiAccessLayer api { get; set; }
|
||||||
|
[CascadingParameter]
|
||||||
|
Task<AuthenticationState> AuthenticationStateTask { get; set; }
|
||||||
string NovelUrl { get; set; }
|
string NovelUrl { get; set; }
|
||||||
List<Novel> novels = new List<Novel>();
|
List<UserNovel> novels = new List<UserNovel>();
|
||||||
protected bool loading = true;
|
protected bool loading = true;
|
||||||
protected bool awaitingRequest = false;
|
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)
|
protected override async Task OnAfterRenderAsync(bool firstRender)
|
||||||
{
|
{
|
||||||
if (firstRender)
|
if (firstRender && authenticated)
|
||||||
{
|
{
|
||||||
await RefreshNovels();
|
await RefreshNovels();
|
||||||
}
|
}
|
||||||
@@ -45,9 +60,17 @@
|
|||||||
async Task UpdateNovels()
|
async Task UpdateNovels()
|
||||||
{
|
{
|
||||||
SetAwaitingRequest(true);
|
SetAwaitingRequest(true);
|
||||||
var res = await api.ScrapeNovels(novels.Select(i => i.Url).ToList());
|
var res = await api.ScrapeNovels(novels.Select(i => i.Novel.Url).ToList());
|
||||||
SetAwaitingRequest(false);
|
|
||||||
await RefreshNovels();
|
await RefreshNovels();
|
||||||
|
SetAwaitingRequest(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
async Task UpdateNovel(Novel novel)
|
||||||
|
{
|
||||||
|
SetAwaitingRequest(true);
|
||||||
|
var res = await api.RequestNovelScrape(novel.Url);
|
||||||
|
await RefreshNovels();
|
||||||
|
SetAwaitingRequest(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool IsDisabled()
|
bool IsDisabled()
|
||||||
|
|||||||
@@ -7,20 +7,24 @@
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
<h3><a href="@Novel.Url">@(Novel.Title)</a></h3>
|
<h3><a href="@Novel.Novel.Url">@(Novel.Novel.Title)</a></h3>
|
||||||
<h4>Author: <a href="@Novel.Author?.Url">@(Novel.Author?.Name ?? "Anonymous")</a></h4>
|
<h4>Author: <a href="@Novel.Novel.Author?.Url">@(Novel.Novel.Author?.Name ?? "Anonymous")</a></h4>
|
||||||
<h4>Date Posted: @Novel.DatePosted</h4>
|
<h4>Date Posted: @Novel.Novel.DatePosted</h4>
|
||||||
<h4>Date Updated: @Novel.LastUpdated</h4>
|
<h4>Date Updated: @Novel.Novel.LastUpdated</h4>
|
||||||
<h4>Tags</h4>
|
<h4>Tags</h4>
|
||||||
<ul>
|
<ul>
|
||||||
@foreach (var tag in Novel.Tags)
|
@foreach (var tag in Novel.Novel.Tags)
|
||||||
{
|
{
|
||||||
<li>@tag.TagValue</li>
|
<li>@tag.TagValue</li>
|
||||||
}
|
}
|
||||||
</ul>
|
</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>
|
<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>
|
<li><a href="@chapter.Url">@chapter.Name</a></li>
|
||||||
}
|
}
|
||||||
@@ -32,16 +36,40 @@ else
|
|||||||
public string? NovelId { get; set; }
|
public string? NovelId { get; set; }
|
||||||
[Inject]
|
[Inject]
|
||||||
public WebApiAccessLayer api { get; set; }
|
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)
|
protected override async Task OnAfterRenderAsync(bool firstRender)
|
||||||
{
|
{
|
||||||
if (firstRender)
|
if (firstRender)
|
||||||
{
|
{
|
||||||
Novel = await api.GetNovel(NovelId);
|
await UpdateNovelDetails();
|
||||||
StateHasChanged();
|
|
||||||
}
|
}
|
||||||
await base.OnAfterRenderAsync(firstRender);
|
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();
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -1,18 +1,24 @@
|
|||||||
using Microsoft.AspNetCore.Components;
|
using Microsoft.AspNetCore.Components;
|
||||||
using Microsoft.AspNetCore.Components.Web;
|
using Microsoft.AspNetCore.Components.Web;
|
||||||
using Newtonsoft.Json;
|
using Newtonsoft.Json;
|
||||||
|
using Treestar.Shared.AccessLayers;
|
||||||
|
using Treestar.Shared.Authentication.OIDC;
|
||||||
using WebNovelPortal.AccessLayers;
|
using WebNovelPortal.AccessLayers;
|
||||||
|
using WebNovelPortal.Authentication;
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
|
||||||
// Add services to the container.
|
// 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.AddRazorPages();
|
||||||
builder.Services.AddServerSideBlazor();
|
builder.Services.AddServerSideBlazor();
|
||||||
|
builder.Services.AddHttpContextAccessor();
|
||||||
builder.Services.AddControllers().AddNewtonsoftJson(opt =>
|
builder.Services.AddControllers().AddNewtonsoftJson(opt =>
|
||||||
{
|
{
|
||||||
opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
|
opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
|
||||||
});
|
});
|
||||||
|
builder.Services.AddOIDCAuth(builder.Configuration);
|
||||||
|
|
||||||
var app = builder.Build();
|
var app = builder.Build();
|
||||||
|
|
||||||
@@ -30,6 +36,9 @@ app.UseStaticFiles();
|
|||||||
|
|
||||||
app.UseRouting();
|
app.UseRouting();
|
||||||
|
|
||||||
|
app.UseAuthentication();
|
||||||
|
app.UseAuthorization();
|
||||||
|
|
||||||
app.MapBlazorHub();
|
app.MapBlazorHub();
|
||||||
app.MapFallbackToPage("/_Host");
|
app.MapFallbackToPage("/_Host");
|
||||||
app.MapControllers();
|
app.MapControllers();
|
||||||
|
|||||||
21
WebNovelPortal/Shared/Components/Display/LoginDisplay.razor
Normal file
21
WebNovelPortal/Shared/Components/Display/LoginDisplay.razor
Normal 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
@using Microsoft.AspNetCore.Components
|
@using Microsoft.AspNetCore.Components
|
||||||
|
@using WebNovelPortal.AccessLayers
|
||||||
|
|
||||||
<h1>Novels</h1>
|
<h1>Novels</h1>
|
||||||
<table>
|
<table>
|
||||||
@@ -12,16 +13,19 @@
|
|||||||
{
|
{
|
||||||
<tr>
|
<tr>
|
||||||
<td>
|
<td>
|
||||||
<a href="@($"/novel/{novel.Guid}")">@novel.Title</a>
|
<a href="@($"/novel/{novel.Novel.Guid}")">@novel.Novel.Title</a>
|
||||||
</td>
|
</td>
|
||||||
<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>
|
||||||
<td>
|
<td>
|
||||||
@novel.Chapters.Count
|
@novel.Novel.Chapters.Count
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
@novel.LastUpdated
|
@novel.Novel.LastUpdated
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<button disabled="@InputDisabled" @onclick="@(()=>HandleUpdateNovelRequest.InvokeAsync(novel.Novel))">Update</button>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
}
|
}
|
||||||
@@ -29,5 +33,13 @@
|
|||||||
|
|
||||||
@code {
|
@code {
|
||||||
[Parameter]
|
[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; }
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -9,7 +9,7 @@
|
|||||||
|
|
||||||
<main>
|
<main>
|
||||||
<div class="top-row px-4">
|
<div class="top-row px-4">
|
||||||
<a href="https://docs.microsoft.com/aspnet/" target="_blank">About</a>
|
<LoginDisplay/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<article class="content px-4">
|
<article class="content px-4">
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
|
|
||||||
article {
|
article {
|
||||||
flex: 1 1 auto;
|
flex: 1 1 auto;
|
||||||
|
width: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
main {
|
main {
|
||||||
|
|||||||
@@ -5,10 +5,10 @@
|
|||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
|
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
|
||||||
|
<UserSecretsId>32b7cf85-871e-439d-88a2-f8ff5186dafd</UserSecretsId>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Folder Include="Authentication" />
|
|
||||||
<Folder Include="Controllers" />
|
<Folder Include="Controllers" />
|
||||||
<Folder Include="Data" />
|
<Folder Include="Data" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
@@ -18,6 +18,7 @@
|
|||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<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.AspNetCore.Mvc.NewtonsoftJson" Version="6.0.7" />
|
||||||
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="6.0.7" />
|
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="6.0.7" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
@@ -5,6 +5,12 @@
|
|||||||
"Microsoft.AspNetCore": "Warning"
|
"Microsoft.AspNetCore": "Warning"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"OIDCAuthOptions": {
|
||||||
|
"Authority": "authority_here",
|
||||||
|
"ClientId": "clientid_here",
|
||||||
|
"ClientSecret": "clientsecret_here",
|
||||||
|
"Scopes": "openid profile email"
|
||||||
|
},
|
||||||
"AllowedHosts": "*",
|
"AllowedHosts": "*",
|
||||||
"WebAPIUrl": "https://localhost:7137/api/"
|
"WebAPIUrl": "https://localhost:7137/api/"
|
||||||
}
|
}
|
||||||
|
|||||||
31
WebNovelPortalAPI/Controllers/AuthorizedController.cs
Normal file
31
WebNovelPortalAPI/Controllers/AuthorizedController.cs
Normal 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()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ using System.Threading.Tasks;
|
|||||||
using DBConnection;
|
using DBConnection;
|
||||||
using DBConnection.Repositories;
|
using DBConnection.Repositories;
|
||||||
using DBConnection.Repositories.Interfaces;
|
using DBConnection.Repositories.Interfaces;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Treestar.Shared.Models.DBDomain;
|
using Treestar.Shared.Models.DBDomain;
|
||||||
@@ -18,15 +19,18 @@ namespace WebNovelPortalAPI.Controllers
|
|||||||
{
|
{
|
||||||
[Route("api/[controller]")]
|
[Route("api/[controller]")]
|
||||||
[ApiController]
|
[ApiController]
|
||||||
public class NovelController : ControllerBase
|
[Authorize]
|
||||||
|
public class NovelController : AuthorizedController
|
||||||
{
|
{
|
||||||
private readonly INovelRepository _novelRepository;
|
private readonly INovelRepository _novelRepository;
|
||||||
|
private readonly IUserRepository _userRepository;
|
||||||
private readonly IEnumerable<IScraper> _scrapers;
|
private readonly IEnumerable<IScraper> _scrapers;
|
||||||
|
|
||||||
public NovelController(IEnumerable<IScraper> scrapers, INovelRepository novelRepository)
|
public NovelController(IEnumerable<IScraper> scrapers, INovelRepository novelRepository, IUserRepository userRepository)
|
||||||
{
|
{
|
||||||
_scrapers = scrapers;
|
_scrapers = scrapers;
|
||||||
_novelRepository = novelRepository;
|
_novelRepository = novelRepository;
|
||||||
|
_userRepository = userRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<Novel?> ScrapeNovel(string url)
|
private async Task<Novel?> ScrapeNovel(string url)
|
||||||
@@ -45,17 +49,27 @@ namespace WebNovelPortalAPI.Controllers
|
|||||||
return _scrapers.FirstOrDefault(i => i.MatchesUrl(novelUrl));
|
return _scrapers.FirstOrDefault(i => i.MatchesUrl(novelUrl));
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpGet]
|
private async Task<User> GetUser()
|
||||||
[Route("{guid:guid}")]
|
|
||||||
public async Task<Novel?> GetNovel(Guid guid)
|
|
||||||
{
|
{
|
||||||
return await _novelRepository.GetNovel(guid);
|
return await _userRepository.GetIncluded(u => u.Id == UserId);
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpGet]
|
[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]
|
[HttpPost]
|
||||||
@@ -75,11 +89,12 @@ namespace WebNovelPortalAPI.Controllers
|
|||||||
failures[novelUrl] = e;
|
failures[novelUrl] = e;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
List<Novel> successfulUploads;
|
||||||
IEnumerable<Novel> successfulUploads;
|
|
||||||
try
|
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)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
@@ -99,7 +114,9 @@ namespace WebNovelPortalAPI.Controllers
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
var novel = await ScrapeNovel(request.NovelUrl);
|
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);
|
return Ok(dbNovel);
|
||||||
}
|
}
|
||||||
catch (NoMatchingScraperException e)
|
catch (NoMatchingScraperException e)
|
||||||
@@ -111,5 +128,15 @@ namespace WebNovelPortalAPI.Controllers
|
|||||||
return StatusCode(500, e);
|
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();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
32
WebNovelPortalAPI/Middleware/EnsureUserCreatedMiddleware.cs
Normal file
32
WebNovelPortalAPI/Middleware/EnsureUserCreatedMiddleware.cs
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,8 +2,11 @@ using DBConnection;
|
|||||||
using DBConnection.Contexts;
|
using DBConnection.Contexts;
|
||||||
using DBConnection.Extensions;
|
using DBConnection.Extensions;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.OpenApi.Models;
|
||||||
using Newtonsoft.Json;
|
using Newtonsoft.Json;
|
||||||
|
using Treestar.Shared.Authentication.JwtBearer;
|
||||||
using WebNovelPortalAPI.Extensions;
|
using WebNovelPortalAPI.Extensions;
|
||||||
|
using WebNovelPortalAPI.Middleware;
|
||||||
using WebNovelPortalAPI.Scrapers;
|
using WebNovelPortalAPI.Scrapers;
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
@@ -11,13 +14,40 @@ var builder = WebApplication.CreateBuilder(args);
|
|||||||
// Add services to the container.
|
// Add services to the container.
|
||||||
builder.Services.AddDbServices(builder.Configuration);
|
builder.Services.AddDbServices(builder.Configuration);
|
||||||
builder.Services.AddScrapers();
|
builder.Services.AddScrapers();
|
||||||
|
builder.Services.AddJwtBearerAuth(builder.Configuration);
|
||||||
|
builder.Services.AddScoped<EnsureUserCreatedMiddleware>();
|
||||||
builder.Services.AddControllers().AddNewtonsoftJson(opt =>
|
builder.Services.AddControllers().AddNewtonsoftJson(opt =>
|
||||||
{
|
{
|
||||||
opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
|
opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
|
||||||
});
|
});
|
||||||
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
||||||
builder.Services.AddEndpointsApiExplorer();
|
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();
|
var app = builder.Build();
|
||||||
app.UpdateDatabase<AppDbContext>();
|
app.UpdateDatabase<AppDbContext>();
|
||||||
@@ -30,8 +60,9 @@ if (app.Environment.IsDevelopment())
|
|||||||
|
|
||||||
app.UseHttpsRedirection();
|
app.UseHttpsRedirection();
|
||||||
|
|
||||||
|
app.UseAuthentication();
|
||||||
app.UseAuthorization();
|
app.UseAuthorization();
|
||||||
|
app.UseMiddleware<EnsureUserCreatedMiddleware>();
|
||||||
app.MapControllers();
|
app.MapControllers();
|
||||||
|
|
||||||
app.Run();
|
app.Run();
|
||||||
@@ -5,10 +5,12 @@
|
|||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
|
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
|
||||||
|
<UserSecretsId>dd5e7c53-e576-4442-ae30-c496ec2070a5</UserSecretsId>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="HtmlAgilityPack" Version="1.11.43" />
|
<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.AspNetCore.Mvc.NewtonsoftJson" Version="6.0.7" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0.7" />
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0.7" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.7" />
|
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.7" />
|
||||||
|
|||||||
@@ -9,6 +9,10 @@
|
|||||||
"Sqlite": "Data Source=test_db",
|
"Sqlite": "Data Source=test_db",
|
||||||
"PostgresSql": "placeholder"
|
"PostgresSql": "placeholder"
|
||||||
},
|
},
|
||||||
|
"JwtBearerAuthOptions": {
|
||||||
|
"Authority": "placeholder",
|
||||||
|
"Audience": ""
|
||||||
|
},
|
||||||
"DatabaseProvider": "Sqlite",
|
"DatabaseProvider": "Sqlite",
|
||||||
"AllowedHosts": "*"
|
"AllowedHosts": "*"
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user