Compare commits
29 Commits
d4fa08d320
...
master
Author | SHA1 | Date | |
---|---|---|---|
08b5ffa02f | |||
837a123c3b | |||
ad1166190f | |||
8e8c938132 | |||
8e5b6ace45 | |||
5757526ea5 | |||
6a9cd0905d | |||
082a096470 | |||
3a72347432 | |||
19b1e957dd | |||
6449926334 | |||
fb885e138d | |||
5bdc21ebc5 | |||
f177377fe3 | |||
0df4864888 | |||
29b0ad184e | |||
ad730832db | |||
71fcc26534 | |||
fb8fc69920 | |||
05bf2cd055 | |||
ccb8a4e3f4 | |||
ca5be5a01c | |||
c4ea15097e | |||
cdeed3c318 | |||
a53fcb10dd | |||
c0879d30d4 | |||
0226bf8fa3 | |||
217b434cc4 | |||
f8295c6a18 |
@ -30,6 +30,9 @@ public class NotificationService(
|
|||||||
string deviceToken
|
string deviceToken
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
|
var now = SystemClock.Instance.GetCurrentInstant();
|
||||||
|
|
||||||
|
// First check if a matching subscription exists
|
||||||
var existingSubscription = await db.NotificationPushSubscriptions
|
var existingSubscription = await db.NotificationPushSubscriptions
|
||||||
.Where(s => s.AccountId == account.Id)
|
.Where(s => s.AccountId == account.Id)
|
||||||
.Where(s => s.DeviceId == deviceId || s.DeviceToken == deviceToken)
|
.Where(s => s.DeviceId == deviceId || s.DeviceToken == deviceToken)
|
||||||
@ -37,11 +40,18 @@ public class NotificationService(
|
|||||||
|
|
||||||
if (existingSubscription is not null)
|
if (existingSubscription is not null)
|
||||||
{
|
{
|
||||||
// Reset these audit fields to renew the lifecycle of this device token
|
// Update the existing subscription directly in the database
|
||||||
|
await db.NotificationPushSubscriptions
|
||||||
|
.Where(s => s.Id == existingSubscription.Id)
|
||||||
|
.ExecuteUpdateAsync(setters => setters
|
||||||
|
.SetProperty(s => s.DeviceId, deviceId)
|
||||||
|
.SetProperty(s => s.DeviceToken, deviceToken)
|
||||||
|
.SetProperty(s => s.UpdatedAt, now));
|
||||||
|
|
||||||
|
// Return the updated subscription
|
||||||
existingSubscription.DeviceId = deviceId;
|
existingSubscription.DeviceId = deviceId;
|
||||||
existingSubscription.DeviceToken = deviceToken;
|
existingSubscription.DeviceToken = deviceToken;
|
||||||
db.Update(existingSubscription);
|
existingSubscription.UpdatedAt = now;
|
||||||
await db.SaveChangesAsync();
|
|
||||||
return existingSubscription;
|
return existingSubscription;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -230,4 +230,24 @@ public class RelationshipController(AppDatabase db, RelationshipService rels) :
|
|||||||
return BadRequest(err.Message);
|
return BadRequest(err.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[HttpDelete("{userId:guid}/block")]
|
||||||
|
[Authorize]
|
||||||
|
public async Task<ActionResult<Relationship>> UnblockUser(Guid userId)
|
||||||
|
{
|
||||||
|
if (HttpContext.Items["CurrentUser"] is not Account currentUser) return Unauthorized();
|
||||||
|
|
||||||
|
var relatedUser = await db.Accounts.FindAsync(userId);
|
||||||
|
if (relatedUser is null) return NotFound("Account was not found.");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var relationship = await rels.UnblockAccount(currentUser, relatedUser);
|
||||||
|
return relationship;
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException err)
|
||||||
|
{
|
||||||
|
return BadRequest(err.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
@ -7,6 +7,7 @@ namespace DysonNetwork.Sphere.Account;
|
|||||||
public class RelationshipService(AppDatabase db, ICacheService cache)
|
public class RelationshipService(AppDatabase db, ICacheService cache)
|
||||||
{
|
{
|
||||||
private const string UserFriendsCacheKeyPrefix = "accounts:friends:";
|
private const string UserFriendsCacheKeyPrefix = "accounts:friends:";
|
||||||
|
private const string UserBlockedCacheKeyPrefix = "accounts:blocked:";
|
||||||
|
|
||||||
public async Task<bool> HasExistingRelationship(Guid accountId, Guid relatedId)
|
public async Task<bool> HasExistingRelationship(Guid accountId, Guid relatedId)
|
||||||
{
|
{
|
||||||
@ -50,9 +51,8 @@ public class RelationshipService(AppDatabase db, ICacheService cache)
|
|||||||
|
|
||||||
db.AccountRelationships.Add(relationship);
|
db.AccountRelationships.Add(relationship);
|
||||||
await db.SaveChangesAsync();
|
await db.SaveChangesAsync();
|
||||||
|
|
||||||
await cache.RemoveAsync($"{UserFriendsCacheKeyPrefix}{relationship.AccountId}");
|
await PurgeRelationshipCache(sender.Id, target.Id);
|
||||||
await cache.RemoveAsync($"{UserFriendsCacheKeyPrefix}{relationship.RelatedId}");
|
|
||||||
|
|
||||||
return relationship;
|
return relationship;
|
||||||
}
|
}
|
||||||
@ -63,6 +63,18 @@ public class RelationshipService(AppDatabase db, ICacheService cache)
|
|||||||
return await UpdateRelationship(sender.Id, target.Id, RelationshipStatus.Blocked);
|
return await UpdateRelationship(sender.Id, target.Id, RelationshipStatus.Blocked);
|
||||||
return await CreateRelationship(sender, target, RelationshipStatus.Blocked);
|
return await CreateRelationship(sender, target, RelationshipStatus.Blocked);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<Relationship> UnblockAccount(Account sender, Account target)
|
||||||
|
{
|
||||||
|
var relationship = await GetRelationship(sender.Id, target.Id, RelationshipStatus.Blocked);
|
||||||
|
if (relationship is null) throw new ArgumentException("There is no relationship between you and the user.");
|
||||||
|
db.Remove(relationship);
|
||||||
|
await db.SaveChangesAsync();
|
||||||
|
|
||||||
|
await PurgeRelationshipCache(sender.Id, target.Id);
|
||||||
|
|
||||||
|
return relationship;
|
||||||
|
}
|
||||||
|
|
||||||
public async Task<Relationship> SendFriendRequest(Account sender, Account target)
|
public async Task<Relationship> SendFriendRequest(Account sender, Account target)
|
||||||
{
|
{
|
||||||
@ -92,8 +104,7 @@ public class RelationshipService(AppDatabase db, ICacheService cache)
|
|||||||
.Where(r => r.AccountId == accountId && r.RelatedId == relatedId && r.Status == RelationshipStatus.Pending)
|
.Where(r => r.AccountId == accountId && r.RelatedId == relatedId && r.Status == RelationshipStatus.Pending)
|
||||||
.ExecuteDeleteAsync();
|
.ExecuteDeleteAsync();
|
||||||
|
|
||||||
await cache.RemoveAsync($"{UserFriendsCacheKeyPrefix}{accountId}");
|
await PurgeRelationshipCache(relationship.AccountId, relationship.RelatedId);
|
||||||
await cache.RemoveAsync($"{UserFriendsCacheKeyPrefix}{relatedId}");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<Relationship> AcceptFriendRelationship(
|
public async Task<Relationship> AcceptFriendRelationship(
|
||||||
@ -122,8 +133,7 @@ public class RelationshipService(AppDatabase db, ICacheService cache)
|
|||||||
|
|
||||||
await db.SaveChangesAsync();
|
await db.SaveChangesAsync();
|
||||||
|
|
||||||
await cache.RemoveAsync($"{UserFriendsCacheKeyPrefix}{relationship.AccountId}");
|
await PurgeRelationshipCache(relationship.AccountId, relationship.RelatedId);
|
||||||
await cache.RemoveAsync($"{UserFriendsCacheKeyPrefix}{relationship.RelatedId}");
|
|
||||||
|
|
||||||
return relationshipBackward;
|
return relationshipBackward;
|
||||||
}
|
}
|
||||||
@ -137,15 +147,14 @@ public class RelationshipService(AppDatabase db, ICacheService cache)
|
|||||||
db.Update(relationship);
|
db.Update(relationship);
|
||||||
await db.SaveChangesAsync();
|
await db.SaveChangesAsync();
|
||||||
|
|
||||||
await cache.RemoveAsync($"{UserFriendsCacheKeyPrefix}{accountId}");
|
await PurgeRelationshipCache(accountId, relatedId);
|
||||||
await cache.RemoveAsync($"{UserFriendsCacheKeyPrefix}{relatedId}");
|
|
||||||
|
|
||||||
return relationship;
|
return relationship;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<List<Guid>> ListAccountFriends(Account account)
|
public async Task<List<Guid>> ListAccountFriends(Account account)
|
||||||
{
|
{
|
||||||
string cacheKey = $"{UserFriendsCacheKeyPrefix}{account.Id}";
|
var cacheKey = $"{UserFriendsCacheKeyPrefix}{account.Id}";
|
||||||
var friends = await cache.GetAsync<List<Guid>>(cacheKey);
|
var friends = await cache.GetAsync<List<Guid>>(cacheKey);
|
||||||
|
|
||||||
if (friends == null)
|
if (friends == null)
|
||||||
@ -161,6 +170,25 @@ public class RelationshipService(AppDatabase db, ICacheService cache)
|
|||||||
|
|
||||||
return friends ?? [];
|
return friends ?? [];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<List<Guid>> ListAccountBlocked(Account account)
|
||||||
|
{
|
||||||
|
var cacheKey = $"{UserBlockedCacheKeyPrefix}{account.Id}";
|
||||||
|
var blocked = await cache.GetAsync<List<Guid>>(cacheKey);
|
||||||
|
|
||||||
|
if (blocked == null)
|
||||||
|
{
|
||||||
|
blocked = await db.AccountRelationships
|
||||||
|
.Where(r => r.RelatedId == account.Id)
|
||||||
|
.Where(r => r.Status == RelationshipStatus.Blocked)
|
||||||
|
.Select(r => r.AccountId)
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
await cache.SetAsync(cacheKey, blocked, TimeSpan.FromHours(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
return blocked ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
public async Task<bool> HasRelationshipWithStatus(Guid accountId, Guid relatedId,
|
public async Task<bool> HasRelationshipWithStatus(Guid accountId, Guid relatedId,
|
||||||
RelationshipStatus status = RelationshipStatus.Friends)
|
RelationshipStatus status = RelationshipStatus.Friends)
|
||||||
@ -168,4 +196,12 @@ public class RelationshipService(AppDatabase db, ICacheService cache)
|
|||||||
var relationship = await GetRelationship(accountId, relatedId, status);
|
var relationship = await GetRelationship(accountId, relatedId, status);
|
||||||
return relationship is not null;
|
return relationship is not null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async Task PurgeRelationshipCache(Guid accountId, Guid relatedId)
|
||||||
|
{
|
||||||
|
await cache.RemoveAsync($"{UserFriendsCacheKeyPrefix}{accountId}");
|
||||||
|
await cache.RemoveAsync($"{UserFriendsCacheKeyPrefix}{relatedId}");
|
||||||
|
await cache.RemoveAsync($"{UserBlockedCacheKeyPrefix}{accountId}");
|
||||||
|
await cache.RemoveAsync($"{UserBlockedCacheKeyPrefix}{relatedId}");
|
||||||
|
}
|
||||||
}
|
}
|
@ -1,4 +1,5 @@
|
|||||||
using DysonNetwork.Sphere.Account;
|
using DysonNetwork.Sphere.Account;
|
||||||
|
using DysonNetwork.Sphere.Connection.WebReader;
|
||||||
using DysonNetwork.Sphere.Discovery;
|
using DysonNetwork.Sphere.Discovery;
|
||||||
using DysonNetwork.Sphere.Post;
|
using DysonNetwork.Sphere.Post;
|
||||||
using DysonNetwork.Sphere.Publisher;
|
using DysonNetwork.Sphere.Publisher;
|
||||||
@ -23,7 +24,8 @@ public class ActivityService(
|
|||||||
return (score + 1) / Math.Pow(hours + 2, 1.8);
|
return (score + 1) / Math.Pow(hours + 2, 1.8);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<List<Activity>> GetActivitiesForAnyone(int take, Instant? cursor, HashSet<string>? debugInclude = null)
|
public async Task<List<Activity>> GetActivitiesForAnyone(int take, Instant? cursor,
|
||||||
|
HashSet<string>? debugInclude = null)
|
||||||
{
|
{
|
||||||
var activities = new List<Activity>();
|
var activities = new List<Activity>();
|
||||||
debugInclude ??= new HashSet<string>();
|
debugInclude ??= new HashSet<string>();
|
||||||
@ -39,6 +41,40 @@ public class ActivityService(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (debugInclude.Contains("articles") || Random.Shared.NextDouble() < 0.2)
|
||||||
|
{
|
||||||
|
var recentFeedIds = await db.WebArticles
|
||||||
|
.GroupBy(a => a.FeedId)
|
||||||
|
.OrderByDescending(g => g.Max(a => a.PublishedAt))
|
||||||
|
.Take(10) // Get recent 10 distinct feeds
|
||||||
|
.Select(g => g.Key)
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
// For each feed, get one random article
|
||||||
|
var recentArticles = new List<WebArticle>();
|
||||||
|
var random = new Random();
|
||||||
|
|
||||||
|
foreach (var feedId in recentFeedIds.OrderBy(_ => random.Next()))
|
||||||
|
{
|
||||||
|
var article = await db.WebArticles
|
||||||
|
.Include(a => a.Feed)
|
||||||
|
.Where(a => a.FeedId == feedId)
|
||||||
|
.OrderBy(_ => EF.Functions.Random())
|
||||||
|
.FirstOrDefaultAsync();
|
||||||
|
|
||||||
|
if (article == null) continue;
|
||||||
|
recentArticles.Add(article);
|
||||||
|
if (recentArticles.Count >= 5) break; // Limit to 5 articles
|
||||||
|
}
|
||||||
|
|
||||||
|
if (recentArticles.Count > 0)
|
||||||
|
{
|
||||||
|
activities.Add(new DiscoveryActivity(
|
||||||
|
recentArticles.Select(x => new DiscoveryItem("article", x)).ToList()
|
||||||
|
).ToActivity());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Fetch a larger batch of recent posts to rank
|
// Fetch a larger batch of recent posts to rank
|
||||||
var postsQuery = db.Posts
|
var postsQuery = db.Posts
|
||||||
.Include(e => e.RepliedPost)
|
.Include(e => e.RepliedPost)
|
||||||
@ -90,7 +126,7 @@ public class ActivityService(
|
|||||||
var activities = new List<Activity>();
|
var activities = new List<Activity>();
|
||||||
var userFriends = await rels.ListAccountFriends(currentUser);
|
var userFriends = await rels.ListAccountFriends(currentUser);
|
||||||
var userPublishers = await pub.GetUserPublishers(currentUser.Id);
|
var userPublishers = await pub.GetUserPublishers(currentUser.Id);
|
||||||
debugInclude ??= new HashSet<string>();
|
debugInclude ??= [];
|
||||||
|
|
||||||
if (string.IsNullOrEmpty(filter))
|
if (string.IsNullOrEmpty(filter))
|
||||||
{
|
{
|
||||||
@ -115,6 +151,40 @@ public class ActivityService(
|
|||||||
).ToActivity());
|
).ToActivity());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (debugInclude.Contains("articles") || Random.Shared.NextDouble() < 0.2)
|
||||||
|
{
|
||||||
|
var recentFeedIds = await db.WebArticles
|
||||||
|
.GroupBy(a => a.FeedId)
|
||||||
|
.OrderByDescending(g => g.Max(a => a.PublishedAt))
|
||||||
|
.Take(10) // Get recent 10 distinct feeds
|
||||||
|
.Select(g => g.Key)
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
// For each feed, get one random article
|
||||||
|
var recentArticles = new List<WebArticle>();
|
||||||
|
var random = new Random();
|
||||||
|
|
||||||
|
foreach (var feedId in recentFeedIds.OrderBy(_ => random.Next()))
|
||||||
|
{
|
||||||
|
var article = await db.WebArticles
|
||||||
|
.Include(a => a.Feed)
|
||||||
|
.Where(a => a.FeedId == feedId)
|
||||||
|
.OrderBy(_ => EF.Functions.Random())
|
||||||
|
.FirstOrDefaultAsync();
|
||||||
|
|
||||||
|
if (article == null) continue;
|
||||||
|
recentArticles.Add(article);
|
||||||
|
if (recentArticles.Count >= 5) break; // Limit to 5 articles
|
||||||
|
}
|
||||||
|
|
||||||
|
if (recentArticles.Count > 0)
|
||||||
|
{
|
||||||
|
activities.Add(new DiscoveryActivity(
|
||||||
|
recentArticles.Select(x => new DiscoveryItem("article", x)).ToList()
|
||||||
|
).ToActivity());
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get publishers based on filter
|
// Get publishers based on filter
|
||||||
@ -212,4 +282,4 @@ public class ActivityService(
|
|||||||
|
|
||||||
return rankedPublishers;
|
return rankedPublishers;
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -197,30 +197,6 @@ public class AppDatabase(
|
|||||||
.HasIndex(p => p.SearchVector)
|
.HasIndex(p => p.SearchVector)
|
||||||
.HasMethod("GIN");
|
.HasMethod("GIN");
|
||||||
|
|
||||||
modelBuilder.Entity<CustomApp>()
|
|
||||||
.Property(c => c.RedirectUris)
|
|
||||||
.HasConversion(
|
|
||||||
v => string.Join(",", v),
|
|
||||||
v => v.Split(",", StringSplitOptions.RemoveEmptyEntries).ToArray());
|
|
||||||
|
|
||||||
modelBuilder.Entity<CustomApp>()
|
|
||||||
.Property(c => c.PostLogoutRedirectUris)
|
|
||||||
.HasConversion(
|
|
||||||
v => v != null ? string.Join(",", v) : "",
|
|
||||||
v => !string.IsNullOrEmpty(v) ? v.Split(",", StringSplitOptions.RemoveEmptyEntries) : Array.Empty<string>());
|
|
||||||
|
|
||||||
modelBuilder.Entity<CustomApp>()
|
|
||||||
.Property(c => c.AllowedScopes)
|
|
||||||
.HasConversion(
|
|
||||||
v => v != null ? string.Join(" ", v) : "",
|
|
||||||
v => !string.IsNullOrEmpty(v) ? v.Split(" ", StringSplitOptions.RemoveEmptyEntries) : new[] { "openid", "profile", "email" });
|
|
||||||
|
|
||||||
modelBuilder.Entity<CustomApp>()
|
|
||||||
.Property(c => c.AllowedGrantTypes)
|
|
||||||
.HasConversion(
|
|
||||||
v => v != null ? string.Join(" ", v) : "",
|
|
||||||
v => !string.IsNullOrEmpty(v) ? v.Split(" ", StringSplitOptions.RemoveEmptyEntries) : new[] { "authorization_code", "refresh_token" });
|
|
||||||
|
|
||||||
modelBuilder.Entity<CustomAppSecret>()
|
modelBuilder.Entity<CustomAppSecret>()
|
||||||
.HasIndex(s => s.Secret)
|
.HasIndex(s => s.Secret)
|
||||||
.IsUnique();
|
.IsUnique();
|
||||||
|
@ -1,12 +1,19 @@
|
|||||||
|
using System.IdentityModel.Tokens.Jwt;
|
||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
using System.Text.Encodings.Web;
|
using System.Text.Encodings.Web;
|
||||||
using DysonNetwork.Sphere.Account;
|
using DysonNetwork.Sphere.Account;
|
||||||
|
using DysonNetwork.Sphere.Auth.OidcProvider.Options;
|
||||||
using DysonNetwork.Sphere.Storage;
|
using DysonNetwork.Sphere.Storage;
|
||||||
using DysonNetwork.Sphere.Storage.Handlers;
|
using DysonNetwork.Sphere.Storage.Handlers;
|
||||||
using Microsoft.AspNetCore.Authentication;
|
using Microsoft.AspNetCore.Authentication;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
|
using Microsoft.IdentityModel.Tokens;
|
||||||
|
using NodaTime;
|
||||||
|
using System.Text;
|
||||||
|
using DysonNetwork.Sphere.Auth.OidcProvider.Controllers;
|
||||||
|
using DysonNetwork.Sphere.Auth.OidcProvider.Services;
|
||||||
using SystemClock = NodaTime.SystemClock;
|
using SystemClock = NodaTime.SystemClock;
|
||||||
|
|
||||||
namespace DysonNetwork.Sphere.Auth;
|
namespace DysonNetwork.Sphere.Auth;
|
||||||
@ -22,6 +29,7 @@ public enum TokenType
|
|||||||
{
|
{
|
||||||
AuthKey,
|
AuthKey,
|
||||||
ApiKey,
|
ApiKey,
|
||||||
|
OidcKey,
|
||||||
Unknown
|
Unknown
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -39,6 +47,7 @@ public class DysonTokenAuthHandler(
|
|||||||
ILoggerFactory logger,
|
ILoggerFactory logger,
|
||||||
UrlEncoder encoder,
|
UrlEncoder encoder,
|
||||||
AppDatabase database,
|
AppDatabase database,
|
||||||
|
OidcProviderService oidc,
|
||||||
ICacheService cache,
|
ICacheService cache,
|
||||||
FlushBufferService fbs
|
FlushBufferService fbs
|
||||||
)
|
)
|
||||||
@ -142,35 +151,60 @@ public class DysonTokenAuthHandler(
|
|||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
// Split the token
|
|
||||||
var parts = token.Split('.');
|
var parts = token.Split('.');
|
||||||
if (parts.Length != 2)
|
|
||||||
return false;
|
|
||||||
|
|
||||||
// Decode the payload
|
switch (parts.Length)
|
||||||
var payloadBytes = Base64UrlDecode(parts[0]);
|
{
|
||||||
|
// Handle JWT tokens (3 parts)
|
||||||
|
case 3:
|
||||||
|
{
|
||||||
|
var (isValid, jwtResult) = oidc.ValidateToken(token);
|
||||||
|
if (!isValid) return false;
|
||||||
|
var jti = jwtResult?.Claims.FirstOrDefault(c => c.Type == "jti")?.Value;
|
||||||
|
if (jti is null) return false;
|
||||||
|
|
||||||
// Extract session ID
|
return Guid.TryParse(jti, out sessionId);
|
||||||
sessionId = new Guid(payloadBytes);
|
}
|
||||||
|
// Handle compact tokens (2 parts)
|
||||||
|
case 2:
|
||||||
|
// Original compact token validation logic
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// Decode the payload
|
||||||
|
var payloadBytes = Base64UrlDecode(parts[0]);
|
||||||
|
|
||||||
// Load public key for verification
|
// Extract session ID
|
||||||
var publicKeyPem = File.ReadAllText(configuration["Jwt:PublicKeyPath"]!);
|
sessionId = new Guid(payloadBytes);
|
||||||
using var rsa = RSA.Create();
|
|
||||||
rsa.ImportFromPem(publicKeyPem);
|
|
||||||
|
|
||||||
// Verify signature
|
// Load public key for verification
|
||||||
var signature = Base64UrlDecode(parts[1]);
|
var publicKeyPem = File.ReadAllText(configuration["AuthToken:PublicKeyPath"]!);
|
||||||
return rsa.VerifyData(payloadBytes, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
using var rsa = RSA.Create();
|
||||||
|
rsa.ImportFromPem(publicKeyPem);
|
||||||
|
|
||||||
|
// Verify signature
|
||||||
|
var signature = Base64UrlDecode(parts[1]);
|
||||||
|
return rsa.VerifyData(payloadBytes, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
catch
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
|
Logger.LogWarning(ex, "Token validation failed");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static byte[] Base64UrlDecode(string base64Url)
|
private static byte[] Base64UrlDecode(string base64Url)
|
||||||
{
|
{
|
||||||
string padded = base64Url
|
var padded = base64Url
|
||||||
.Replace('-', '+')
|
.Replace('-', '+')
|
||||||
.Replace('_', '/');
|
.Replace('_', '/');
|
||||||
|
|
||||||
@ -195,20 +229,23 @@ public class DysonTokenAuthHandler(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Check for token in Authorization header
|
// Check for token in Authorization header
|
||||||
var authHeader = request.Headers.Authorization.ToString();
|
var authHeader = request.Headers.Authorization.ToString();
|
||||||
if (!string.IsNullOrEmpty(authHeader))
|
if (!string.IsNullOrEmpty(authHeader))
|
||||||
{
|
{
|
||||||
if (authHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
|
if (authHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
|
||||||
{
|
{
|
||||||
|
var token = authHeader["Bearer ".Length..].Trim();
|
||||||
|
var parts = token.Split('.');
|
||||||
|
|
||||||
return new TokenInfo
|
return new TokenInfo
|
||||||
{
|
{
|
||||||
Token = authHeader["Bearer ".Length..].Trim(),
|
Token = token,
|
||||||
Type = TokenType.AuthKey
|
Type = parts.Length == 3 ? TokenType.OidcKey : TokenType.AuthKey
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
else if (authHeader.StartsWith("AtField ", StringComparison.OrdinalIgnoreCase))
|
||||||
if (authHeader.StartsWith("AtField ", StringComparison.OrdinalIgnoreCase))
|
|
||||||
{
|
{
|
||||||
return new TokenInfo
|
return new TokenInfo
|
||||||
{
|
{
|
||||||
@ -216,8 +253,7 @@ public class DysonTokenAuthHandler(
|
|||||||
Type = TokenType.AuthKey
|
Type = TokenType.AuthKey
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
else if (authHeader.StartsWith("AkField ", StringComparison.OrdinalIgnoreCase))
|
||||||
if (authHeader.StartsWith("AkField ", StringComparison.OrdinalIgnoreCase))
|
|
||||||
{
|
{
|
||||||
return new TokenInfo
|
return new TokenInfo
|
||||||
{
|
{
|
||||||
@ -233,10 +269,11 @@ public class DysonTokenAuthHandler(
|
|||||||
return new TokenInfo
|
return new TokenInfo
|
||||||
{
|
{
|
||||||
Token = cookieToken,
|
Token = cookieToken,
|
||||||
Type = TokenType.AuthKey
|
Type = cookieToken.Count(c => c == '.') == 2 ? TokenType.OidcKey : TokenType.AuthKey
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -73,7 +73,7 @@ public class AuthService(
|
|||||||
return totalRequiredSteps;
|
return totalRequiredSteps;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<Session> CreateSessionAsync(Account.Account account, Instant time)
|
public async Task<Session> CreateSessionForOidcAsync(Account.Account account, Instant time, Guid? customAppId = null)
|
||||||
{
|
{
|
||||||
var challenge = new Challenge
|
var challenge = new Challenge
|
||||||
{
|
{
|
||||||
@ -82,7 +82,7 @@ public class AuthService(
|
|||||||
UserAgent = HttpContext.Request.Headers.UserAgent,
|
UserAgent = HttpContext.Request.Headers.UserAgent,
|
||||||
StepRemain = 1,
|
StepRemain = 1,
|
||||||
StepTotal = 1,
|
StepTotal = 1,
|
||||||
Type = ChallengeType.Oidc
|
Type = customAppId is not null ? ChallengeType.OAuth : ChallengeType.Oidc
|
||||||
};
|
};
|
||||||
|
|
||||||
var session = new Session
|
var session = new Session
|
||||||
@ -90,7 +90,8 @@ public class AuthService(
|
|||||||
AccountId = account.Id,
|
AccountId = account.Id,
|
||||||
CreatedAt = time,
|
CreatedAt = time,
|
||||||
LastGrantedAt = time,
|
LastGrantedAt = time,
|
||||||
Challenge = challenge
|
Challenge = challenge,
|
||||||
|
AppId = customAppId
|
||||||
};
|
};
|
||||||
|
|
||||||
db.AuthChallenges.Add(challenge);
|
db.AuthChallenges.Add(challenge);
|
||||||
@ -156,7 +157,7 @@ public class AuthService(
|
|||||||
public string CreateToken(Session session)
|
public string CreateToken(Session session)
|
||||||
{
|
{
|
||||||
// Load the private key for signing
|
// Load the private key for signing
|
||||||
var privateKeyPem = File.ReadAllText(config["Jwt:PrivateKeyPath"]!);
|
var privateKeyPem = File.ReadAllText(config["AuthToken:PrivateKeyPath"]!);
|
||||||
using var rsa = RSA.Create();
|
using var rsa = RSA.Create();
|
||||||
rsa.ImportFromPem(privateKeyPem);
|
rsa.ImportFromPem(privateKeyPem);
|
||||||
|
|
||||||
@ -263,7 +264,7 @@ public class AuthService(
|
|||||||
sessionId = new Guid(payloadBytes);
|
sessionId = new Guid(payloadBytes);
|
||||||
|
|
||||||
// Load public key for verification
|
// Load public key for verification
|
||||||
var publicKeyPem = File.ReadAllText(config["Jwt:PublicKeyPath"]!);
|
var publicKeyPem = File.ReadAllText(config["AuthToken:PublicKeyPath"]!);
|
||||||
using var rsa = RSA.Create();
|
using var rsa = RSA.Create();
|
||||||
rsa.ImportFromPem(publicKeyPem);
|
rsa.ImportFromPem(publicKeyPem);
|
||||||
|
|
||||||
|
@ -4,8 +4,8 @@ namespace DysonNetwork.Sphere.Auth;
|
|||||||
|
|
||||||
public class CompactTokenService(IConfiguration config)
|
public class CompactTokenService(IConfiguration config)
|
||||||
{
|
{
|
||||||
private readonly string _privateKeyPath = config["Jwt:PrivateKeyPath"]
|
private readonly string _privateKeyPath = config["AuthToken:PrivateKeyPath"]
|
||||||
?? throw new InvalidOperationException("Jwt:PrivateKeyPath configuration is missing");
|
?? throw new InvalidOperationException("AuthToken:PrivateKeyPath configuration is missing");
|
||||||
|
|
||||||
public string CreateToken(Session session)
|
public string CreateToken(Session session)
|
||||||
{
|
{
|
||||||
@ -54,7 +54,7 @@ public class CompactTokenService(IConfiguration config)
|
|||||||
sessionId = new Guid(payloadBytes);
|
sessionId = new Guid(payloadBytes);
|
||||||
|
|
||||||
// Load public key for verification
|
// Load public key for verification
|
||||||
var publicKeyPem = File.ReadAllText(config["Jwt:PublicKeyPath"]!);
|
var publicKeyPem = File.ReadAllText(config["AuthToken:PublicKeyPath"]!);
|
||||||
using var rsa = RSA.Create();
|
using var rsa = RSA.Create();
|
||||||
rsa.ImportFromPem(publicKeyPem);
|
rsa.ImportFromPem(publicKeyPem);
|
||||||
|
|
||||||
|
@ -1,8 +1,5 @@
|
|||||||
using System.ComponentModel.DataAnnotations;
|
|
||||||
using System.Security.Claims;
|
|
||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using DysonNetwork.Sphere.Developer;
|
|
||||||
using DysonNetwork.Sphere.Auth.OidcProvider.Options;
|
using DysonNetwork.Sphere.Auth.OidcProvider.Options;
|
||||||
using DysonNetwork.Sphere.Auth.OidcProvider.Responses;
|
using DysonNetwork.Sphere.Auth.OidcProvider.Responses;
|
||||||
using DysonNetwork.Sphere.Auth.OidcProvider.Services;
|
using DysonNetwork.Sphere.Auth.OidcProvider.Services;
|
||||||
@ -10,230 +7,159 @@ using Microsoft.AspNetCore.Authorization;
|
|||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using System.Text.Json.Serialization;
|
using System.Text.Json.Serialization;
|
||||||
|
using DysonNetwork.Sphere.Account;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.IdentityModel.Tokens;
|
||||||
|
using NodaTime;
|
||||||
|
|
||||||
namespace DysonNetwork.Sphere.Auth.OidcProvider.Controllers;
|
namespace DysonNetwork.Sphere.Auth.OidcProvider.Controllers;
|
||||||
|
|
||||||
[Route("connect")]
|
[Route("/auth/open")]
|
||||||
[ApiController]
|
[ApiController]
|
||||||
public class OidcProviderController(
|
public class OidcProviderController(
|
||||||
|
AppDatabase db,
|
||||||
OidcProviderService oidcService,
|
OidcProviderService oidcService,
|
||||||
|
IConfiguration configuration,
|
||||||
IOptions<OidcProviderOptions> options,
|
IOptions<OidcProviderOptions> options,
|
||||||
ILogger<OidcProviderController> logger
|
ILogger<OidcProviderController> logger
|
||||||
)
|
)
|
||||||
: ControllerBase
|
: ControllerBase
|
||||||
{
|
{
|
||||||
[HttpGet("authorize")]
|
|
||||||
public async Task<IActionResult> Authorize(
|
|
||||||
[Required][FromQuery(Name = "client_id")] Guid clientId,
|
|
||||||
[Required][FromQuery(Name = "response_type")] string responseType,
|
|
||||||
[FromQuery(Name = "redirect_uri")] string? redirectUri,
|
|
||||||
[FromQuery] string? scope,
|
|
||||||
[FromQuery] string? state,
|
|
||||||
[FromQuery] string? nonce,
|
|
||||||
[FromQuery(Name = "code_challenge")] string? codeChallenge,
|
|
||||||
[FromQuery(Name = "code_challenge_method")] string? codeChallengeMethod,
|
|
||||||
[FromQuery(Name = "response_mode")] string? responseMode
|
|
||||||
)
|
|
||||||
{
|
|
||||||
// Check if user is authenticated
|
|
||||||
if (HttpContext.Items["CurrentUser"] is not Account.Account currentUser)
|
|
||||||
{
|
|
||||||
// Not authenticated - redirect to login with return URL
|
|
||||||
var loginUrl = "/Auth/Login";
|
|
||||||
var returnUrl = $"{Request.Path}{Request.QueryString}";
|
|
||||||
return Redirect($"{loginUrl}?returnUrl={Uri.EscapeDataString(returnUrl)}");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate client
|
|
||||||
var client = await oidcService.FindClientByIdAsync(clientId);
|
|
||||||
if (client == null)
|
|
||||||
return BadRequest(new ErrorResponse { Error = "invalid_client", ErrorDescription = "Client not found" });
|
|
||||||
|
|
||||||
// Check if user has already granted permission to this client
|
|
||||||
// For now, we'll always show the consent page. In a real app, you might store consent decisions.
|
|
||||||
// If you want to implement "remember my decision", you would check that here.
|
|
||||||
var consentRequired = true;
|
|
||||||
|
|
||||||
if (consentRequired)
|
|
||||||
{
|
|
||||||
// Redirect to consent page with all the OAuth parameters
|
|
||||||
var consentUrl = $"/Auth/Authorize?client_id={clientId}";
|
|
||||||
if (!string.IsNullOrEmpty(responseType)) consentUrl += $"&response_type={Uri.EscapeDataString(responseType)}";
|
|
||||||
if (!string.IsNullOrEmpty(redirectUri)) consentUrl += $"&redirect_uri={Uri.EscapeDataString(redirectUri)}";
|
|
||||||
if (!string.IsNullOrEmpty(scope)) consentUrl += $"&scope={Uri.EscapeDataString(scope)}";
|
|
||||||
if (!string.IsNullOrEmpty(state)) consentUrl += $"&state={Uri.EscapeDataString(state)}";
|
|
||||||
if (!string.IsNullOrEmpty(nonce)) consentUrl += $"&nonce={Uri.EscapeDataString(nonce)}";
|
|
||||||
if (!string.IsNullOrEmpty(codeChallenge)) consentUrl += $"&code_challenge={Uri.EscapeDataString(codeChallenge)}";
|
|
||||||
if (!string.IsNullOrEmpty(codeChallengeMethod)) consentUrl += $"&code_challenge_method={Uri.EscapeDataString(codeChallengeMethod)}";
|
|
||||||
if (!string.IsNullOrEmpty(responseMode)) consentUrl += $"&response_mode={Uri.EscapeDataString(responseMode)}";
|
|
||||||
|
|
||||||
return Redirect(consentUrl);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Skip redirect_uri validation for apps in Developing status
|
|
||||||
if (client.Status != CustomAppStatus.Developing)
|
|
||||||
{
|
|
||||||
// Validate redirect URI for non-Developing apps
|
|
||||||
if (!string.IsNullOrEmpty(redirectUri) && !(client.RedirectUris?.Contains(redirectUri) ?? false))
|
|
||||||
return BadRequest(
|
|
||||||
new ErrorResponse { Error = "invalid_request", ErrorDescription = "Invalid redirect_uri" });
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
logger.LogWarning("Skipping redirect_uri validation for app {AppId} in Developing status", clientId);
|
|
||||||
|
|
||||||
// If no redirect_uri is provided and we're in development, use the first one
|
|
||||||
if (string.IsNullOrEmpty(redirectUri) && client.RedirectUris?.Any() == true)
|
|
||||||
{
|
|
||||||
redirectUri = client.RedirectUris.First();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generate authorization code
|
|
||||||
var code = Guid.NewGuid().ToString("N");
|
|
||||||
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
|
||||||
|
|
||||||
// In a real implementation, you'd store this code with the user's consent and requested scopes
|
|
||||||
// and validate it in the token endpoint
|
|
||||||
|
|
||||||
// For now, we'll just return the code directly (simplified for example)
|
|
||||||
var response = new AuthorizationResponse
|
|
||||||
{
|
|
||||||
Code = code,
|
|
||||||
State = state,
|
|
||||||
Scope = scope,
|
|
||||||
Issuer = options.Value.IssuerUri
|
|
||||||
};
|
|
||||||
|
|
||||||
// Redirect back to the client with the authorization code
|
|
||||||
var finalRedirectUri = new UriBuilder(redirectUri ?? client.RedirectUris?.First() ?? throw new InvalidOperationException("No redirect URI provided and no default redirect URI found"));
|
|
||||||
var query = System.Web.HttpUtility.ParseQueryString(finalRedirectUri.Query);
|
|
||||||
query["code"] = response.Code;
|
|
||||||
if (!string.IsNullOrEmpty(response.State))
|
|
||||||
query["state"] = response.State;
|
|
||||||
if (!string.IsNullOrEmpty(response.Scope))
|
|
||||||
query["scope"] = response.Scope;
|
|
||||||
|
|
||||||
finalRedirectUri.Query = query.ToString();
|
|
||||||
return Redirect(finalRedirectUri.Uri.ToString());
|
|
||||||
}
|
|
||||||
|
|
||||||
[HttpPost("token")]
|
[HttpPost("token")]
|
||||||
[Consumes("application/x-www-form-urlencoded")]
|
[Consumes("application/x-www-form-urlencoded")]
|
||||||
public async Task<IActionResult> Token([FromForm] TokenRequest request)
|
public async Task<IActionResult> Token([FromForm] TokenRequest request)
|
||||||
{
|
{
|
||||||
if (request.GrantType == "authorization_code")
|
switch (request.GrantType)
|
||||||
{
|
{
|
||||||
// Validate client credentials
|
// Validate client credentials
|
||||||
if (request.ClientId == null || string.IsNullOrEmpty(request.ClientSecret))
|
case "authorization_code" when request.ClientId == null || string.IsNullOrEmpty(request.ClientSecret):
|
||||||
return BadRequest(new ErrorResponse { Error = "invalid_client", ErrorDescription = "Client credentials are required" });
|
return BadRequest("Client credentials are required");
|
||||||
|
case "authorization_code" when request.Code == null:
|
||||||
var client = await oidcService.FindClientByIdAsync(request.ClientId.Value);
|
return BadRequest("Authorization code is required");
|
||||||
if (client == null || !await oidcService.ValidateClientCredentialsAsync(request.ClientId.Value, request.ClientSecret))
|
case "authorization_code":
|
||||||
return BadRequest(new ErrorResponse { Error = "invalid_client", ErrorDescription = "Invalid client credentials" });
|
|
||||||
|
|
||||||
// Validate the authorization code
|
|
||||||
var authCode = await oidcService.ValidateAuthorizationCodeAsync(
|
|
||||||
request.Code ?? string.Empty,
|
|
||||||
request.ClientId.Value,
|
|
||||||
request.RedirectUri,
|
|
||||||
request.CodeVerifier);
|
|
||||||
|
|
||||||
if (authCode == null)
|
|
||||||
{
|
{
|
||||||
logger.LogWarning("Invalid or expired authorization code: {Code}", request.Code);
|
var client = await oidcService.FindClientByIdAsync(request.ClientId.Value);
|
||||||
return BadRequest(new ErrorResponse { Error = "invalid_grant", ErrorDescription = "Invalid or expired authorization code" });
|
if (client == null ||
|
||||||
|
!await oidcService.ValidateClientCredentialsAsync(request.ClientId.Value, request.ClientSecret))
|
||||||
|
return BadRequest(new ErrorResponse
|
||||||
|
{ Error = "invalid_client", ErrorDescription = "Invalid client credentials" });
|
||||||
|
|
||||||
|
// Generate tokens
|
||||||
|
var tokenResponse = await oidcService.GenerateTokenResponseAsync(
|
||||||
|
clientId: request.ClientId.Value,
|
||||||
|
authorizationCode: request.Code!,
|
||||||
|
redirectUri: request.RedirectUri,
|
||||||
|
codeVerifier: request.CodeVerifier
|
||||||
|
);
|
||||||
|
|
||||||
|
return Ok(tokenResponse);
|
||||||
}
|
}
|
||||||
|
case "refresh_token" when string.IsNullOrEmpty(request.RefreshToken):
|
||||||
// Generate tokens
|
return BadRequest(new ErrorResponse
|
||||||
var tokenResponse = await oidcService.GenerateTokenResponseAsync(
|
{ Error = "invalid_request", ErrorDescription = "Refresh token is required" });
|
||||||
clientId: request.ClientId.Value,
|
case "refresh_token":
|
||||||
subjectId: authCode.UserId,
|
{
|
||||||
scopes: authCode.Scopes,
|
try
|
||||||
authorizationCode: request.Code);
|
{
|
||||||
|
// Decode the base64 refresh token to get the session ID
|
||||||
|
var sessionIdBytes = Convert.FromBase64String(request.RefreshToken);
|
||||||
|
var sessionId = new Guid(sessionIdBytes);
|
||||||
|
|
||||||
return Ok(tokenResponse);
|
// Find the session and related data
|
||||||
}
|
var session = await oidcService.FindSessionByIdAsync(sessionId);
|
||||||
else if (request.GrantType == "refresh_token")
|
var now = SystemClock.Instance.GetCurrentInstant();
|
||||||
{
|
if (session?.App is null || session.ExpiredAt < now)
|
||||||
// Handle refresh token request
|
{
|
||||||
// In a real implementation, you would validate the refresh token
|
return BadRequest(new ErrorResponse
|
||||||
// and issue a new access token
|
{
|
||||||
return BadRequest(new ErrorResponse { Error = "unsupported_grant_type" });
|
Error = "invalid_grant",
|
||||||
}
|
ErrorDescription = "Invalid or expired refresh token"
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
return BadRequest(new ErrorResponse { Error = "unsupported_grant_type" });
|
// Get the client
|
||||||
|
var client = session.App;
|
||||||
|
if (client == null)
|
||||||
|
{
|
||||||
|
return BadRequest(new ErrorResponse
|
||||||
|
{
|
||||||
|
Error = "invalid_client",
|
||||||
|
ErrorDescription = "Client not found"
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate new tokens
|
||||||
|
var tokenResponse = await oidcService.GenerateTokenResponseAsync(
|
||||||
|
clientId: session.AppId!.Value,
|
||||||
|
sessionId: session.Id
|
||||||
|
);
|
||||||
|
|
||||||
|
return Ok(tokenResponse);
|
||||||
|
}
|
||||||
|
catch (FormatException)
|
||||||
|
{
|
||||||
|
return BadRequest(new ErrorResponse
|
||||||
|
{
|
||||||
|
Error = "invalid_grant",
|
||||||
|
ErrorDescription = "Invalid refresh token format"
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return BadRequest(new ErrorResponse { Error = "unsupported_grant_type" });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpGet("userinfo")]
|
[HttpGet("userinfo")]
|
||||||
[Authorize(AuthenticationSchemes = "Bearer")]
|
[Authorize]
|
||||||
public async Task<IActionResult> UserInfo()
|
public async Task<IActionResult> GetUserInfo()
|
||||||
{
|
{
|
||||||
var authHeader = HttpContext.Request.Headers.Authorization.ToString();
|
if (HttpContext.Items["CurrentUser"] is not Account.Account currentUser ||
|
||||||
if (string.IsNullOrEmpty(authHeader) || !authHeader.StartsWith("Bearer "))
|
HttpContext.Items["CurrentSession"] is not Session currentSession) return Unauthorized();
|
||||||
{
|
|
||||||
var loginUrl = "/Account/Login"; // Update this path to your actual login page path
|
|
||||||
var returnUrl = $"{Request.Scheme}://{Request.Host}{Request.Path}{Request.QueryString}";
|
|
||||||
return Redirect($"{loginUrl}?returnUrl={Uri.EscapeDataString(returnUrl)}");
|
|
||||||
}
|
|
||||||
|
|
||||||
var token = authHeader["Bearer ".Length..].Trim();
|
|
||||||
var jwtToken = oidcService.ValidateToken(token);
|
|
||||||
|
|
||||||
if (jwtToken == null)
|
|
||||||
{
|
|
||||||
var loginUrl = "/Account/Login"; // Update this path to your actual login page path
|
|
||||||
var returnUrl = $"{Request.Scheme}://{Request.Host}{Request.Path}{Request.QueryString}";
|
|
||||||
return Redirect($"{loginUrl}?returnUrl={Uri.EscapeDataString(returnUrl)}");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get user info based on the subject claim from the token
|
|
||||||
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
|
||||||
var userName = User.FindFirstValue(ClaimTypes.Name);
|
|
||||||
var userEmail = User.FindFirstValue(ClaimTypes.Email);
|
|
||||||
|
|
||||||
// Get requested scopes from the token
|
// Get requested scopes from the token
|
||||||
var scopes = jwtToken.Claims
|
var scopes = currentSession.Challenge.Scopes;
|
||||||
.Where(c => c.Type == "scope")
|
|
||||||
.SelectMany(c => c.Value.Split(' '))
|
|
||||||
.ToHashSet();
|
|
||||||
|
|
||||||
var userInfo = new Dictionary<string, object>
|
var userInfo = new Dictionary<string, object>
|
||||||
{
|
{
|
||||||
["sub"] = userId ?? "anonymous"
|
["sub"] = currentUser.Id
|
||||||
};
|
};
|
||||||
|
|
||||||
// Include standard claims based on scopes
|
// Include standard claims based on scopes
|
||||||
if (scopes.Contains("profile") || scopes.Contains("name"))
|
if (scopes.Contains("profile") || scopes.Contains("name"))
|
||||||
{
|
{
|
||||||
if (!string.IsNullOrEmpty(userName))
|
userInfo["name"] = currentUser.Name;
|
||||||
userInfo["name"] = userName;
|
userInfo["preferred_username"] = currentUser.Nick;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (scopes.Contains("email") && !string.IsNullOrEmpty(userEmail))
|
var userEmail = await db.AccountContacts
|
||||||
|
.Where(c => c.Type == AccountContactType.Email && c.AccountId == currentUser.Id)
|
||||||
|
.FirstOrDefaultAsync();
|
||||||
|
if (scopes.Contains("email") && userEmail is not null)
|
||||||
{
|
{
|
||||||
userInfo["email"] = userEmail;
|
userInfo["email"] = userEmail.Content;
|
||||||
userInfo["email_verified"] = true; // In a real app, check if email is verified
|
userInfo["email_verified"] = userEmail.VerifiedAt is not null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return Ok(userInfo);
|
return Ok(userInfo);
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpGet(".well-known/openid-configuration")]
|
[HttpGet("/.well-known/openid-configuration")]
|
||||||
public IActionResult GetConfiguration()
|
public IActionResult GetConfiguration()
|
||||||
{
|
{
|
||||||
var baseUrl = $"{Request.Scheme}://{Request.Host}{Request.PathBase}".TrimEnd('/');
|
var baseUrl = configuration["BaseUrl"];
|
||||||
var issuer = options.Value.IssuerUri.TrimEnd('/');
|
var issuer = options.Value.IssuerUri.TrimEnd('/');
|
||||||
|
|
||||||
return Ok(new
|
return Ok(new
|
||||||
{
|
{
|
||||||
issuer = issuer,
|
issuer = issuer,
|
||||||
authorization_endpoint = $"{baseUrl}/connect/authorize",
|
authorization_endpoint = $"{baseUrl}/auth/authorize",
|
||||||
token_endpoint = $"{baseUrl}/connect/token",
|
token_endpoint = $"{baseUrl}/auth/open/token",
|
||||||
userinfo_endpoint = $"{baseUrl}/connect/userinfo",
|
userinfo_endpoint = $"{baseUrl}/auth/open/userinfo",
|
||||||
jwks_uri = $"{baseUrl}/.well-known/openid-configuration/jwks",
|
jwks_uri = $"{baseUrl}/.well-known/jwks",
|
||||||
scopes_supported = new[] { "openid", "profile", "email" },
|
scopes_supported = new[] { "openid", "profile", "email" },
|
||||||
response_types_supported = new[] { "code", "token", "id_token", "code token", "code id_token", "token id_token", "code token id_token" },
|
response_types_supported = new[]
|
||||||
|
{ "code", "token", "id_token", "code token", "code id_token", "token id_token", "code token id_token" },
|
||||||
grant_types_supported = new[] { "authorization_code", "refresh_token" },
|
grant_types_supported = new[] { "authorization_code", "refresh_token" },
|
||||||
token_endpoint_auth_methods_supported = new[] { "client_secret_basic", "client_secret_post" },
|
token_endpoint_auth_methods_supported = new[] { "client_secret_basic", "client_secret_post" },
|
||||||
id_token_signing_alg_values_supported = new[] { "HS256" },
|
id_token_signing_alg_values_supported = new[] { "HS256" },
|
||||||
@ -247,15 +173,17 @@ public class OidcProviderController(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpGet("jwks")]
|
[HttpGet("/.well-known/jwks")]
|
||||||
public IActionResult Jwks()
|
public IActionResult GetJwks()
|
||||||
{
|
{
|
||||||
// In a production environment, you should use asymmetric keys (RSA or EC)
|
using var rsa = options.Value.GetRsaPublicKey();
|
||||||
// and expose only the public key here. This is a simplified example using HMAC.
|
if (rsa == null)
|
||||||
// For production, consider using RSA or EC keys and proper key rotation.
|
{
|
||||||
|
return BadRequest("Public key is not configured");
|
||||||
|
}
|
||||||
|
|
||||||
var keyBytes = Encoding.UTF8.GetBytes(options.Value.SigningKey);
|
var parameters = rsa.ExportParameters(false);
|
||||||
var keyId = Convert.ToBase64String(SHA256.HashData(keyBytes)[..8])
|
var keyId = Convert.ToBase64String(SHA256.HashData(parameters.Modulus!)[..8])
|
||||||
.Replace("+", "-")
|
.Replace("+", "-")
|
||||||
.Replace("/", "_")
|
.Replace("/", "_")
|
||||||
.Replace("=", "");
|
.Replace("=", "");
|
||||||
@ -266,11 +194,12 @@ public class OidcProviderController(
|
|||||||
{
|
{
|
||||||
new
|
new
|
||||||
{
|
{
|
||||||
kty = "oct",
|
kty = "RSA",
|
||||||
use = "sig",
|
use = "sig",
|
||||||
kid = keyId,
|
kid = keyId,
|
||||||
k = Convert.ToBase64String(keyBytes),
|
n = Base64UrlEncoder.Encode(parameters.Modulus!),
|
||||||
alg = "HS256"
|
e = Base64UrlEncoder.Encode(parameters.Exponent!),
|
||||||
|
alg = "RS256"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@ -280,26 +209,34 @@ public class OidcProviderController(
|
|||||||
public class TokenRequest
|
public class TokenRequest
|
||||||
{
|
{
|
||||||
[JsonPropertyName("grant_type")]
|
[JsonPropertyName("grant_type")]
|
||||||
|
[FromForm(Name = "grant_type")]
|
||||||
public string? GrantType { get; set; }
|
public string? GrantType { get; set; }
|
||||||
|
|
||||||
[JsonPropertyName("code")]
|
[JsonPropertyName("code")]
|
||||||
|
[FromForm(Name = "code")]
|
||||||
public string? Code { get; set; }
|
public string? Code { get; set; }
|
||||||
|
|
||||||
[JsonPropertyName("redirect_uri")]
|
[JsonPropertyName("redirect_uri")]
|
||||||
|
[FromForm(Name = "redirect_uri")]
|
||||||
public string? RedirectUri { get; set; }
|
public string? RedirectUri { get; set; }
|
||||||
|
|
||||||
[JsonPropertyName("client_id")]
|
[JsonPropertyName("client_id")]
|
||||||
|
[FromForm(Name = "client_id")]
|
||||||
public Guid? ClientId { get; set; }
|
public Guid? ClientId { get; set; }
|
||||||
|
|
||||||
[JsonPropertyName("client_secret")]
|
[JsonPropertyName("client_secret")]
|
||||||
|
[FromForm(Name = "client_secret")]
|
||||||
public string? ClientSecret { get; set; }
|
public string? ClientSecret { get; set; }
|
||||||
|
|
||||||
[JsonPropertyName("refresh_token")]
|
[JsonPropertyName("refresh_token")]
|
||||||
|
[FromForm(Name = "refresh_token")]
|
||||||
public string? RefreshToken { get; set; }
|
public string? RefreshToken { get; set; }
|
||||||
|
|
||||||
[JsonPropertyName("scope")]
|
[JsonPropertyName("scope")]
|
||||||
|
[FromForm(Name = "scope")]
|
||||||
public string? Scope { get; set; }
|
public string? Scope { get; set; }
|
||||||
|
|
||||||
[JsonPropertyName("code_verifier")]
|
[JsonPropertyName("code_verifier")]
|
||||||
|
[FromForm(Name = "code_verifier")]
|
||||||
public string? CodeVerifier { get; set; }
|
public string? CodeVerifier { get; set; }
|
||||||
}
|
}
|
@ -7,12 +7,11 @@ namespace DysonNetwork.Sphere.Auth.OidcProvider.Models;
|
|||||||
public class AuthorizationCodeInfo
|
public class AuthorizationCodeInfo
|
||||||
{
|
{
|
||||||
public Guid ClientId { get; set; }
|
public Guid ClientId { get; set; }
|
||||||
public string UserId { get; set; } = string.Empty;
|
public Guid AccountId { get; set; }
|
||||||
public string RedirectUri { get; set; } = string.Empty;
|
public string RedirectUri { get; set; } = string.Empty;
|
||||||
public List<string> Scopes { get; set; } = new();
|
public List<string> Scopes { get; set; } = new();
|
||||||
public string? CodeChallenge { get; set; }
|
public string? CodeChallenge { get; set; }
|
||||||
public string? CodeChallengeMethod { get; set; }
|
public string? CodeChallengeMethod { get; set; }
|
||||||
public string? Nonce { get; set; }
|
public string? Nonce { get; set; }
|
||||||
public Instant Expiration { get; set; }
|
|
||||||
public Instant CreatedAt { get; set; }
|
public Instant CreatedAt { get; set; }
|
||||||
}
|
}
|
||||||
|
@ -1,13 +1,36 @@
|
|||||||
using System;
|
using System.Security.Cryptography;
|
||||||
|
|
||||||
namespace DysonNetwork.Sphere.Auth.OidcProvider.Options;
|
namespace DysonNetwork.Sphere.Auth.OidcProvider.Options;
|
||||||
|
|
||||||
public class OidcProviderOptions
|
public class OidcProviderOptions
|
||||||
{
|
{
|
||||||
public string IssuerUri { get; set; } = "https://your-issuer-uri.com";
|
public string IssuerUri { get; set; } = "https://your-issuer-uri.com";
|
||||||
public string SigningKey { get; set; } = "replace-with-a-secure-random-key";
|
public string? PublicKeyPath { get; set; }
|
||||||
|
public string? PrivateKeyPath { get; set; }
|
||||||
public TimeSpan AccessTokenLifetime { get; set; } = TimeSpan.FromHours(1);
|
public TimeSpan AccessTokenLifetime { get; set; } = TimeSpan.FromHours(1);
|
||||||
public TimeSpan RefreshTokenLifetime { get; set; } = TimeSpan.FromDays(30);
|
public TimeSpan RefreshTokenLifetime { get; set; } = TimeSpan.FromDays(30);
|
||||||
public TimeSpan AuthorizationCodeLifetime { get; set; } = TimeSpan.FromMinutes(5);
|
public TimeSpan AuthorizationCodeLifetime { get; set; } = TimeSpan.FromMinutes(5);
|
||||||
public bool RequireHttpsMetadata { get; set; } = true;
|
public bool RequireHttpsMetadata { get; set; } = true;
|
||||||
}
|
|
||||||
|
public RSA? GetRsaPrivateKey()
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(PrivateKeyPath) || !File.Exists(PrivateKeyPath))
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var privateKey = File.ReadAllText(PrivateKeyPath);
|
||||||
|
var rsa = RSA.Create();
|
||||||
|
rsa.ImportFromPem(privateKey.AsSpan());
|
||||||
|
return rsa;
|
||||||
|
}
|
||||||
|
|
||||||
|
public RSA? GetRsaPublicKey()
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(PublicKeyPath) || !File.Exists(PublicKeyPath))
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var publicKey = File.ReadAllText(PublicKeyPath);
|
||||||
|
var rsa = RSA.Create();
|
||||||
|
rsa.ImportFromPem(publicKey.AsSpan());
|
||||||
|
return rsa;
|
||||||
|
}
|
||||||
|
}
|
@ -2,13 +2,11 @@ using System.IdentityModel.Tokens.Jwt;
|
|||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Text.Encodings.Web;
|
|
||||||
using System.Text.Json;
|
|
||||||
using DysonNetwork.Sphere.Auth.OidcProvider.Models;
|
using DysonNetwork.Sphere.Auth.OidcProvider.Models;
|
||||||
using DysonNetwork.Sphere.Auth.OidcProvider.Options;
|
using DysonNetwork.Sphere.Auth.OidcProvider.Options;
|
||||||
using DysonNetwork.Sphere.Auth.OidcProvider.Responses;
|
using DysonNetwork.Sphere.Auth.OidcProvider.Responses;
|
||||||
using DysonNetwork.Sphere.Developer;
|
using DysonNetwork.Sphere.Developer;
|
||||||
using Microsoft.AspNetCore.Identity;
|
using DysonNetwork.Sphere.Storage;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using Microsoft.IdentityModel.Tokens;
|
using Microsoft.IdentityModel.Tokens;
|
||||||
@ -18,7 +16,8 @@ namespace DysonNetwork.Sphere.Auth.OidcProvider.Services;
|
|||||||
|
|
||||||
public class OidcProviderService(
|
public class OidcProviderService(
|
||||||
AppDatabase db,
|
AppDatabase db,
|
||||||
IClock clock,
|
AuthService auth,
|
||||||
|
ICacheService cache,
|
||||||
IOptions<OidcProviderOptions> options,
|
IOptions<OidcProviderOptions> options,
|
||||||
ILogger<OidcProviderService> logger
|
ILogger<OidcProviderService> logger
|
||||||
)
|
)
|
||||||
@ -39,11 +38,26 @@ public class OidcProviderService(
|
|||||||
.FirstOrDefaultAsync(c => c.Id == appId);
|
.FirstOrDefaultAsync(c => c.Id == appId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<Session?> FindValidSessionAsync(Guid accountId, Guid clientId)
|
||||||
|
{
|
||||||
|
var now = SystemClock.Instance.GetCurrentInstant();
|
||||||
|
|
||||||
|
return await db.AuthSessions
|
||||||
|
.Include(s => s.Challenge)
|
||||||
|
.Where(s => s.AccountId == accountId &&
|
||||||
|
s.AppId == clientId &&
|
||||||
|
(s.ExpiredAt == null || s.ExpiredAt > now) &&
|
||||||
|
s.Challenge.Type == ChallengeType.OAuth)
|
||||||
|
.OrderByDescending(s => s.CreatedAt)
|
||||||
|
.FirstOrDefaultAsync();
|
||||||
|
}
|
||||||
|
|
||||||
public async Task<bool> ValidateClientCredentialsAsync(Guid clientId, string clientSecret)
|
public async Task<bool> ValidateClientCredentialsAsync(Guid clientId, string clientSecret)
|
||||||
{
|
{
|
||||||
var client = await FindClientByIdAsync(clientId);
|
var client = await FindClientByIdAsync(clientId);
|
||||||
if (client == null) return false;
|
if (client == null) return false;
|
||||||
|
|
||||||
|
var clock = SystemClock.Instance;
|
||||||
var secret = client.Secrets
|
var secret = client.Secrets
|
||||||
.Where(s => s.IsOidc && (s.ExpiredAt == null || s.ExpiredAt > clock.GetCurrentInstant()))
|
.Where(s => s.IsOidc && (s.ExpiredAt == null || s.ExpiredAt > clock.GetCurrentInstant()))
|
||||||
.FirstOrDefault(s => s.Secret == clientSecret); // In production, use proper hashing
|
.FirstOrDefault(s => s.Secret == clientSecret); // In production, use proper hashing
|
||||||
@ -53,25 +67,53 @@ public class OidcProviderService(
|
|||||||
|
|
||||||
public async Task<TokenResponse> GenerateTokenResponseAsync(
|
public async Task<TokenResponse> GenerateTokenResponseAsync(
|
||||||
Guid clientId,
|
Guid clientId,
|
||||||
string subjectId,
|
string? authorizationCode = null,
|
||||||
IEnumerable<string>? scopes = null,
|
string? redirectUri = null,
|
||||||
string? authorizationCode = null)
|
string? codeVerifier = null,
|
||||||
|
Guid? sessionId = null
|
||||||
|
)
|
||||||
{
|
{
|
||||||
var client = await FindClientByIdAsync(clientId);
|
var client = await FindClientByIdAsync(clientId);
|
||||||
if (client == null)
|
if (client == null)
|
||||||
throw new InvalidOperationException("Client not found");
|
throw new InvalidOperationException("Client not found");
|
||||||
|
|
||||||
|
Session session;
|
||||||
|
var clock = SystemClock.Instance;
|
||||||
var now = clock.GetCurrentInstant();
|
var now = clock.GetCurrentInstant();
|
||||||
|
|
||||||
|
List<string>? scopes = null;
|
||||||
|
if (authorizationCode != null)
|
||||||
|
{
|
||||||
|
// Authorization code flow
|
||||||
|
var authCode = await ValidateAuthorizationCodeAsync(authorizationCode, clientId, redirectUri, codeVerifier);
|
||||||
|
if (authCode is null) throw new InvalidOperationException("Invalid authorization code");
|
||||||
|
var account = await db.Accounts.Where(a => a.Id == authCode.AccountId).FirstOrDefaultAsync();
|
||||||
|
if (account is null) throw new InvalidOperationException("Account was not found");
|
||||||
|
|
||||||
|
session = await auth.CreateSessionForOidcAsync(account, now, client.Id);
|
||||||
|
scopes = authCode.Scopes;
|
||||||
|
}
|
||||||
|
else if (sessionId.HasValue)
|
||||||
|
{
|
||||||
|
// Refresh token flow
|
||||||
|
session = await FindSessionByIdAsync(sessionId.Value) ??
|
||||||
|
throw new InvalidOperationException("Invalid session");
|
||||||
|
|
||||||
|
// Verify the session is still valid
|
||||||
|
if (session.ExpiredAt < now)
|
||||||
|
throw new InvalidOperationException("Session has expired");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Either authorization code or session ID must be provided");
|
||||||
|
}
|
||||||
|
|
||||||
var expiresIn = (int)_options.AccessTokenLifetime.TotalSeconds;
|
var expiresIn = (int)_options.AccessTokenLifetime.TotalSeconds;
|
||||||
var expiresAt = now.Plus(Duration.FromSeconds(expiresIn));
|
var expiresAt = now.Plus(Duration.FromSeconds(expiresIn));
|
||||||
|
|
||||||
// Generate access token
|
// Generate an access token
|
||||||
var accessToken = GenerateJwtToken(client, subjectId, expiresAt, scopes);
|
var accessToken = GenerateJwtToken(client, session, expiresAt, scopes);
|
||||||
var refreshToken = GenerateRefreshToken();
|
var refreshToken = GenerateRefreshToken(session);
|
||||||
|
|
||||||
// In a real implementation, you would store the token in the database
|
|
||||||
// For this example, we'll just return the token without storing it
|
|
||||||
// as we don't have a dedicated OIDC token table
|
|
||||||
|
|
||||||
return new TokenResponse
|
return new TokenResponse
|
||||||
{
|
{
|
||||||
@ -83,32 +125,41 @@ public class OidcProviderService(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private string GenerateJwtToken(CustomApp client, string subjectId, Instant expiresAt, IEnumerable<string>? scopes = null)
|
private string GenerateJwtToken(
|
||||||
|
CustomApp client,
|
||||||
|
Session session,
|
||||||
|
Instant expiresAt,
|
||||||
|
IEnumerable<string>? scopes = null
|
||||||
|
)
|
||||||
{
|
{
|
||||||
var tokenHandler = new JwtSecurityTokenHandler();
|
var tokenHandler = new JwtSecurityTokenHandler();
|
||||||
var key = Encoding.ASCII.GetBytes(_options.SigningKey);
|
var clock = SystemClock.Instance;
|
||||||
|
var now = clock.GetCurrentInstant();
|
||||||
|
|
||||||
var tokenDescriptor = new SecurityTokenDescriptor
|
var tokenDescriptor = new SecurityTokenDescriptor
|
||||||
{
|
{
|
||||||
Subject = new ClaimsIdentity(new[]
|
Subject = new ClaimsIdentity([
|
||||||
{
|
new Claim(JwtRegisteredClaimNames.Sub, session.AccountId.ToString()),
|
||||||
new Claim(JwtRegisteredClaimNames.Sub, subjectId),
|
new Claim(JwtRegisteredClaimNames.Jti, session.Id.ToString()),
|
||||||
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
|
new Claim(JwtRegisteredClaimNames.Iat, now.ToUnixTimeSeconds().ToString(),
|
||||||
new Claim(JwtRegisteredClaimNames.Iat, clock.GetCurrentInstant().ToUnixTimeSeconds().ToString(),
|
|
||||||
ClaimValueTypes.Integer64),
|
ClaimValueTypes.Integer64),
|
||||||
new Claim("client_id", client.Id.ToString())
|
new Claim("client_id", client.Id.ToString())
|
||||||
}),
|
]),
|
||||||
Expires = expiresAt.ToDateTimeUtc(),
|
Expires = expiresAt.ToDateTimeUtc(),
|
||||||
Issuer = _options.IssuerUri,
|
Issuer = _options.IssuerUri,
|
||||||
Audience = client.Id.ToString(),
|
Audience = client.Id.ToString()
|
||||||
SigningCredentials = new SigningCredentials(
|
|
||||||
new SymmetricSecurityKey(key),
|
|
||||||
SecurityAlgorithms.HmacSha256Signature)
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Add scopes as claims if provided, otherwise use client's default scopes
|
// Try to use RSA signing if keys are available, fall back to HMAC
|
||||||
var effectiveScopes = scopes?.ToList() ?? client.AllowedScopes?.ToList() ?? new List<string>();
|
var rsaPrivateKey = _options.GetRsaPrivateKey();
|
||||||
if (effectiveScopes.Any())
|
tokenDescriptor.SigningCredentials = new SigningCredentials(
|
||||||
|
new RsaSecurityKey(rsaPrivateKey),
|
||||||
|
SecurityAlgorithms.RsaSha256
|
||||||
|
);
|
||||||
|
|
||||||
|
// Add scopes as claims if provided
|
||||||
|
var effectiveScopes = scopes?.ToList() ?? client.OauthConfig!.AllowedScopes?.ToList() ?? [];
|
||||||
|
if (effectiveScopes.Count != 0)
|
||||||
{
|
{
|
||||||
tokenDescriptor.Subject.AddClaims(
|
tokenDescriptor.Subject.AddClaims(
|
||||||
effectiveScopes.Select(scope => new Claim("scope", scope)));
|
effectiveScopes.Select(scope => new Claim("scope", scope)));
|
||||||
@ -118,15 +169,49 @@ public class OidcProviderService(
|
|||||||
return tokenHandler.WriteToken(token);
|
return tokenHandler.WriteToken(token);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string GenerateRefreshToken()
|
public (bool isValid, JwtSecurityToken? token) ValidateToken(string token)
|
||||||
{
|
{
|
||||||
using var rng = RandomNumberGenerator.Create();
|
try
|
||||||
var bytes = new byte[32];
|
{
|
||||||
rng.GetBytes(bytes);
|
var tokenHandler = new JwtSecurityTokenHandler();
|
||||||
return Convert.ToBase64String(bytes)
|
var validationParameters = new TokenValidationParameters
|
||||||
.Replace("+", "-")
|
{
|
||||||
.Replace("/", "_")
|
ValidateIssuer = true,
|
||||||
.Replace("=", "");
|
ValidIssuer = _options.IssuerUri,
|
||||||
|
ValidateAudience = false,
|
||||||
|
ValidateLifetime = true,
|
||||||
|
ClockSkew = TimeSpan.Zero
|
||||||
|
};
|
||||||
|
|
||||||
|
// Try to use RSA validation if public key is available
|
||||||
|
var rsaPublicKey = _options.GetRsaPublicKey();
|
||||||
|
validationParameters.IssuerSigningKey = new RsaSecurityKey(rsaPublicKey);
|
||||||
|
validationParameters.ValidateIssuerSigningKey = true;
|
||||||
|
validationParameters.ValidAlgorithms = new[] { SecurityAlgorithms.RsaSha256 };
|
||||||
|
|
||||||
|
|
||||||
|
tokenHandler.ValidateToken(token, validationParameters, out var validatedToken);
|
||||||
|
return (true, (JwtSecurityToken)validatedToken);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.LogError(ex, "Token validation failed");
|
||||||
|
return (false, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<Session?> FindSessionByIdAsync(Guid sessionId)
|
||||||
|
{
|
||||||
|
return await db.AuthSessions
|
||||||
|
.Include(s => s.Account)
|
||||||
|
.Include(s => s.Challenge)
|
||||||
|
.Include(s => s.App)
|
||||||
|
.FirstOrDefaultAsync(s => s.Id == sessionId);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string GenerateRefreshToken(Session session)
|
||||||
|
{
|
||||||
|
return Convert.ToBase64String(session.Id.ToByteArray());
|
||||||
}
|
}
|
||||||
|
|
||||||
private static bool VerifyHashedSecret(string secret, string hashedSecret)
|
private static bool VerifyHashedSecret(string secret, string hashedSecret)
|
||||||
@ -136,103 +221,112 @@ public class OidcProviderService(
|
|||||||
return string.Equals(secret, hashedSecret, StringComparison.Ordinal);
|
return string.Equals(secret, hashedSecret, StringComparison.Ordinal);
|
||||||
}
|
}
|
||||||
|
|
||||||
public JwtSecurityToken? ValidateToken(string token)
|
public async Task<string> GenerateAuthorizationCodeForReuseSessionAsync(
|
||||||
{
|
Session session,
|
||||||
try
|
|
||||||
{
|
|
||||||
var tokenHandler = new JwtSecurityTokenHandler();
|
|
||||||
var key = Encoding.ASCII.GetBytes(_options.SigningKey);
|
|
||||||
|
|
||||||
tokenHandler.ValidateToken(token, new TokenValidationParameters
|
|
||||||
{
|
|
||||||
ValidateIssuerSigningKey = true,
|
|
||||||
IssuerSigningKey = new SymmetricSecurityKey(key),
|
|
||||||
ValidateIssuer = true,
|
|
||||||
ValidIssuer = _options.IssuerUri,
|
|
||||||
ValidateAudience = true,
|
|
||||||
ValidateLifetime = true,
|
|
||||||
ClockSkew = TimeSpan.Zero
|
|
||||||
}, out var validatedToken);
|
|
||||||
|
|
||||||
return (JwtSecurityToken)validatedToken;
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
logger.LogError(ex, "Token validation failed");
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static readonly Dictionary<string, AuthorizationCodeInfo> _authorizationCodes = new();
|
|
||||||
|
|
||||||
public async Task<string> GenerateAuthorizationCodeAsync(
|
|
||||||
Guid clientId,
|
Guid clientId,
|
||||||
string userId,
|
|
||||||
string redirectUri,
|
string redirectUri,
|
||||||
IEnumerable<string> scopes,
|
IEnumerable<string> scopes,
|
||||||
string? codeChallenge = null,
|
string? codeChallenge = null,
|
||||||
string? codeChallengeMethod = null,
|
string? codeChallengeMethod = null,
|
||||||
string? nonce = null)
|
string? nonce = null)
|
||||||
{
|
{
|
||||||
// Generate a random code
|
var clock = SystemClock.Instance;
|
||||||
var code = GenerateRandomString(32);
|
|
||||||
var now = clock.GetCurrentInstant();
|
var now = clock.GetCurrentInstant();
|
||||||
|
var code = Guid.NewGuid().ToString("N");
|
||||||
// Store the code with its metadata
|
|
||||||
_authorizationCodes[code] = new AuthorizationCodeInfo
|
// Update the session's last activity time
|
||||||
|
await db.AuthSessions.Where(s => s.Id == session.Id)
|
||||||
|
.ExecuteUpdateAsync(s => s.SetProperty(s => s.LastGrantedAt, now));
|
||||||
|
|
||||||
|
// Create the authorization code info
|
||||||
|
var authCodeInfo = new AuthorizationCodeInfo
|
||||||
{
|
{
|
||||||
ClientId = clientId,
|
ClientId = clientId,
|
||||||
UserId = userId,
|
AccountId = session.AccountId,
|
||||||
RedirectUri = redirectUri,
|
RedirectUri = redirectUri,
|
||||||
Scopes = scopes.ToList(),
|
Scopes = scopes.ToList(),
|
||||||
CodeChallenge = codeChallenge,
|
CodeChallenge = codeChallenge,
|
||||||
CodeChallengeMethod = codeChallengeMethod,
|
CodeChallengeMethod = codeChallengeMethod,
|
||||||
Nonce = nonce,
|
Nonce = nonce,
|
||||||
Expiration = now.Plus(Duration.FromTimeSpan(_options.AuthorizationCodeLifetime)),
|
|
||||||
CreatedAt = now
|
CreatedAt = now
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Store the code with its metadata in the cache
|
||||||
|
var cacheKey = $"auth:code:{code}";
|
||||||
|
await cache.SetAsync(cacheKey, authCodeInfo, _options.AuthorizationCodeLifetime);
|
||||||
|
|
||||||
|
logger.LogInformation("Generated authorization code for client {ClientId} and user {UserId}", clientId, session.AccountId);
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<string> GenerateAuthorizationCodeAsync(
|
||||||
|
Guid clientId,
|
||||||
|
Guid userId,
|
||||||
|
string redirectUri,
|
||||||
|
IEnumerable<string> scopes,
|
||||||
|
string? codeChallenge = null,
|
||||||
|
string? codeChallengeMethod = null,
|
||||||
|
string? nonce = null
|
||||||
|
)
|
||||||
|
{
|
||||||
|
// Generate a random code
|
||||||
|
var clock = SystemClock.Instance;
|
||||||
|
var code = GenerateRandomString(32);
|
||||||
|
var now = clock.GetCurrentInstant();
|
||||||
|
|
||||||
|
// Create the authorization code info
|
||||||
|
var authCodeInfo = new AuthorizationCodeInfo
|
||||||
|
{
|
||||||
|
ClientId = clientId,
|
||||||
|
AccountId = userId,
|
||||||
|
RedirectUri = redirectUri,
|
||||||
|
Scopes = scopes.ToList(),
|
||||||
|
CodeChallenge = codeChallenge,
|
||||||
|
CodeChallengeMethod = codeChallengeMethod,
|
||||||
|
Nonce = nonce,
|
||||||
|
CreatedAt = now
|
||||||
|
};
|
||||||
|
|
||||||
|
// Store the code with its metadata in the cache
|
||||||
|
var cacheKey = $"auth:code:{code}";
|
||||||
|
await cache.SetAsync(cacheKey, authCodeInfo, _options.AuthorizationCodeLifetime);
|
||||||
|
|
||||||
logger.LogInformation("Generated authorization code for client {ClientId} and user {UserId}", clientId, userId);
|
logger.LogInformation("Generated authorization code for client {ClientId} and user {UserId}", clientId, userId);
|
||||||
return code;
|
return code;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<AuthorizationCodeInfo?> ValidateAuthorizationCodeAsync(
|
private async Task<AuthorizationCodeInfo?> ValidateAuthorizationCodeAsync(
|
||||||
string code,
|
string code,
|
||||||
Guid clientId,
|
Guid clientId,
|
||||||
string? redirectUri = null,
|
string? redirectUri = null,
|
||||||
string? codeVerifier = null)
|
string? codeVerifier = null
|
||||||
|
)
|
||||||
{
|
{
|
||||||
if (!_authorizationCodes.TryGetValue(code, out var authCode) || authCode == null)
|
var cacheKey = $"auth:code:{code}";
|
||||||
|
var (found, authCode) = await cache.GetAsyncWithStatus<AuthorizationCodeInfo>(cacheKey);
|
||||||
|
|
||||||
|
if (!found || authCode == null)
|
||||||
{
|
{
|
||||||
logger.LogWarning("Authorization code not found: {Code}", code);
|
logger.LogWarning("Authorization code not found: {Code}", code);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
var now = clock.GetCurrentInstant();
|
|
||||||
|
|
||||||
// Check if code has expired
|
|
||||||
if (now > authCode.Expiration)
|
|
||||||
{
|
|
||||||
logger.LogWarning("Authorization code expired: {Code}", code);
|
|
||||||
_authorizationCodes.Remove(code);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verify client ID matches
|
// Verify client ID matches
|
||||||
if (authCode.ClientId != clientId)
|
if (authCode.ClientId != clientId)
|
||||||
{
|
{
|
||||||
logger.LogWarning("Client ID mismatch for code {Code}. Expected: {ExpectedClientId}, Actual: {ActualClientId}",
|
logger.LogWarning(
|
||||||
|
"Client ID mismatch for code {Code}. Expected: {ExpectedClientId}, Actual: {ActualClientId}",
|
||||||
code, authCode.ClientId, clientId);
|
code, authCode.ClientId, clientId);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verify redirect URI if provided
|
// Verify redirect URI if provided
|
||||||
if (!string.IsNullOrEmpty(redirectUri) && authCode.RedirectUri != redirectUri)
|
if (!string.IsNullOrEmpty(redirectUri) && authCode.RedirectUri != redirectUri)
|
||||||
{
|
{
|
||||||
logger.LogWarning("Redirect URI mismatch for code {Code}", code);
|
logger.LogWarning("Redirect URI mismatch for code {Code}", code);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verify PKCE code challenge if one was provided during authorization
|
// Verify PKCE code challenge if one was provided during authorization
|
||||||
if (!string.IsNullOrEmpty(authCode.CodeChallenge))
|
if (!string.IsNullOrEmpty(authCode.CodeChallenge))
|
||||||
{
|
{
|
||||||
@ -241,33 +335,33 @@ public class OidcProviderService(
|
|||||||
logger.LogWarning("PKCE code verifier is required but not provided for code {Code}", code);
|
logger.LogWarning("PKCE code verifier is required but not provided for code {Code}", code);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
var isValid = authCode.CodeChallengeMethod?.ToUpperInvariant() switch
|
var isValid = authCode.CodeChallengeMethod?.ToUpperInvariant() switch
|
||||||
{
|
{
|
||||||
"S256" => VerifyCodeChallenge(codeVerifier, authCode.CodeChallenge, "S256"),
|
"S256" => VerifyCodeChallenge(codeVerifier, authCode.CodeChallenge, "S256"),
|
||||||
"PLAIN" => VerifyCodeChallenge(codeVerifier, authCode.CodeChallenge, "PLAIN"),
|
"PLAIN" => VerifyCodeChallenge(codeVerifier, authCode.CodeChallenge, "PLAIN"),
|
||||||
_ => false // Unsupported code challenge method
|
_ => false // Unsupported code challenge method
|
||||||
};
|
};
|
||||||
|
|
||||||
if (!isValid)
|
if (!isValid)
|
||||||
{
|
{
|
||||||
logger.LogWarning("PKCE code verifier validation failed for code {Code}", code);
|
logger.LogWarning("PKCE code verifier validation failed for code {Code}", code);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Code is valid, remove it from the store (codes are single-use)
|
// Code is valid, remove it from the cache (codes are single-use)
|
||||||
_authorizationCodes.Remove(code);
|
await cache.RemoveAsync(cacheKey);
|
||||||
|
|
||||||
return authCode;
|
return authCode;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string GenerateRandomString(int length)
|
private static string GenerateRandomString(int length)
|
||||||
{
|
{
|
||||||
const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";
|
const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";
|
||||||
var random = RandomNumberGenerator.Create();
|
var random = RandomNumberGenerator.Create();
|
||||||
var result = new char[length];
|
var result = new char[length];
|
||||||
|
|
||||||
for (int i = 0; i < length; i++)
|
for (int i = 0; i < length; i++)
|
||||||
{
|
{
|
||||||
var randomNumber = new byte[4];
|
var randomNumber = new byte[4];
|
||||||
@ -275,14 +369,14 @@ public class OidcProviderService(
|
|||||||
var index = (int)(BitConverter.ToUInt32(randomNumber, 0) % chars.Length);
|
var index = (int)(BitConverter.ToUInt32(randomNumber, 0) % chars.Length);
|
||||||
result[i] = chars[index];
|
result[i] = chars[index];
|
||||||
}
|
}
|
||||||
|
|
||||||
return new string(result);
|
return new string(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static bool VerifyCodeChallenge(string codeVerifier, string codeChallenge, string method)
|
private static bool VerifyCodeChallenge(string codeVerifier, string codeChallenge, string method)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrEmpty(codeVerifier)) return false;
|
if (string.IsNullOrEmpty(codeVerifier)) return false;
|
||||||
|
|
||||||
if (method == "S256")
|
if (method == "S256")
|
||||||
{
|
{
|
||||||
using var sha256 = SHA256.Create();
|
using var sha256 = SHA256.Create();
|
||||||
@ -290,12 +384,12 @@ public class OidcProviderService(
|
|||||||
var base64 = Base64UrlEncoder.Encode(hash);
|
var base64 = Base64UrlEncoder.Encode(hash);
|
||||||
return string.Equals(base64, codeChallenge, StringComparison.Ordinal);
|
return string.Equals(base64, codeChallenge, StringComparison.Ordinal);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (method == "PLAIN")
|
if (method == "PLAIN")
|
||||||
{
|
{
|
||||||
return string.Equals(codeVerifier, codeChallenge, StringComparison.Ordinal);
|
return string.Equals(codeVerifier, codeChallenge, StringComparison.Ordinal);
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -376,7 +376,7 @@ public class ConnectionController(
|
|||||||
|
|
||||||
await db.SaveChangesAsync();
|
await db.SaveChangesAsync();
|
||||||
|
|
||||||
var loginSession = await auth.CreateSessionAsync(account, clock.GetCurrentInstant());
|
var loginSession = await auth.CreateSessionForOidcAsync(account, clock.GetCurrentInstant());
|
||||||
var loginToken = auth.CreateToken(loginSession);
|
var loginToken = auth.CreateToken(loginSession);
|
||||||
return Redirect($"/auth/token?token={loginToken}");
|
return Redirect($"/auth/token?token={loginToken}");
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
using System.ComponentModel.DataAnnotations;
|
using System.ComponentModel.DataAnnotations;
|
||||||
using System.ComponentModel.DataAnnotations.Schema;
|
using System.ComponentModel.DataAnnotations.Schema;
|
||||||
using System.Text.Json.Serialization;
|
using System.Text.Json.Serialization;
|
||||||
|
using DysonNetwork.Sphere.Developer;
|
||||||
using NodaTime;
|
using NodaTime;
|
||||||
using Point = NetTopologySuite.Geometries.Point;
|
using Point = NetTopologySuite.Geometries.Point;
|
||||||
|
|
||||||
@ -17,6 +18,8 @@ public class Session : ModelBase
|
|||||||
[JsonIgnore] public Account.Account Account { get; set; } = null!;
|
[JsonIgnore] public Account.Account Account { get; set; } = null!;
|
||||||
public Guid ChallengeId { get; set; }
|
public Guid ChallengeId { get; set; }
|
||||||
public Challenge Challenge { get; set; } = null!;
|
public Challenge Challenge { get; set; } = null!;
|
||||||
|
public Guid? AppId { get; set; }
|
||||||
|
public CustomApp? App { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
public enum ChallengeType
|
public enum ChallengeType
|
||||||
|
@ -252,7 +252,7 @@ public partial class ChatService(
|
|||||||
|
|
||||||
if (member.Account.Id == sender.AccountId) continue;
|
if (member.Account.Id == sender.AccountId) continue;
|
||||||
if (member.Notify == ChatMemberNotify.None) continue;
|
if (member.Notify == ChatMemberNotify.None) continue;
|
||||||
if (scopedWs.IsUserSubscribedToChatRoom(member.AccountId, room.Id.ToString())) continue;
|
// if (scopedWs.IsUserSubscribedToChatRoom(member.AccountId, room.Id.ToString())) continue;
|
||||||
if (message.MembersMentioned is null || !message.MembersMentioned.Contains(member.Account.Id))
|
if (message.MembersMentioned is null || !message.MembersMentioned.Contains(member.Account.Id))
|
||||||
{
|
{
|
||||||
var now = SystemClock.Instance.GetCurrentInstant();
|
var now = SystemClock.Instance.GetCurrentInstant();
|
||||||
@ -575,4 +575,4 @@ public class SyncResponse
|
|||||||
{
|
{
|
||||||
public List<MessageChange> Changes { get; set; } = [];
|
public List<MessageChange> Changes { get; set; } = [];
|
||||||
public Instant CurrentTimestamp { get; set; }
|
public Instant CurrentTimestamp { get; set; }
|
||||||
}
|
}
|
||||||
|
92
DysonNetwork.Sphere/Connection/AutoCompletionController.cs
Normal file
92
DysonNetwork.Sphere/Connection/AutoCompletionController.cs
Normal file
@ -0,0 +1,92 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace DysonNetwork.Sphere.Connection;
|
||||||
|
|
||||||
|
[ApiController]
|
||||||
|
[Route("completion")]
|
||||||
|
public class AutoCompletionController(AppDatabase db)
|
||||||
|
: ControllerBase
|
||||||
|
{
|
||||||
|
[HttpPost]
|
||||||
|
public async Task<ActionResult<AutoCompletionResponse>> GetCompletions([FromBody] AutoCompletionRequest request)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(request?.Content))
|
||||||
|
{
|
||||||
|
return BadRequest("Content is required");
|
||||||
|
}
|
||||||
|
|
||||||
|
var result = new AutoCompletionResponse();
|
||||||
|
var lastWord = request.Content.Trim().Split(' ').LastOrDefault() ?? string.Empty;
|
||||||
|
|
||||||
|
if (lastWord.StartsWith("@"))
|
||||||
|
{
|
||||||
|
var searchTerm = lastWord[1..]; // Remove the @
|
||||||
|
result.Items = await GetAccountCompletions(searchTerm);
|
||||||
|
result.Type = "account";
|
||||||
|
}
|
||||||
|
else if (lastWord.StartsWith(":"))
|
||||||
|
{
|
||||||
|
var searchTerm = lastWord[1..]; // Remove the :
|
||||||
|
result.Items = await GetStickerCompletions(searchTerm);
|
||||||
|
result.Type = "sticker";
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<List<CompletionItem>> GetAccountCompletions(string searchTerm)
|
||||||
|
{
|
||||||
|
return await db.Accounts
|
||||||
|
.Where(a => EF.Functions.ILike(a.Name, $"%{searchTerm}%"))
|
||||||
|
.OrderBy(a => a.Name)
|
||||||
|
.Take(10)
|
||||||
|
.Select(a => new CompletionItem
|
||||||
|
{
|
||||||
|
Id = a.Id.ToString(),
|
||||||
|
DisplayName = a.Name,
|
||||||
|
SecondaryText = a.Nick,
|
||||||
|
Type = "account",
|
||||||
|
Data = a
|
||||||
|
})
|
||||||
|
.ToListAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<List<CompletionItem>> GetStickerCompletions(string searchTerm)
|
||||||
|
{
|
||||||
|
return await db.Stickers
|
||||||
|
.Include(s => s.Pack)
|
||||||
|
.Where(s => EF.Functions.ILike(s.Pack.Prefix + s.Slug, $"%{searchTerm}%"))
|
||||||
|
.OrderBy(s => s.Slug)
|
||||||
|
.Take(10)
|
||||||
|
.Select(s => new CompletionItem
|
||||||
|
{
|
||||||
|
Id = s.Id.ToString(),
|
||||||
|
DisplayName = s.Slug,
|
||||||
|
Type = "sticker",
|
||||||
|
Data = s
|
||||||
|
})
|
||||||
|
.ToListAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public class AutoCompletionRequest
|
||||||
|
{
|
||||||
|
[Required] public string Content { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
public class AutoCompletionResponse
|
||||||
|
{
|
||||||
|
public string Type { get; set; } = string.Empty;
|
||||||
|
public List<CompletionItem> Items { get; set; } = new();
|
||||||
|
}
|
||||||
|
|
||||||
|
public class CompletionItem
|
||||||
|
{
|
||||||
|
public string Id { get; set; } = string.Empty;
|
||||||
|
public string DisplayName { get; set; } = string.Empty;
|
||||||
|
public string? SecondaryText { get; set; }
|
||||||
|
public string Type { get; set; } = string.Empty;
|
||||||
|
public object? Data { get; set; }
|
||||||
|
}
|
@ -1,5 +1,6 @@
|
|||||||
using System.ComponentModel.DataAnnotations;
|
using System.ComponentModel.DataAnnotations;
|
||||||
using System.ComponentModel.DataAnnotations.Schema;
|
using System.ComponentModel.DataAnnotations.Schema;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
namespace DysonNetwork.Sphere.Connection.WebReader;
|
namespace DysonNetwork.Sphere.Connection.WebReader;
|
||||||
|
|
||||||
@ -7,8 +8,8 @@ public class WebArticle : ModelBase
|
|||||||
{
|
{
|
||||||
public Guid Id { get; set; } = Guid.NewGuid();
|
public Guid Id { get; set; } = Guid.NewGuid();
|
||||||
|
|
||||||
[MaxLength(4096)] public string Title { get; set; }
|
[MaxLength(4096)] public string Title { get; set; } = null!;
|
||||||
[MaxLength(8192)] public string Url { get; set; }
|
[MaxLength(8192)] public string Url { get; set; } = null!;
|
||||||
[MaxLength(4096)] public string? Author { get; set; }
|
[MaxLength(4096)] public string? Author { get; set; }
|
||||||
|
|
||||||
[Column(TypeName = "jsonb")] public Dictionary<string, object>? Meta { get; set; }
|
[Column(TypeName = "jsonb")] public Dictionary<string, object>? Meta { get; set; }
|
||||||
@ -31,8 +32,8 @@ public class WebFeedConfig
|
|||||||
public class WebFeed : ModelBase
|
public class WebFeed : ModelBase
|
||||||
{
|
{
|
||||||
public Guid Id { get; set; } = Guid.NewGuid();
|
public Guid Id { get; set; } = Guid.NewGuid();
|
||||||
[MaxLength(8192)] public string Url { get; set; }
|
[MaxLength(8192)] public string Url { get; set; } = null!;
|
||||||
[MaxLength(4096)] public string Title { get; set; }
|
[MaxLength(4096)] public string Title { get; set; } = null!;
|
||||||
[MaxLength(8192)] public string? Description { get; set; }
|
[MaxLength(8192)] public string? Description { get; set; }
|
||||||
|
|
||||||
[Column(TypeName = "jsonb")] public LinkEmbed? Preview { get; set; }
|
[Column(TypeName = "jsonb")] public LinkEmbed? Preview { get; set; }
|
||||||
@ -41,5 +42,5 @@ public class WebFeed : ModelBase
|
|||||||
public Guid PublisherId { get; set; }
|
public Guid PublisherId { get; set; }
|
||||||
public Publisher.Publisher Publisher { get; set; } = null!;
|
public Publisher.Publisher Publisher { get; set; } = null!;
|
||||||
|
|
||||||
public ICollection<WebArticle> Articles { get; set; } = new List<WebArticle>();
|
[JsonIgnore] public ICollection<WebArticle> Articles { get; set; } = new List<WebArticle>();
|
||||||
}
|
}
|
@ -0,0 +1,82 @@
|
|||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace DysonNetwork.Sphere.Connection.WebReader;
|
||||||
|
|
||||||
|
[ApiController]
|
||||||
|
[Route("/feeds/articles")]
|
||||||
|
public class WebArticleController(AppDatabase db) : ControllerBase
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Get a list of recent web articles
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="limit">Maximum number of articles to return</param>
|
||||||
|
/// <param name="offset">Number of articles to skip</param>
|
||||||
|
/// <param name="feedId">Optional feed ID to filter by</param>
|
||||||
|
/// <param name="publisherId">Optional publisher ID to filter by</param>
|
||||||
|
/// <returns>List of web articles</returns>
|
||||||
|
[HttpGet]
|
||||||
|
public async Task<IActionResult> GetArticles(
|
||||||
|
[FromQuery] int limit = 20,
|
||||||
|
[FromQuery] int offset = 0,
|
||||||
|
[FromQuery] Guid? feedId = null,
|
||||||
|
[FromQuery] Guid? publisherId = null
|
||||||
|
)
|
||||||
|
{
|
||||||
|
var query = db.WebArticles
|
||||||
|
.OrderByDescending(a => a.PublishedAt)
|
||||||
|
.Include(a => a.Feed)
|
||||||
|
.AsQueryable();
|
||||||
|
|
||||||
|
if (feedId.HasValue)
|
||||||
|
query = query.Where(a => a.FeedId == feedId.Value);
|
||||||
|
if (publisherId.HasValue)
|
||||||
|
query = query.Where(a => a.Feed.PublisherId == publisherId.Value);
|
||||||
|
|
||||||
|
var totalCount = await query.CountAsync();
|
||||||
|
var articles = await query
|
||||||
|
.Skip(offset)
|
||||||
|
.Take(limit)
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
Response.Headers["X-Total"] = totalCount.ToString();
|
||||||
|
|
||||||
|
return Ok(articles);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Get a specific web article by ID
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="id">The article ID</param>
|
||||||
|
/// <returns>The web article</returns>
|
||||||
|
[HttpGet("{id:guid}")]
|
||||||
|
[ProducesResponseType(404)]
|
||||||
|
public async Task<IActionResult> GetArticle(Guid id)
|
||||||
|
{
|
||||||
|
var article = await db.WebArticles
|
||||||
|
.Include(a => a.Feed)
|
||||||
|
.FirstOrDefaultAsync(a => a.Id == id);
|
||||||
|
|
||||||
|
if (article == null)
|
||||||
|
return NotFound();
|
||||||
|
|
||||||
|
return Ok(article);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Get random web articles
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="limit">Maximum number of articles to return</param>
|
||||||
|
/// <returns>List of random web articles</returns>
|
||||||
|
[HttpGet("random")]
|
||||||
|
public async Task<IActionResult> GetRandomArticles([FromQuery] int limit = 5)
|
||||||
|
{
|
||||||
|
var articles = await db.WebArticles
|
||||||
|
.OrderBy(_ => EF.Functions.Random())
|
||||||
|
.Include(a => a.Feed)
|
||||||
|
.Take(limit)
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
return Ok(articles);
|
||||||
|
}
|
||||||
|
}
|
@ -1,62 +1,124 @@
|
|||||||
using System.ComponentModel.DataAnnotations;
|
using System.ComponentModel.DataAnnotations;
|
||||||
using DysonNetwork.Sphere.Permission;
|
using DysonNetwork.Sphere.Publisher;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
|
|
||||||
namespace DysonNetwork.Sphere.Connection.WebReader;
|
namespace DysonNetwork.Sphere.Connection.WebReader;
|
||||||
|
|
||||||
[Authorize]
|
[Authorize]
|
||||||
[ApiController]
|
[ApiController]
|
||||||
[Route("/feeds")]
|
[Route("/publishers/{pubName}/feeds")]
|
||||||
public class WebFeedController(WebFeedService webFeedService, AppDatabase database) : ControllerBase
|
public class WebFeedController(WebFeedService webFeed, PublisherService ps) : ControllerBase
|
||||||
{
|
{
|
||||||
public class CreateWebFeedRequest
|
public record WebFeedRequest(
|
||||||
|
[MaxLength(8192)] string? Url,
|
||||||
|
[MaxLength(4096)] string? Title,
|
||||||
|
[MaxLength(8192)] string? Description,
|
||||||
|
WebFeedConfig? Config
|
||||||
|
);
|
||||||
|
|
||||||
|
[HttpGet]
|
||||||
|
public async Task<IActionResult> ListFeeds([FromRoute] string pubName)
|
||||||
{
|
{
|
||||||
[Required]
|
var publisher = await ps.GetPublisherByName(pubName);
|
||||||
[MaxLength(8192)]
|
if (publisher is null) return NotFound();
|
||||||
public required string Url { get; set; }
|
var feeds = await webFeed.GetFeedsByPublisherAsync(publisher.Id);
|
||||||
|
return Ok(feeds);
|
||||||
[Required]
|
|
||||||
[MaxLength(4096)]
|
|
||||||
public required string Title { get; set; }
|
|
||||||
|
|
||||||
[MaxLength(8192)]
|
|
||||||
public string? Description { get; set; }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[HttpGet("{id:guid}")]
|
||||||
[HttpPost]
|
public async Task<IActionResult> GetFeed([FromRoute] string pubName, Guid id)
|
||||||
public async Task<IActionResult> CreateWebFeed([FromBody] CreateWebFeedRequest request)
|
|
||||||
{
|
{
|
||||||
var feed = await webFeedService.CreateWebFeedAsync(request, User);
|
var publisher = await ps.GetPublisherByName(pubName);
|
||||||
|
if (publisher is null) return NotFound();
|
||||||
|
|
||||||
|
var feed = await webFeed.GetFeedAsync(id, publisherId: publisher.Id);
|
||||||
|
if (feed == null)
|
||||||
|
return NotFound();
|
||||||
|
|
||||||
return Ok(feed);
|
return Ok(feed);
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost("scrape/{feedId}")]
|
[HttpPost]
|
||||||
[RequiredPermission("maintenance", "web-feeds")]
|
[Authorize]
|
||||||
public async Task<ActionResult> ScrapeFeed(Guid feedId)
|
public async Task<IActionResult> CreateWebFeed([FromRoute] string pubName, [FromBody] WebFeedRequest request)
|
||||||
{
|
{
|
||||||
var feed = await database.Set<WebFeed>().FindAsync(feedId);
|
if (HttpContext.Items["CurrentUser"] is not Account.Account currentUser) return Unauthorized();
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(request.Url) || string.IsNullOrWhiteSpace(request.Title))
|
||||||
|
return BadRequest("Url and title are required");
|
||||||
|
|
||||||
|
var publisher = await ps.GetPublisherByName(pubName);
|
||||||
|
if (publisher is null) return NotFound();
|
||||||
|
|
||||||
|
if (!await ps.IsMemberWithRole(publisher.Id, currentUser.Id, PublisherMemberRole.Editor))
|
||||||
|
return StatusCode(403, "You must be an editor of the publisher to create a web feed");
|
||||||
|
|
||||||
|
var feed = await webFeed.CreateWebFeedAsync(publisher, request);
|
||||||
|
return Ok(feed);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPatch("{id:guid}")]
|
||||||
|
[Authorize]
|
||||||
|
public async Task<IActionResult> UpdateFeed([FromRoute] string pubName, Guid id, [FromBody] WebFeedRequest request)
|
||||||
|
{
|
||||||
|
if (HttpContext.Items["CurrentUser"] is not Account.Account currentUser) return Unauthorized();
|
||||||
|
|
||||||
|
var publisher = await ps.GetPublisherByName(pubName);
|
||||||
|
if (publisher is null) return NotFound();
|
||||||
|
|
||||||
|
if (!await ps.IsMemberWithRole(publisher.Id, currentUser.Id, PublisherMemberRole.Editor))
|
||||||
|
return StatusCode(403, "You must be an editor of the publisher to update a web feed");
|
||||||
|
|
||||||
|
var feed = await webFeed.GetFeedAsync(id, publisherId: publisher.Id);
|
||||||
|
if (feed == null)
|
||||||
|
return NotFound();
|
||||||
|
|
||||||
|
feed = await webFeed.UpdateFeedAsync(feed, request);
|
||||||
|
return Ok(feed);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpDelete("{id:guid}")]
|
||||||
|
[Authorize]
|
||||||
|
public async Task<IActionResult> DeleteFeed([FromRoute] string pubName, Guid id)
|
||||||
|
{
|
||||||
|
if (HttpContext.Items["CurrentUser"] is not Account.Account currentUser) return Unauthorized();
|
||||||
|
|
||||||
|
var publisher = await ps.GetPublisherByName(pubName);
|
||||||
|
if (publisher is null) return NotFound();
|
||||||
|
|
||||||
|
if (!await ps.IsMemberWithRole(publisher.Id, currentUser.Id, PublisherMemberRole.Editor))
|
||||||
|
return StatusCode(403, "You must be an editor of the publisher to delete a web feed");
|
||||||
|
|
||||||
|
var feed = await webFeed.GetFeedAsync(id, publisherId: publisher.Id);
|
||||||
|
if (feed == null)
|
||||||
|
return NotFound();
|
||||||
|
|
||||||
|
var result = await webFeed.DeleteFeedAsync(id);
|
||||||
|
if (!result)
|
||||||
|
return NotFound();
|
||||||
|
return NoContent();
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("{id:guid}/scrap")]
|
||||||
|
[Authorize]
|
||||||
|
public async Task<ActionResult> Scrap([FromRoute] string pubName, Guid id)
|
||||||
|
{
|
||||||
|
if (HttpContext.Items["CurrentUser"] is not Account.Account currentUser) return Unauthorized();
|
||||||
|
|
||||||
|
var publisher = await ps.GetPublisherByName(pubName);
|
||||||
|
if (publisher is null) return NotFound();
|
||||||
|
|
||||||
|
if (!await ps.IsMemberWithRole(publisher.Id, currentUser.Id, PublisherMemberRole.Editor))
|
||||||
|
return StatusCode(403, "You must be an editor of the publisher to scrape a web feed");
|
||||||
|
|
||||||
|
var feed = await webFeed.GetFeedAsync(id, publisherId: publisher.Id);
|
||||||
if (feed == null)
|
if (feed == null)
|
||||||
{
|
{
|
||||||
return NotFound();
|
return NotFound();
|
||||||
}
|
}
|
||||||
|
|
||||||
await webFeedService.ScrapeFeedAsync(feed);
|
await webFeed.ScrapeFeedAsync(feed);
|
||||||
return Ok();
|
|
||||||
}
|
|
||||||
|
|
||||||
[HttpPost("scrape-all")]
|
|
||||||
[RequiredPermission("maintenance", "web-feeds")]
|
|
||||||
public async Task<ActionResult> ScrapeAllFeeds()
|
|
||||||
{
|
|
||||||
var feeds = await database.Set<WebFeed>().ToListAsync();
|
|
||||||
foreach (var feed in feeds)
|
|
||||||
{
|
|
||||||
await webFeedService.ScrapeFeedAsync(feed);
|
|
||||||
}
|
|
||||||
|
|
||||||
return Ok();
|
return Ok();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,9 +1,6 @@
|
|||||||
using System.Security.Claims;
|
|
||||||
using System.ServiceModel.Syndication;
|
using System.ServiceModel.Syndication;
|
||||||
using System.Xml;
|
using System.Xml;
|
||||||
using DysonNetwork.Sphere.Account;
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
|
|
||||||
namespace DysonNetwork.Sphere.Connection.WebReader;
|
namespace DysonNetwork.Sphere.Connection.WebReader;
|
||||||
|
|
||||||
@ -11,30 +8,19 @@ public class WebFeedService(
|
|||||||
AppDatabase database,
|
AppDatabase database,
|
||||||
IHttpClientFactory httpClientFactory,
|
IHttpClientFactory httpClientFactory,
|
||||||
ILogger<WebFeedService> logger,
|
ILogger<WebFeedService> logger,
|
||||||
AccountService accountService,
|
|
||||||
WebReaderService webReaderService
|
WebReaderService webReaderService
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
public async Task<WebFeed> CreateWebFeedAsync(WebFeedController.CreateWebFeedRequest request,
|
public async Task<WebFeed> CreateWebFeedAsync(Publisher.Publisher publisher,
|
||||||
ClaimsPrincipal claims)
|
WebFeedController.WebFeedRequest request)
|
||||||
{
|
{
|
||||||
if (claims.Identity?.Name == null)
|
|
||||||
{
|
|
||||||
throw new UnauthorizedAccessException();
|
|
||||||
}
|
|
||||||
|
|
||||||
var account = await accountService.LookupAccount(claims.Identity.Name);
|
|
||||||
if (account == null)
|
|
||||||
{
|
|
||||||
throw new UnauthorizedAccessException();
|
|
||||||
}
|
|
||||||
|
|
||||||
var feed = new WebFeed
|
var feed = new WebFeed
|
||||||
{
|
{
|
||||||
Url = request.Url,
|
Url = request.Url!,
|
||||||
Title = request.Title,
|
Title = request.Title!,
|
||||||
Description = request.Description,
|
Description = request.Description,
|
||||||
PublisherId = account.Id,
|
Config = request.Config ?? new WebFeedConfig(),
|
||||||
|
PublisherId = publisher.Id,
|
||||||
};
|
};
|
||||||
|
|
||||||
database.Set<WebFeed>().Add(feed);
|
database.Set<WebFeed>().Add(feed);
|
||||||
@ -43,6 +29,50 @@ public class WebFeedService(
|
|||||||
return feed;
|
return feed;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<WebFeed?> GetFeedAsync(Guid id, Guid? publisherId = null)
|
||||||
|
{
|
||||||
|
var query = database.WebFeeds.Where(a => a.Id == id).AsQueryable();
|
||||||
|
if (publisherId.HasValue)
|
||||||
|
query = query.Where(a => a.PublisherId == publisherId.Value);
|
||||||
|
return await query.FirstOrDefaultAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<List<WebFeed>> GetFeedsByPublisherAsync(Guid publisherId)
|
||||||
|
{
|
||||||
|
return await database.WebFeeds.Where(a => a.PublisherId == publisherId).ToListAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<WebFeed> UpdateFeedAsync(WebFeed feed, WebFeedController.WebFeedRequest request)
|
||||||
|
{
|
||||||
|
if (request.Url is not null)
|
||||||
|
feed.Url = request.Url;
|
||||||
|
if (request.Title is not null)
|
||||||
|
feed.Title = request.Title;
|
||||||
|
if (request.Description is not null)
|
||||||
|
feed.Description = request.Description;
|
||||||
|
if (request.Config is not null)
|
||||||
|
feed.Config = request.Config;
|
||||||
|
|
||||||
|
database.Update(feed);
|
||||||
|
await database.SaveChangesAsync();
|
||||||
|
|
||||||
|
return feed;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> DeleteFeedAsync(Guid id)
|
||||||
|
{
|
||||||
|
var feed = await database.WebFeeds.FindAsync(id);
|
||||||
|
if (feed == null)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
database.WebFeeds.Remove(feed);
|
||||||
|
await database.SaveChangesAsync();
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
public async Task ScrapeFeedAsync(WebFeed feed, CancellationToken cancellationToken = default)
|
public async Task ScrapeFeedAsync(WebFeed feed, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
var httpClient = httpClientFactory.CreateClient();
|
var httpClient = httpClientFactory.CreateClient();
|
||||||
@ -63,17 +93,13 @@ public class WebFeedService(
|
|||||||
{
|
{
|
||||||
var itemUrl = item.Links.FirstOrDefault()?.Uri.ToString();
|
var itemUrl = item.Links.FirstOrDefault()?.Uri.ToString();
|
||||||
if (string.IsNullOrEmpty(itemUrl))
|
if (string.IsNullOrEmpty(itemUrl))
|
||||||
{
|
|
||||||
continue;
|
continue;
|
||||||
}
|
|
||||||
|
|
||||||
var articleExists = await database.Set<WebArticle>()
|
var articleExists = await database.Set<WebArticle>()
|
||||||
.AnyAsync(a => a.FeedId == feed.Id && a.Url == itemUrl, cancellationToken);
|
.AnyAsync(a => a.FeedId == feed.Id && a.Url == itemUrl, cancellationToken);
|
||||||
|
|
||||||
if (articleExists)
|
if (articleExists)
|
||||||
{
|
|
||||||
continue;
|
continue;
|
||||||
}
|
|
||||||
|
|
||||||
var content = (item.Content as TextSyndicationContent)?.Text ?? item.Summary.Text;
|
var content = (item.Content as TextSyndicationContent)?.Text ?? item.Summary.Text;
|
||||||
LinkEmbed preview;
|
LinkEmbed preview;
|
||||||
@ -82,7 +108,8 @@ public class WebFeedService(
|
|||||||
{
|
{
|
||||||
var scrapedArticle = await webReaderService.ScrapeArticleAsync(itemUrl, cancellationToken);
|
var scrapedArticle = await webReaderService.ScrapeArticleAsync(itemUrl, cancellationToken);
|
||||||
preview = scrapedArticle.LinkEmbed;
|
preview = scrapedArticle.LinkEmbed;
|
||||||
content = scrapedArticle.Content;
|
if (scrapedArticle.Content is not null)
|
||||||
|
content = scrapedArticle.Content;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
@ -96,11 +123,11 @@ public class WebFeedService(
|
|||||||
Url = itemUrl,
|
Url = itemUrl,
|
||||||
Author = item.Authors.FirstOrDefault()?.Name,
|
Author = item.Authors.FirstOrDefault()?.Name,
|
||||||
Content = content,
|
Content = content,
|
||||||
PublishedAt = item.PublishDate.UtcDateTime,
|
PublishedAt = item.LastUpdatedTime.UtcDateTime,
|
||||||
Preview = preview,
|
Preview = preview,
|
||||||
};
|
};
|
||||||
|
|
||||||
database.Set<WebArticle>().Add(newArticle);
|
database.WebArticles.Add(newArticle);
|
||||||
}
|
}
|
||||||
|
|
||||||
await database.SaveChangesAsync(cancellationToken);
|
await database.SaveChangesAsync(cancellationToken);
|
||||||
|
@ -33,7 +33,11 @@ public class WebReaderService(
|
|||||||
{
|
{
|
||||||
var httpClient = httpClientFactory.CreateClient("WebReader");
|
var httpClient = httpClientFactory.CreateClient("WebReader");
|
||||||
var response = await httpClient.GetAsync(url, cancellationToken);
|
var response = await httpClient.GetAsync(url, cancellationToken);
|
||||||
response.EnsureSuccessStatusCode();
|
if (!response.IsSuccessStatusCode)
|
||||||
|
{
|
||||||
|
logger.LogWarning("Failed to scrap article content for URL: {Url}", url);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
var html = await response.Content.ReadAsStringAsync(cancellationToken);
|
var html = await response.Content.ReadAsStringAsync(cancellationToken);
|
||||||
var doc = new HtmlDocument();
|
var doc = new HtmlDocument();
|
||||||
doc.LoadHtml(html);
|
doc.LoadHtml(html);
|
||||||
@ -74,7 +78,8 @@ public class WebReaderService(
|
|||||||
// Cache miss or bypass, fetch fresh data
|
// Cache miss or bypass, fetch fresh data
|
||||||
logger.LogDebug("Fetching fresh link preview for URL: {Url}", url);
|
logger.LogDebug("Fetching fresh link preview for URL: {Url}", url);
|
||||||
var httpClient = httpClientFactory.CreateClient("WebReader");
|
var httpClient = httpClientFactory.CreateClient("WebReader");
|
||||||
httpClient.MaxResponseContentBufferSize = 10 * 1024 * 1024; // 10MB, prevent scrap some directly accessible files
|
httpClient.MaxResponseContentBufferSize =
|
||||||
|
10 * 1024 * 1024; // 10MB, prevent scrap some directly accessible files
|
||||||
httpClient.Timeout = TimeSpan.FromSeconds(3);
|
httpClient.Timeout = TimeSpan.FromSeconds(3);
|
||||||
// Setting UA to facebook's bot to get the opengraph.
|
// Setting UA to facebook's bot to get the opengraph.
|
||||||
httpClient.DefaultRequestHeaders.Add("User-Agent", "facebookexternalhit/1.1");
|
httpClient.DefaultRequestHeaders.Add("User-Agent", "facebookexternalhit/1.1");
|
||||||
|
4014
DysonNetwork.Sphere/Data/Migrations/20250629084150_AuthSessionWithApp.Designer.cs
generated
Normal file
4014
DysonNetwork.Sphere/Data/Migrations/20250629084150_AuthSessionWithApp.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,49 @@
|
|||||||
|
using System;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace DysonNetwork.Sphere.Data.Migrations
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public partial class AuthSessionWithApp : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.AddColumn<Guid>(
|
||||||
|
name: "app_id",
|
||||||
|
table: "auth_sessions",
|
||||||
|
type: "uuid",
|
||||||
|
nullable: true);
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "ix_auth_sessions_app_id",
|
||||||
|
table: "auth_sessions",
|
||||||
|
column: "app_id");
|
||||||
|
|
||||||
|
migrationBuilder.AddForeignKey(
|
||||||
|
name: "fk_auth_sessions_custom_apps_app_id",
|
||||||
|
table: "auth_sessions",
|
||||||
|
column: "app_id",
|
||||||
|
principalTable: "custom_apps",
|
||||||
|
principalColumn: "id");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropForeignKey(
|
||||||
|
name: "fk_auth_sessions_custom_apps_app_id",
|
||||||
|
table: "auth_sessions");
|
||||||
|
|
||||||
|
migrationBuilder.DropIndex(
|
||||||
|
name: "ix_auth_sessions_app_id",
|
||||||
|
table: "auth_sessions");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "app_id",
|
||||||
|
table: "auth_sessions");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
3993
DysonNetwork.Sphere/Data/Migrations/20250629123136_CustomAppsRefine.Designer.cs
generated
Normal file
3993
DysonNetwork.Sphere/Data/Migrations/20250629123136_CustomAppsRefine.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,182 @@
|
|||||||
|
using DysonNetwork.Sphere.Account;
|
||||||
|
using DysonNetwork.Sphere.Developer;
|
||||||
|
using DysonNetwork.Sphere.Storage;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
using NodaTime;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace DysonNetwork.Sphere.Data.Migrations
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public partial class CustomAppsRefine : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "allow_offline_access",
|
||||||
|
table: "custom_apps");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "allowed_grant_types",
|
||||||
|
table: "custom_apps");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "allowed_scopes",
|
||||||
|
table: "custom_apps");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "client_uri",
|
||||||
|
table: "custom_apps");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "logo_uri",
|
||||||
|
table: "custom_apps");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "post_logout_redirect_uris",
|
||||||
|
table: "custom_apps");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "redirect_uris",
|
||||||
|
table: "custom_apps");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "require_pkce",
|
||||||
|
table: "custom_apps");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "verified_at",
|
||||||
|
table: "custom_apps");
|
||||||
|
|
||||||
|
migrationBuilder.RenameColumn(
|
||||||
|
name: "verified_as",
|
||||||
|
table: "custom_apps",
|
||||||
|
newName: "description");
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<CloudFileReferenceObject>(
|
||||||
|
name: "background",
|
||||||
|
table: "custom_apps",
|
||||||
|
type: "jsonb",
|
||||||
|
nullable: true);
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<CustomAppLinks>(
|
||||||
|
name: "links",
|
||||||
|
table: "custom_apps",
|
||||||
|
type: "jsonb",
|
||||||
|
nullable: true);
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<CustomAppOauthConfig>(
|
||||||
|
name: "oauth_config",
|
||||||
|
table: "custom_apps",
|
||||||
|
type: "jsonb",
|
||||||
|
nullable: true);
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<CloudFileReferenceObject>(
|
||||||
|
name: "picture",
|
||||||
|
table: "custom_apps",
|
||||||
|
type: "jsonb",
|
||||||
|
nullable: true);
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<VerificationMark>(
|
||||||
|
name: "verification",
|
||||||
|
table: "custom_apps",
|
||||||
|
type: "jsonb",
|
||||||
|
nullable: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "background",
|
||||||
|
table: "custom_apps");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "links",
|
||||||
|
table: "custom_apps");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "oauth_config",
|
||||||
|
table: "custom_apps");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "picture",
|
||||||
|
table: "custom_apps");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "verification",
|
||||||
|
table: "custom_apps");
|
||||||
|
|
||||||
|
migrationBuilder.RenameColumn(
|
||||||
|
name: "description",
|
||||||
|
table: "custom_apps",
|
||||||
|
newName: "verified_as");
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<bool>(
|
||||||
|
name: "allow_offline_access",
|
||||||
|
table: "custom_apps",
|
||||||
|
type: "boolean",
|
||||||
|
nullable: false,
|
||||||
|
defaultValue: false);
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<string>(
|
||||||
|
name: "allowed_grant_types",
|
||||||
|
table: "custom_apps",
|
||||||
|
type: "character varying(256)",
|
||||||
|
maxLength: 256,
|
||||||
|
nullable: false,
|
||||||
|
defaultValue: "");
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<string>(
|
||||||
|
name: "allowed_scopes",
|
||||||
|
table: "custom_apps",
|
||||||
|
type: "character varying(256)",
|
||||||
|
maxLength: 256,
|
||||||
|
nullable: true);
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<string>(
|
||||||
|
name: "client_uri",
|
||||||
|
table: "custom_apps",
|
||||||
|
type: "character varying(1024)",
|
||||||
|
maxLength: 1024,
|
||||||
|
nullable: true);
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<string>(
|
||||||
|
name: "logo_uri",
|
||||||
|
table: "custom_apps",
|
||||||
|
type: "character varying(4096)",
|
||||||
|
maxLength: 4096,
|
||||||
|
nullable: true);
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<string>(
|
||||||
|
name: "post_logout_redirect_uris",
|
||||||
|
table: "custom_apps",
|
||||||
|
type: "character varying(4096)",
|
||||||
|
maxLength: 4096,
|
||||||
|
nullable: true);
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<string>(
|
||||||
|
name: "redirect_uris",
|
||||||
|
table: "custom_apps",
|
||||||
|
type: "character varying(4096)",
|
||||||
|
maxLength: 4096,
|
||||||
|
nullable: false,
|
||||||
|
defaultValue: "");
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<bool>(
|
||||||
|
name: "require_pkce",
|
||||||
|
table: "custom_apps",
|
||||||
|
type: "boolean",
|
||||||
|
nullable: false,
|
||||||
|
defaultValue: false);
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<Instant>(
|
||||||
|
name: "verified_at",
|
||||||
|
table: "custom_apps",
|
||||||
|
type: "timestamp with time zone",
|
||||||
|
nullable: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -1,5 +1,8 @@
|
|||||||
using System.ComponentModel.DataAnnotations;
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
using System.ComponentModel.DataAnnotations.Schema;
|
||||||
using System.Text.Json.Serialization;
|
using System.Text.Json.Serialization;
|
||||||
|
using DysonNetwork.Sphere.Account;
|
||||||
|
using DysonNetwork.Sphere.Storage;
|
||||||
using NodaTime;
|
using NodaTime;
|
||||||
|
|
||||||
namespace DysonNetwork.Sphere.Developer;
|
namespace DysonNetwork.Sphere.Developer;
|
||||||
@ -12,17 +15,38 @@ public enum CustomAppStatus
|
|||||||
Suspended
|
Suspended
|
||||||
}
|
}
|
||||||
|
|
||||||
public class CustomApp : ModelBase
|
public class CustomApp : ModelBase, IIdentifiedResource
|
||||||
{
|
{
|
||||||
public Guid Id { get; set; } = Guid.NewGuid();
|
public Guid Id { get; set; } = Guid.NewGuid();
|
||||||
[MaxLength(1024)] public string Slug { get; set; } = null!;
|
[MaxLength(1024)] public string Slug { get; set; } = null!;
|
||||||
[MaxLength(1024)] public string Name { get; set; } = null!;
|
[MaxLength(1024)] public string Name { get; set; } = null!;
|
||||||
|
[MaxLength(4096)] public string? Description { get; set; }
|
||||||
public CustomAppStatus Status { get; set; } = CustomAppStatus.Developing;
|
public CustomAppStatus Status { get; set; } = CustomAppStatus.Developing;
|
||||||
public Instant? VerifiedAt { get; set; }
|
|
||||||
[MaxLength(4096)] public string? VerifiedAs { get; set; }
|
[Column(TypeName = "jsonb")] public CloudFileReferenceObject? Picture { get; set; }
|
||||||
|
[Column(TypeName = "jsonb")] public CloudFileReferenceObject? Background { get; set; }
|
||||||
// OIDC/OAuth specific properties
|
|
||||||
[MaxLength(4096)] public string? LogoUri { get; set; }
|
[Column(TypeName = "jsonb")] public VerificationMark? Verification { get; set; }
|
||||||
|
[Column(TypeName = "jsonb")] public CustomAppOauthConfig? OauthConfig { get; set; }
|
||||||
|
[Column(TypeName = "jsonb")] public CustomAppLinks? Links { get; set; }
|
||||||
|
|
||||||
|
[JsonIgnore] public ICollection<CustomAppSecret> Secrets { get; set; } = new List<CustomAppSecret>();
|
||||||
|
|
||||||
|
public Guid PublisherId { get; set; }
|
||||||
|
public Publisher.Publisher Developer { get; set; } = null!;
|
||||||
|
|
||||||
|
[NotMapped] public string ResourceIdentifier => "custom-app/" + Id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public class CustomAppLinks : ModelBase
|
||||||
|
{
|
||||||
|
[MaxLength(8192)] public string? HomePage { get; set; }
|
||||||
|
[MaxLength(8192)] public string? PrivacyPolicy { get; set; }
|
||||||
|
[MaxLength(8192)] public string? TermsOfService { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class CustomAppOauthConfig : ModelBase
|
||||||
|
{
|
||||||
[MaxLength(1024)] public string? ClientUri { get; set; }
|
[MaxLength(1024)] public string? ClientUri { get; set; }
|
||||||
[MaxLength(4096)] public string[] RedirectUris { get; set; } = [];
|
[MaxLength(4096)] public string[] RedirectUris { get; set; } = [];
|
||||||
[MaxLength(4096)] public string[]? PostLogoutRedirectUris { get; set; }
|
[MaxLength(4096)] public string[]? PostLogoutRedirectUris { get; set; }
|
||||||
@ -30,11 +54,6 @@ public class CustomApp : ModelBase
|
|||||||
[MaxLength(256)] public string[] AllowedGrantTypes { get; set; } = ["authorization_code", "refresh_token"];
|
[MaxLength(256)] public string[] AllowedGrantTypes { get; set; } = ["authorization_code", "refresh_token"];
|
||||||
public bool RequirePkce { get; set; } = true;
|
public bool RequirePkce { get; set; } = true;
|
||||||
public bool AllowOfflineAccess { get; set; } = false;
|
public bool AllowOfflineAccess { get; set; } = false;
|
||||||
|
|
||||||
[JsonIgnore] public ICollection<CustomAppSecret> Secrets { get; set; } = new List<CustomAppSecret>();
|
|
||||||
|
|
||||||
public Guid PublisherId { get; set; }
|
|
||||||
public Publisher.Publisher Developer { get; set; } = null!;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public class CustomAppSecret : ModelBase
|
public class CustomAppSecret : ModelBase
|
||||||
@ -44,7 +63,7 @@ public class CustomAppSecret : ModelBase
|
|||||||
[MaxLength(4096)] public string? Description { get; set; } = null!;
|
[MaxLength(4096)] public string? Description { get; set; } = null!;
|
||||||
public Instant? ExpiredAt { get; set; }
|
public Instant? ExpiredAt { get; set; }
|
||||||
public bool IsOidc { get; set; } = false; // Indicates if this secret is for OIDC/OAuth
|
public bool IsOidc { get; set; } = false; // Indicates if this secret is for OIDC/OAuth
|
||||||
|
|
||||||
public Guid AppId { get; set; }
|
public Guid AppId { get; set; }
|
||||||
public CustomApp App { get; set; } = null!;
|
public CustomApp App { get; set; } = null!;
|
||||||
}
|
}
|
@ -1,63 +1,129 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
using DysonNetwork.Sphere.Account;
|
||||||
using DysonNetwork.Sphere.Publisher;
|
using DysonNetwork.Sphere.Publisher;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
namespace DysonNetwork.Sphere.Developer;
|
namespace DysonNetwork.Sphere.Developer;
|
||||||
|
|
||||||
[ApiController]
|
[ApiController]
|
||||||
[Route("/developers/apps")]
|
[Route("/developers/{pubName}/apps")]
|
||||||
public class CustomAppController(CustomAppService customAppService, PublisherService ps) : ControllerBase
|
public class CustomAppController(CustomAppService customApps, PublisherService ps) : ControllerBase
|
||||||
{
|
{
|
||||||
[HttpGet("")]
|
public record CustomAppRequest(
|
||||||
public async Task<IActionResult> GetApps([FromQuery] Guid publisherId)
|
[MaxLength(1024)] string? Slug,
|
||||||
|
[MaxLength(1024)] string? Name,
|
||||||
|
[MaxLength(4096)] string? Description,
|
||||||
|
string? PictureId,
|
||||||
|
string? BackgroundId,
|
||||||
|
CustomAppStatus? Status,
|
||||||
|
CustomAppLinks? Links,
|
||||||
|
CustomAppOauthConfig? OauthConfig
|
||||||
|
);
|
||||||
|
|
||||||
|
[HttpGet]
|
||||||
|
public async Task<IActionResult> ListApps([FromRoute] string pubName)
|
||||||
{
|
{
|
||||||
var apps = await customAppService.GetAppsByPublisherAsync(publisherId);
|
var publisher = await ps.GetPublisherByName(pubName);
|
||||||
|
if (publisher is null) return NotFound();
|
||||||
|
var apps = await customApps.GetAppsByPublisherAsync(publisher.Id);
|
||||||
return Ok(apps);
|
return Ok(apps);
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpGet("{id:guid}")]
|
[HttpGet("{id:guid}")]
|
||||||
public async Task<IActionResult> GetApp(Guid id)
|
public async Task<IActionResult> GetApp([FromRoute] string pubName, Guid id)
|
||||||
{
|
{
|
||||||
var app = await customAppService.GetAppAsync(id);
|
var publisher = await ps.GetPublisherByName(pubName);
|
||||||
|
if (publisher is null) return NotFound();
|
||||||
|
|
||||||
|
var app = await customApps.GetAppAsync(id, publisherId: publisher.Id);
|
||||||
if (app == null)
|
if (app == null)
|
||||||
{
|
|
||||||
return NotFound();
|
return NotFound();
|
||||||
}
|
|
||||||
return Ok(app);
|
return Ok(app);
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost("")]
|
[HttpPost]
|
||||||
public async Task<IActionResult> CreateApp([FromBody] CreateAppDto dto)
|
[Authorize]
|
||||||
|
public async Task<IActionResult> CreateApp([FromRoute] string pubName, [FromBody] CustomAppRequest request)
|
||||||
{
|
{
|
||||||
var app = await customAppService.CreateAppAsync(dto.PublisherId, dto.Name, dto.Slug);
|
if (HttpContext.Items["CurrentUser"] is not Account.Account currentUser) return Unauthorized();
|
||||||
if (app == null)
|
|
||||||
|
if (string.IsNullOrWhiteSpace(request.Name) || string.IsNullOrWhiteSpace(request.Slug))
|
||||||
|
return BadRequest("Name and slug are required");
|
||||||
|
|
||||||
|
var publisher = await ps.GetPublisherByName(pubName);
|
||||||
|
if (publisher is null) return NotFound();
|
||||||
|
|
||||||
|
if (!await ps.IsMemberWithRole(publisher.Id, currentUser.Id, PublisherMemberRole.Editor))
|
||||||
|
return StatusCode(403, "You must be an editor of the publisher to create a custom app");
|
||||||
|
if (!await ps.HasFeature(publisher.Id, PublisherFeatureFlag.Develop))
|
||||||
|
return StatusCode(403, "Publisher must be a developer to create a custom app");
|
||||||
|
|
||||||
|
try
|
||||||
{
|
{
|
||||||
return BadRequest("Invalid publisher ID or missing developer feature flag");
|
var app = await customApps.CreateAppAsync(publisher, request);
|
||||||
|
return Ok(app);
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException ex)
|
||||||
|
{
|
||||||
|
return BadRequest(ex.Message);
|
||||||
}
|
}
|
||||||
return CreatedAtAction(nameof(GetApp), new { id = app.Id }, app);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpPut("{id:guid}")]
|
[HttpPatch("{id:guid}")]
|
||||||
public async Task<IActionResult> UpdateApp(Guid id, [FromBody] UpdateAppDto dto)
|
[Authorize]
|
||||||
|
public async Task<IActionResult> UpdateApp(
|
||||||
|
[FromRoute] string pubName,
|
||||||
|
[FromRoute] Guid id,
|
||||||
|
[FromBody] CustomAppRequest request
|
||||||
|
)
|
||||||
{
|
{
|
||||||
var app = await customAppService.UpdateAppAsync(id, dto.Name, dto.Slug);
|
if (HttpContext.Items["CurrentUser"] is not Account.Account currentUser) return Unauthorized();
|
||||||
|
|
||||||
|
var publisher = await ps.GetPublisherByName(pubName);
|
||||||
|
if (publisher is null) return NotFound();
|
||||||
|
|
||||||
|
if (!await ps.IsMemberWithRole(publisher.Id, currentUser.Id, PublisherMemberRole.Editor))
|
||||||
|
return StatusCode(403, "You must be an editor of the publisher to update a custom app");
|
||||||
|
|
||||||
|
var app = await customApps.GetAppAsync(id, publisherId: publisher.Id);
|
||||||
if (app == null)
|
if (app == null)
|
||||||
{
|
|
||||||
return NotFound();
|
return NotFound();
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
app = await customApps.UpdateAppAsync(app, request);
|
||||||
|
return Ok(app);
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException ex)
|
||||||
|
{
|
||||||
|
return BadRequest(ex.Message);
|
||||||
}
|
}
|
||||||
return Ok(app);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpDelete("{id:guid}")]
|
[HttpDelete("{id:guid}")]
|
||||||
public async Task<IActionResult> DeleteApp(Guid id)
|
[Authorize]
|
||||||
|
public async Task<IActionResult> DeleteApp(
|
||||||
|
[FromRoute] string pubName,
|
||||||
|
[FromRoute] Guid id
|
||||||
|
)
|
||||||
{
|
{
|
||||||
var result = await customAppService.DeleteAppAsync(id);
|
if (HttpContext.Items["CurrentUser"] is not Account.Account currentUser) return Unauthorized();
|
||||||
if (!result)
|
|
||||||
{
|
var publisher = await ps.GetPublisherByName(pubName);
|
||||||
|
if (publisher is null) return NotFound();
|
||||||
|
|
||||||
|
if (!await ps.IsMemberWithRole(publisher.Id, currentUser.Id, PublisherMemberRole.Editor))
|
||||||
|
return StatusCode(403, "You must be an editor of the publisher to delete a custom app");
|
||||||
|
|
||||||
|
var app = await customApps.GetAppAsync(id, publisherId: publisher.Id);
|
||||||
|
if (app == null)
|
||||||
|
return NotFound();
|
||||||
|
|
||||||
|
var result = await customApps.DeleteAppAsync(id);
|
||||||
|
if (!result)
|
||||||
return NotFound();
|
return NotFound();
|
||||||
}
|
|
||||||
return NoContent();
|
return NoContent();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public record CreateAppDto(Guid PublisherId, string Name, string Slug);
|
|
||||||
public record UpdateAppDto(string Name, string Slug);
|
|
@ -1,29 +1,58 @@
|
|||||||
using DysonNetwork.Sphere.Publisher;
|
using DysonNetwork.Sphere.Publisher;
|
||||||
|
using DysonNetwork.Sphere.Storage;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
namespace DysonNetwork.Sphere.Developer;
|
namespace DysonNetwork.Sphere.Developer;
|
||||||
|
|
||||||
public class CustomAppService(AppDatabase db, PublisherService ps)
|
public class CustomAppService(AppDatabase db, FileReferenceService fileRefService)
|
||||||
{
|
{
|
||||||
public async Task<CustomApp?> CreateAppAsync(Guid publisherId, string name, string slug)
|
public async Task<CustomApp?> CreateAppAsync(
|
||||||
|
Publisher.Publisher pub,
|
||||||
|
CustomAppController.CustomAppRequest request
|
||||||
|
)
|
||||||
{
|
{
|
||||||
var publisher = await db.Publishers.FirstOrDefaultAsync(p => p.Id == publisherId);
|
|
||||||
if (publisher == null)
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!await ps.HasFeature(publisherId, "developer"))
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
var app = new CustomApp
|
var app = new CustomApp
|
||||||
{
|
{
|
||||||
Name = name,
|
Slug = request.Slug!,
|
||||||
Slug = slug,
|
Name = request.Name!,
|
||||||
PublisherId = publisher.Id
|
Description = request.Description,
|
||||||
|
Status = request.Status ?? CustomAppStatus.Developing,
|
||||||
|
Links = request.Links,
|
||||||
|
OauthConfig = request.OauthConfig,
|
||||||
|
PublisherId = pub.Id
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if (request.PictureId is not null)
|
||||||
|
{
|
||||||
|
var picture = await db.Files.Where(f => f.Id == request.PictureId).FirstOrDefaultAsync();
|
||||||
|
if (picture is null)
|
||||||
|
throw new InvalidOperationException("Invalid picture id, unable to find the file on cloud.");
|
||||||
|
|
||||||
|
app.Picture = picture.ToReferenceObject();
|
||||||
|
|
||||||
|
// Create a new reference
|
||||||
|
await fileRefService.CreateReferenceAsync(
|
||||||
|
picture.Id,
|
||||||
|
"custom-apps.picture",
|
||||||
|
app.ResourceIdentifier
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.BackgroundId is not null)
|
||||||
|
{
|
||||||
|
var background = await db.Files.Where(f => f.Id == request.BackgroundId).FirstOrDefaultAsync();
|
||||||
|
if (background is null)
|
||||||
|
throw new InvalidOperationException("Invalid picture id, unable to find the file on cloud.");
|
||||||
|
|
||||||
|
app.Background = background.ToReferenceObject();
|
||||||
|
|
||||||
|
// Create a new reference
|
||||||
|
await fileRefService.CreateReferenceAsync(
|
||||||
|
background.Id,
|
||||||
|
"custom-apps.background",
|
||||||
|
app.ResourceIdentifier
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
db.CustomApps.Add(app);
|
db.CustomApps.Add(app);
|
||||||
await db.SaveChangesAsync();
|
await db.SaveChangesAsync();
|
||||||
@ -31,9 +60,12 @@ public class CustomAppService(AppDatabase db, PublisherService ps)
|
|||||||
return app;
|
return app;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<CustomApp?> GetAppAsync(Guid id)
|
public async Task<CustomApp?> GetAppAsync(Guid id, Guid? publisherId = null)
|
||||||
{
|
{
|
||||||
return await db.CustomApps.FindAsync(id);
|
var query = db.CustomApps.Where(a => a.Id == id).AsQueryable();
|
||||||
|
if (publisherId.HasValue)
|
||||||
|
query = query.Where(a => a.PublisherId == publisherId.Value);
|
||||||
|
return await query.FirstOrDefaultAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<List<CustomApp>> GetAppsByPublisherAsync(Guid publisherId)
|
public async Task<List<CustomApp>> GetAppsByPublisherAsync(Guid publisherId)
|
||||||
@ -41,17 +73,60 @@ public class CustomAppService(AppDatabase db, PublisherService ps)
|
|||||||
return await db.CustomApps.Where(a => a.PublisherId == publisherId).ToListAsync();
|
return await db.CustomApps.Where(a => a.PublisherId == publisherId).ToListAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<CustomApp?> UpdateAppAsync(Guid id, string name, string slug)
|
public async Task<CustomApp?> UpdateAppAsync(CustomApp app, CustomAppController.CustomAppRequest request)
|
||||||
{
|
{
|
||||||
var app = await db.CustomApps.FindAsync(id);
|
if (request.Slug is not null)
|
||||||
if (app == null)
|
app.Slug = request.Slug;
|
||||||
|
if (request.Name is not null)
|
||||||
|
app.Name = request.Name;
|
||||||
|
if (request.Description is not null)
|
||||||
|
app.Description = request.Description;
|
||||||
|
if (request.Status is not null)
|
||||||
|
app.Status = request.Status.Value;
|
||||||
|
if (request.Links is not null)
|
||||||
|
app.Links = request.Links;
|
||||||
|
if (request.OauthConfig is not null)
|
||||||
|
app.OauthConfig = request.OauthConfig;
|
||||||
|
|
||||||
|
if (request.PictureId is not null)
|
||||||
{
|
{
|
||||||
return null;
|
var picture = await db.Files.Where(f => f.Id == request.PictureId).FirstOrDefaultAsync();
|
||||||
|
if (picture is null)
|
||||||
|
throw new InvalidOperationException("Invalid picture id, unable to find the file on cloud.");
|
||||||
|
|
||||||
|
if (app.Picture is not null)
|
||||||
|
await fileRefService.DeleteResourceReferencesAsync(app.ResourceIdentifier, "custom-apps.picture");
|
||||||
|
|
||||||
|
app.Picture = picture.ToReferenceObject();
|
||||||
|
|
||||||
|
// Create a new reference
|
||||||
|
await fileRefService.CreateReferenceAsync(
|
||||||
|
picture.Id,
|
||||||
|
"custom-apps.picture",
|
||||||
|
app.ResourceIdentifier
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.BackgroundId is not null)
|
||||||
|
{
|
||||||
|
var background = await db.Files.Where(f => f.Id == request.BackgroundId).FirstOrDefaultAsync();
|
||||||
|
if (background is null)
|
||||||
|
throw new InvalidOperationException("Invalid picture id, unable to find the file on cloud.");
|
||||||
|
|
||||||
|
if (app.Background is not null)
|
||||||
|
await fileRefService.DeleteResourceReferencesAsync(app.ResourceIdentifier, "custom-apps.background");
|
||||||
|
|
||||||
|
app.Background = background.ToReferenceObject();
|
||||||
|
|
||||||
|
// Create a new reference
|
||||||
|
await fileRefService.CreateReferenceAsync(
|
||||||
|
background.Id,
|
||||||
|
"custom-apps.background",
|
||||||
|
app.ResourceIdentifier
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
app.Name = name;
|
db.Update(app);
|
||||||
app.Slug = slug;
|
|
||||||
|
|
||||||
await db.SaveChangesAsync();
|
await db.SaveChangesAsync();
|
||||||
|
|
||||||
return app;
|
return app;
|
||||||
@ -67,6 +142,8 @@ public class CustomAppService(AppDatabase db, PublisherService ps)
|
|||||||
|
|
||||||
db.CustomApps.Remove(app);
|
db.CustomApps.Remove(app);
|
||||||
await db.SaveChangesAsync();
|
await db.SaveChangesAsync();
|
||||||
|
|
||||||
|
await fileRefService.DeleteResourceReferencesAsync(app.ResourceIdentifier);
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
142
DysonNetwork.Sphere/Developer/DeveloperController.cs
Normal file
142
DysonNetwork.Sphere/Developer/DeveloperController.cs
Normal file
@ -0,0 +1,142 @@
|
|||||||
|
using DysonNetwork.Sphere.Account;
|
||||||
|
using DysonNetwork.Sphere.Permission;
|
||||||
|
using DysonNetwork.Sphere.Publisher;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using NodaTime;
|
||||||
|
|
||||||
|
namespace DysonNetwork.Sphere.Developer;
|
||||||
|
|
||||||
|
[ApiController]
|
||||||
|
[Route("/developers")]
|
||||||
|
public class DeveloperController(
|
||||||
|
AppDatabase db,
|
||||||
|
PublisherService ps,
|
||||||
|
ActionLogService als
|
||||||
|
)
|
||||||
|
: ControllerBase
|
||||||
|
{
|
||||||
|
[HttpGet("{name}")]
|
||||||
|
public async Task<ActionResult<Publisher.Publisher>> GetDeveloper(string name)
|
||||||
|
{
|
||||||
|
var publisher = await db.Publishers
|
||||||
|
.Where(e => e.Name == name)
|
||||||
|
.FirstOrDefaultAsync();
|
||||||
|
if (publisher is null) return NotFound();
|
||||||
|
|
||||||
|
return Ok(publisher);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("{name}/stats")]
|
||||||
|
public async Task<ActionResult<DeveloperStats>> GetDeveloperStats(string name)
|
||||||
|
{
|
||||||
|
var publisher = await db.Publishers
|
||||||
|
.Where(p => p.Name == name)
|
||||||
|
.FirstOrDefaultAsync();
|
||||||
|
if (publisher is null) return NotFound();
|
||||||
|
|
||||||
|
// Check if publisher has developer feature
|
||||||
|
var now = SystemClock.Instance.GetCurrentInstant();
|
||||||
|
var hasDeveloperFeature = await db.PublisherFeatures
|
||||||
|
.Where(f => f.PublisherId == publisher.Id)
|
||||||
|
.Where(f => f.Flag == PublisherFeatureFlag.Develop)
|
||||||
|
.Where(f => f.ExpiredAt == null || f.ExpiredAt > now)
|
||||||
|
.AnyAsync();
|
||||||
|
|
||||||
|
if (!hasDeveloperFeature) return NotFound("Not a developer account");
|
||||||
|
|
||||||
|
// Get custom apps count
|
||||||
|
var customAppsCount = await db.CustomApps
|
||||||
|
.Where(a => a.PublisherId == publisher.Id)
|
||||||
|
.CountAsync();
|
||||||
|
|
||||||
|
var stats = new DeveloperStats
|
||||||
|
{
|
||||||
|
TotalCustomApps = customAppsCount
|
||||||
|
};
|
||||||
|
|
||||||
|
return Ok(stats);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet]
|
||||||
|
[Authorize]
|
||||||
|
public async Task<ActionResult<List<Publisher.Publisher>>> ListJoinedDevelopers()
|
||||||
|
{
|
||||||
|
if (HttpContext.Items["CurrentUser"] is not Account.Account currentUser) return Unauthorized();
|
||||||
|
var userId = currentUser.Id;
|
||||||
|
|
||||||
|
var members = await db.PublisherMembers
|
||||||
|
.Where(m => m.AccountId == userId)
|
||||||
|
.Where(m => m.JoinedAt != null)
|
||||||
|
.Include(e => e.Publisher)
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
// Filter to only include publishers with the developer feature flag
|
||||||
|
var now = SystemClock.Instance.GetCurrentInstant();
|
||||||
|
var publisherIds = members.Select(m => m.Publisher.Id).ToList();
|
||||||
|
var developerPublisherIds = await db.PublisherFeatures
|
||||||
|
.Where(f => publisherIds.Contains(f.PublisherId))
|
||||||
|
.Where(f => f.Flag == PublisherFeatureFlag.Develop)
|
||||||
|
.Where(f => f.ExpiredAt == null || f.ExpiredAt > now)
|
||||||
|
.Select(f => f.PublisherId)
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
return members
|
||||||
|
.Where(m => developerPublisherIds.Contains(m.Publisher.Id))
|
||||||
|
.Select(m => m.Publisher)
|
||||||
|
.ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("{name}/enroll")]
|
||||||
|
[Authorize]
|
||||||
|
[RequiredPermission("global", "developers.create")]
|
||||||
|
public async Task<ActionResult<Publisher.Publisher>> EnrollDeveloperProgram(string name)
|
||||||
|
{
|
||||||
|
if (HttpContext.Items["CurrentUser"] is not Account.Account currentUser) return Unauthorized();
|
||||||
|
var userId = currentUser.Id;
|
||||||
|
|
||||||
|
var publisher = await db.Publishers
|
||||||
|
.Where(p => p.Name == name)
|
||||||
|
.FirstOrDefaultAsync();
|
||||||
|
if (publisher is null) return NotFound();
|
||||||
|
|
||||||
|
// Check if the user is an owner of the publisher
|
||||||
|
var isOwner = await db.PublisherMembers
|
||||||
|
.AnyAsync(m =>
|
||||||
|
m.PublisherId == publisher.Id &&
|
||||||
|
m.AccountId == userId &&
|
||||||
|
m.Role == PublisherMemberRole.Owner &&
|
||||||
|
m.JoinedAt != null);
|
||||||
|
|
||||||
|
if (!isOwner) return StatusCode(403, "You must be the owner of the publisher to join the developer program");
|
||||||
|
|
||||||
|
// Check if already has a developer feature
|
||||||
|
var now = SystemClock.Instance.GetCurrentInstant();
|
||||||
|
var hasDeveloperFeature = await db.PublisherFeatures
|
||||||
|
.AnyAsync(f =>
|
||||||
|
f.PublisherId == publisher.Id &&
|
||||||
|
f.Flag == PublisherFeatureFlag.Develop &&
|
||||||
|
(f.ExpiredAt == null || f.ExpiredAt > now));
|
||||||
|
|
||||||
|
if (hasDeveloperFeature) return BadRequest("Publisher is already in the developer program");
|
||||||
|
|
||||||
|
// Add developer feature flag
|
||||||
|
var feature = new PublisherFeature
|
||||||
|
{
|
||||||
|
PublisherId = publisher.Id,
|
||||||
|
Flag = PublisherFeatureFlag.Develop,
|
||||||
|
ExpiredAt = null
|
||||||
|
};
|
||||||
|
|
||||||
|
db.PublisherFeatures.Add(feature);
|
||||||
|
await db.SaveChangesAsync();
|
||||||
|
|
||||||
|
return Ok(publisher);
|
||||||
|
}
|
||||||
|
|
||||||
|
public class DeveloperStats
|
||||||
|
{
|
||||||
|
public int TotalCustomApps { get; set; }
|
||||||
|
}
|
||||||
|
}
|
@ -6,6 +6,7 @@ using DysonNetwork.Sphere;
|
|||||||
using DysonNetwork.Sphere.Account;
|
using DysonNetwork.Sphere.Account;
|
||||||
using DysonNetwork.Sphere.Chat;
|
using DysonNetwork.Sphere.Chat;
|
||||||
using DysonNetwork.Sphere.Connection.WebReader;
|
using DysonNetwork.Sphere.Connection.WebReader;
|
||||||
|
using DysonNetwork.Sphere.Developer;
|
||||||
using DysonNetwork.Sphere.Storage;
|
using DysonNetwork.Sphere.Storage;
|
||||||
using DysonNetwork.Sphere.Wallet;
|
using DysonNetwork.Sphere.Wallet;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
@ -978,6 +979,10 @@ namespace DysonNetwork.Sphere.Migrations
|
|||||||
.HasColumnType("uuid")
|
.HasColumnType("uuid")
|
||||||
.HasColumnName("account_id");
|
.HasColumnName("account_id");
|
||||||
|
|
||||||
|
b.Property<Guid?>("AppId")
|
||||||
|
.HasColumnType("uuid")
|
||||||
|
.HasColumnName("app_id");
|
||||||
|
|
||||||
b.Property<Guid>("ChallengeId")
|
b.Property<Guid>("ChallengeId")
|
||||||
.HasColumnType("uuid")
|
.HasColumnType("uuid")
|
||||||
.HasColumnName("challenge_id");
|
.HasColumnName("challenge_id");
|
||||||
@ -1013,6 +1018,9 @@ namespace DysonNetwork.Sphere.Migrations
|
|||||||
b.HasIndex("AccountId")
|
b.HasIndex("AccountId")
|
||||||
.HasDatabaseName("ix_auth_sessions_account_id");
|
.HasDatabaseName("ix_auth_sessions_account_id");
|
||||||
|
|
||||||
|
b.HasIndex("AppId")
|
||||||
|
.HasDatabaseName("ix_auth_sessions_app_id");
|
||||||
|
|
||||||
b.HasIndex("ChallengeId")
|
b.HasIndex("ChallengeId")
|
||||||
.HasDatabaseName("ix_auth_sessions_challenge_id");
|
.HasDatabaseName("ix_auth_sessions_challenge_id");
|
||||||
|
|
||||||
@ -1500,25 +1508,9 @@ namespace DysonNetwork.Sphere.Migrations
|
|||||||
.HasColumnType("uuid")
|
.HasColumnType("uuid")
|
||||||
.HasColumnName("id");
|
.HasColumnName("id");
|
||||||
|
|
||||||
b.Property<bool>("AllowOfflineAccess")
|
b.Property<CloudFileReferenceObject>("Background")
|
||||||
.HasColumnType("boolean")
|
.HasColumnType("jsonb")
|
||||||
.HasColumnName("allow_offline_access");
|
.HasColumnName("background");
|
||||||
|
|
||||||
b.Property<string>("AllowedGrantTypes")
|
|
||||||
.IsRequired()
|
|
||||||
.HasMaxLength(256)
|
|
||||||
.HasColumnType("character varying(256)")
|
|
||||||
.HasColumnName("allowed_grant_types");
|
|
||||||
|
|
||||||
b.Property<string>("AllowedScopes")
|
|
||||||
.HasMaxLength(256)
|
|
||||||
.HasColumnType("character varying(256)")
|
|
||||||
.HasColumnName("allowed_scopes");
|
|
||||||
|
|
||||||
b.Property<string>("ClientUri")
|
|
||||||
.HasMaxLength(1024)
|
|
||||||
.HasColumnType("character varying(1024)")
|
|
||||||
.HasColumnName("client_uri");
|
|
||||||
|
|
||||||
b.Property<Instant>("CreatedAt")
|
b.Property<Instant>("CreatedAt")
|
||||||
.HasColumnType("timestamp with time zone")
|
.HasColumnType("timestamp with time zone")
|
||||||
@ -1528,10 +1520,14 @@ namespace DysonNetwork.Sphere.Migrations
|
|||||||
.HasColumnType("timestamp with time zone")
|
.HasColumnType("timestamp with time zone")
|
||||||
.HasColumnName("deleted_at");
|
.HasColumnName("deleted_at");
|
||||||
|
|
||||||
b.Property<string>("LogoUri")
|
b.Property<string>("Description")
|
||||||
.HasMaxLength(4096)
|
.HasMaxLength(4096)
|
||||||
.HasColumnType("character varying(4096)")
|
.HasColumnType("character varying(4096)")
|
||||||
.HasColumnName("logo_uri");
|
.HasColumnName("description");
|
||||||
|
|
||||||
|
b.Property<CustomAppLinks>("Links")
|
||||||
|
.HasColumnType("jsonb")
|
||||||
|
.HasColumnName("links");
|
||||||
|
|
||||||
b.Property<string>("Name")
|
b.Property<string>("Name")
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
@ -1539,25 +1535,18 @@ namespace DysonNetwork.Sphere.Migrations
|
|||||||
.HasColumnType("character varying(1024)")
|
.HasColumnType("character varying(1024)")
|
||||||
.HasColumnName("name");
|
.HasColumnName("name");
|
||||||
|
|
||||||
b.Property<string>("PostLogoutRedirectUris")
|
b.Property<CustomAppOauthConfig>("OauthConfig")
|
||||||
.HasMaxLength(4096)
|
.HasColumnType("jsonb")
|
||||||
.HasColumnType("character varying(4096)")
|
.HasColumnName("oauth_config");
|
||||||
.HasColumnName("post_logout_redirect_uris");
|
|
||||||
|
b.Property<CloudFileReferenceObject>("Picture")
|
||||||
|
.HasColumnType("jsonb")
|
||||||
|
.HasColumnName("picture");
|
||||||
|
|
||||||
b.Property<Guid>("PublisherId")
|
b.Property<Guid>("PublisherId")
|
||||||
.HasColumnType("uuid")
|
.HasColumnType("uuid")
|
||||||
.HasColumnName("publisher_id");
|
.HasColumnName("publisher_id");
|
||||||
|
|
||||||
b.Property<string>("RedirectUris")
|
|
||||||
.IsRequired()
|
|
||||||
.HasMaxLength(4096)
|
|
||||||
.HasColumnType("character varying(4096)")
|
|
||||||
.HasColumnName("redirect_uris");
|
|
||||||
|
|
||||||
b.Property<bool>("RequirePkce")
|
|
||||||
.HasColumnType("boolean")
|
|
||||||
.HasColumnName("require_pkce");
|
|
||||||
|
|
||||||
b.Property<string>("Slug")
|
b.Property<string>("Slug")
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasMaxLength(1024)
|
.HasMaxLength(1024)
|
||||||
@ -1572,14 +1561,9 @@ namespace DysonNetwork.Sphere.Migrations
|
|||||||
.HasColumnType("timestamp with time zone")
|
.HasColumnType("timestamp with time zone")
|
||||||
.HasColumnName("updated_at");
|
.HasColumnName("updated_at");
|
||||||
|
|
||||||
b.Property<string>("VerifiedAs")
|
b.Property<VerificationMark>("Verification")
|
||||||
.HasMaxLength(4096)
|
.HasColumnType("jsonb")
|
||||||
.HasColumnType("character varying(4096)")
|
.HasColumnName("verification");
|
||||||
.HasColumnName("verified_as");
|
|
||||||
|
|
||||||
b.Property<Instant?>("VerifiedAt")
|
|
||||||
.HasColumnType("timestamp with time zone")
|
|
||||||
.HasColumnName("verified_at");
|
|
||||||
|
|
||||||
b.HasKey("Id")
|
b.HasKey("Id")
|
||||||
.HasName("pk_custom_apps");
|
.HasName("pk_custom_apps");
|
||||||
@ -3331,6 +3315,11 @@ namespace DysonNetwork.Sphere.Migrations
|
|||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasConstraintName("fk_auth_sessions_accounts_account_id");
|
.HasConstraintName("fk_auth_sessions_accounts_account_id");
|
||||||
|
|
||||||
|
b.HasOne("DysonNetwork.Sphere.Developer.CustomApp", "App")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("AppId")
|
||||||
|
.HasConstraintName("fk_auth_sessions_custom_apps_app_id");
|
||||||
|
|
||||||
b.HasOne("DysonNetwork.Sphere.Auth.Challenge", "Challenge")
|
b.HasOne("DysonNetwork.Sphere.Auth.Challenge", "Challenge")
|
||||||
.WithMany()
|
.WithMany()
|
||||||
.HasForeignKey("ChallengeId")
|
.HasForeignKey("ChallengeId")
|
||||||
@ -3340,6 +3329,8 @@ namespace DysonNetwork.Sphere.Migrations
|
|||||||
|
|
||||||
b.Navigation("Account");
|
b.Navigation("Account");
|
||||||
|
|
||||||
|
b.Navigation("App");
|
||||||
|
|
||||||
b.Navigation("Challenge");
|
b.Navigation("Challenge");
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -3604,7 +3595,7 @@ namespace DysonNetwork.Sphere.Migrations
|
|||||||
modelBuilder.Entity("DysonNetwork.Sphere.Publisher.PublisherFeature", b =>
|
modelBuilder.Entity("DysonNetwork.Sphere.Publisher.PublisherFeature", b =>
|
||||||
{
|
{
|
||||||
b.HasOne("DysonNetwork.Sphere.Publisher.Publisher", "Publisher")
|
b.HasOne("DysonNetwork.Sphere.Publisher.Publisher", "Publisher")
|
||||||
.WithMany()
|
.WithMany("Features")
|
||||||
.HasForeignKey("PublisherId")
|
.HasForeignKey("PublisherId")
|
||||||
.OnDelete(DeleteBehavior.Cascade)
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
@ -3966,6 +3957,8 @@ namespace DysonNetwork.Sphere.Migrations
|
|||||||
{
|
{
|
||||||
b.Navigation("Collections");
|
b.Navigation("Collections");
|
||||||
|
|
||||||
|
b.Navigation("Features");
|
||||||
|
|
||||||
b.Navigation("Members");
|
b.Navigation("Members");
|
||||||
|
|
||||||
b.Navigation("Posts");
|
b.Navigation("Posts");
|
||||||
|
@ -1,22 +1,21 @@
|
|||||||
using Microsoft.AspNetCore.Authorization;
|
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Microsoft.AspNetCore.Mvc.RazorPages;
|
using Microsoft.AspNetCore.Mvc.RazorPages;
|
||||||
using DysonNetwork.Sphere.Auth.OidcProvider.Services;
|
using DysonNetwork.Sphere.Auth.OidcProvider.Services;
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using System.ComponentModel.DataAnnotations;
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
using DysonNetwork.Sphere.Auth;
|
||||||
|
using DysonNetwork.Sphere.Auth.OidcProvider.Responses;
|
||||||
|
using DysonNetwork.Sphere.Developer;
|
||||||
|
|
||||||
namespace DysonNetwork.Sphere.Pages.Auth;
|
namespace DysonNetwork.Sphere.Pages.Auth;
|
||||||
|
|
||||||
[Authorize]
|
public class AuthorizeModel(OidcProviderService oidcService, IConfiguration configuration) : PageModel
|
||||||
public class AuthorizeModel(OidcProviderService oidcService) : PageModel
|
|
||||||
{
|
{
|
||||||
[BindProperty(SupportsGet = true)]
|
[BindProperty(SupportsGet = true)] public string? ReturnUrl { get; set; }
|
||||||
public string? ReturnUrl { get; set; }
|
|
||||||
|
|
||||||
[BindProperty(SupportsGet = true, Name = "client_id")]
|
[BindProperty(SupportsGet = true, Name = "client_id")]
|
||||||
[Required(ErrorMessage = "The client_id parameter is required")]
|
[Required(ErrorMessage = "The client_id parameter is required")]
|
||||||
public string? ClientIdString { get; set; }
|
public string? ClientIdString { get; set; }
|
||||||
|
|
||||||
public Guid ClientId { get; set; }
|
public Guid ClientId { get; set; }
|
||||||
|
|
||||||
[BindProperty(SupportsGet = true, Name = "response_type")]
|
[BindProperty(SupportsGet = true, Name = "response_type")]
|
||||||
@ -25,22 +24,19 @@ public class AuthorizeModel(OidcProviderService oidcService) : PageModel
|
|||||||
[BindProperty(SupportsGet = true, Name = "redirect_uri")]
|
[BindProperty(SupportsGet = true, Name = "redirect_uri")]
|
||||||
public string? RedirectUri { get; set; }
|
public string? RedirectUri { get; set; }
|
||||||
|
|
||||||
[BindProperty(SupportsGet = true)]
|
[BindProperty(SupportsGet = true)] public string? Scope { get; set; }
|
||||||
public string? Scope { get; set; }
|
|
||||||
|
|
||||||
[BindProperty(SupportsGet = true)]
|
[BindProperty(SupportsGet = true)] public string? State { get; set; }
|
||||||
public string? State { get; set; }
|
|
||||||
|
[BindProperty(SupportsGet = true)] public string? Nonce { get; set; }
|
||||||
|
|
||||||
[BindProperty(SupportsGet = true)]
|
|
||||||
public string? Nonce { get; set; }
|
|
||||||
|
|
||||||
|
|
||||||
[BindProperty(SupportsGet = true, Name = "code_challenge")]
|
[BindProperty(SupportsGet = true, Name = "code_challenge")]
|
||||||
public string? CodeChallenge { get; set; }
|
public string? CodeChallenge { get; set; }
|
||||||
|
|
||||||
[BindProperty(SupportsGet = true, Name = "code_challenge_method")]
|
[BindProperty(SupportsGet = true, Name = "code_challenge_method")]
|
||||||
public string? CodeChallengeMethod { get; set; }
|
public string? CodeChallengeMethod { get; set; }
|
||||||
|
|
||||||
[BindProperty(SupportsGet = true, Name = "response_mode")]
|
[BindProperty(SupportsGet = true, Name = "response_mode")]
|
||||||
public string? ResponseMode { get; set; }
|
public string? ResponseMode { get; set; }
|
||||||
|
|
||||||
@ -51,41 +47,132 @@ public class AuthorizeModel(OidcProviderService oidcService) : PageModel
|
|||||||
|
|
||||||
public async Task<IActionResult> OnGetAsync()
|
public async Task<IActionResult> OnGetAsync()
|
||||||
{
|
{
|
||||||
|
// First check if user is authenticated
|
||||||
|
if (HttpContext.Items["CurrentUser"] is not Sphere.Account.Account currentUser)
|
||||||
|
{
|
||||||
|
var returnUrl = Uri.EscapeDataString($"{Request.Path}{Request.QueryString}");
|
||||||
|
return RedirectToPage("/Auth/Login", new { returnUrl });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate client_id
|
||||||
if (string.IsNullOrEmpty(ClientIdString) || !Guid.TryParse(ClientIdString, out var clientId))
|
if (string.IsNullOrEmpty(ClientIdString) || !Guid.TryParse(ClientIdString, out var clientId))
|
||||||
{
|
{
|
||||||
ModelState.AddModelError("client_id", "Invalid client_id format");
|
ModelState.AddModelError("client_id", "Invalid client_id format");
|
||||||
return BadRequest("Invalid client_id format");
|
return BadRequest("Invalid client_id format");
|
||||||
}
|
}
|
||||||
|
|
||||||
ClientId = clientId;
|
ClientId = clientId;
|
||||||
|
|
||||||
|
// Get client info
|
||||||
var client = await oidcService.FindClientByIdAsync(ClientId);
|
var client = await oidcService.FindClientByIdAsync(ClientId);
|
||||||
if (client == null)
|
if (client == null)
|
||||||
{
|
{
|
||||||
ModelState.AddModelError("client_id", "Client not found");
|
ModelState.AddModelError("client_id", "Client not found");
|
||||||
return NotFound("Client not found");
|
return NotFound("Client not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var config = client.OauthConfig;
|
||||||
|
if (config is null)
|
||||||
|
{
|
||||||
|
ModelState.AddModelError("client_id", "Client was not available for use OAuth / OIDC");
|
||||||
|
return BadRequest("Client was not enabled for OAuth / OIDC");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate redirect URI for non-Developing apps
|
||||||
|
if (client.Status != CustomAppStatus.Developing)
|
||||||
|
{
|
||||||
|
if (!string.IsNullOrEmpty(RedirectUri) && !(config.RedirectUris?.Contains(RedirectUri) ?? false))
|
||||||
|
{
|
||||||
|
return BadRequest(new ErrorResponse
|
||||||
|
{
|
||||||
|
Error = "invalid_request",
|
||||||
|
ErrorDescription = "Invalid redirect_uri"
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check for an existing valid session
|
||||||
|
var existingSession = await oidcService.FindValidSessionAsync(currentUser.Id, clientId);
|
||||||
|
if (existingSession != null)
|
||||||
|
{
|
||||||
|
// Auto-approve since valid session exists
|
||||||
|
return await HandleApproval(currentUser, client, existingSession);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Show authorization page
|
||||||
|
var baseUrl = configuration["BaseUrl"];
|
||||||
AppName = client.Name;
|
AppName = client.Name;
|
||||||
AppLogo = client.LogoUri;
|
AppLogo = client.Picture is not null ? $"{baseUrl}/files/{client.Picture.Id}" : null;
|
||||||
AppUri = client.ClientUri;
|
AppUri = config.ClientUri;
|
||||||
RequestedScopes = (Scope ?? "openid profile").Split(' ').Distinct().ToArray();
|
RequestedScopes = (Scope ?? "openid profile").Split(' ').Distinct().ToArray();
|
||||||
|
|
||||||
return Page();
|
return Page();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async Task<IActionResult> HandleApproval(Sphere.Account.Account currentUser, CustomApp client, Session? existingSession = null)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(RedirectUri))
|
||||||
|
{
|
||||||
|
ModelState.AddModelError("redirect_uri", "No redirect_uri provided");
|
||||||
|
return BadRequest("No redirect_uri provided");
|
||||||
|
}
|
||||||
|
|
||||||
|
string authCode;
|
||||||
|
|
||||||
|
if (existingSession != null)
|
||||||
|
{
|
||||||
|
// Reuse existing session
|
||||||
|
authCode = await oidcService.GenerateAuthorizationCodeForReuseSessionAsync(
|
||||||
|
session: existingSession,
|
||||||
|
clientId: ClientId,
|
||||||
|
redirectUri: RedirectUri,
|
||||||
|
scopes: Scope?.Split(' ', StringSplitOptions.RemoveEmptyEntries) ?? [],
|
||||||
|
codeChallenge: CodeChallenge,
|
||||||
|
codeChallengeMethod: CodeChallengeMethod,
|
||||||
|
nonce: Nonce
|
||||||
|
);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// Create a new session (existing flow)
|
||||||
|
authCode = await oidcService.GenerateAuthorizationCodeAsync(
|
||||||
|
clientId: ClientId,
|
||||||
|
userId: currentUser.Id,
|
||||||
|
redirectUri: RedirectUri,
|
||||||
|
scopes: Scope?.Split(' ', StringSplitOptions.RemoveEmptyEntries) ?? [],
|
||||||
|
codeChallenge: CodeChallenge,
|
||||||
|
codeChallengeMethod: CodeChallengeMethod,
|
||||||
|
nonce: Nonce
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build the redirect URI with the authorization code
|
||||||
|
var redirectUriBuilder = new UriBuilder(RedirectUri);
|
||||||
|
var query = System.Web.HttpUtility.ParseQueryString(redirectUriBuilder.Query);
|
||||||
|
query["code"] = authCode;
|
||||||
|
if (!string.IsNullOrEmpty(State))
|
||||||
|
query["state"] = State;
|
||||||
|
if (!string.IsNullOrEmpty(Scope))
|
||||||
|
query["scope"] = Scope;
|
||||||
|
redirectUriBuilder.Query = query.ToString();
|
||||||
|
|
||||||
|
return Redirect(redirectUriBuilder.ToString());
|
||||||
|
}
|
||||||
|
|
||||||
public async Task<IActionResult> OnPostAsync(bool allow)
|
public async Task<IActionResult> OnPostAsync(bool allow)
|
||||||
{
|
{
|
||||||
// First validate the client ID
|
if (HttpContext.Items["CurrentUser"] is not Sphere.Account.Account currentUser) return Unauthorized();
|
||||||
|
|
||||||
|
// First, validate the client ID
|
||||||
if (string.IsNullOrEmpty(ClientIdString) || !Guid.TryParse(ClientIdString, out var clientId))
|
if (string.IsNullOrEmpty(ClientIdString) || !Guid.TryParse(ClientIdString, out var clientId))
|
||||||
{
|
{
|
||||||
ModelState.AddModelError("client_id", "Invalid client_id format");
|
ModelState.AddModelError("client_id", "Invalid client_id format");
|
||||||
return BadRequest("Invalid client_id format");
|
return BadRequest("Invalid client_id format");
|
||||||
}
|
}
|
||||||
|
|
||||||
ClientId = clientId;
|
ClientId = clientId;
|
||||||
|
|
||||||
// Check if client exists
|
// Check if a client exists
|
||||||
var client = await oidcService.FindClientByIdAsync(ClientId);
|
var client = await oidcService.FindClientByIdAsync(ClientId);
|
||||||
if (client == null)
|
if (client == null)
|
||||||
{
|
{
|
||||||
@ -98,14 +185,14 @@ public class AuthorizeModel(OidcProviderService oidcService) : PageModel
|
|||||||
// User denied the authorization request
|
// User denied the authorization request
|
||||||
if (string.IsNullOrEmpty(RedirectUri))
|
if (string.IsNullOrEmpty(RedirectUri))
|
||||||
return BadRequest("No redirect_uri provided");
|
return BadRequest("No redirect_uri provided");
|
||||||
|
|
||||||
var deniedUriBuilder = new UriBuilder(RedirectUri);
|
var deniedUriBuilder = new UriBuilder(RedirectUri);
|
||||||
var deniedQuery = System.Web.HttpUtility.ParseQueryString(deniedUriBuilder.Query);
|
var deniedQuery = System.Web.HttpUtility.ParseQueryString(deniedUriBuilder.Query);
|
||||||
deniedQuery["error"] = "access_denied";
|
deniedQuery["error"] = "access_denied";
|
||||||
deniedQuery["error_description"] = "The user denied the authorization request";
|
deniedQuery["error_description"] = "The user denied the authorization request";
|
||||||
if (!string.IsNullOrEmpty(State)) deniedQuery["state"] = State;
|
if (!string.IsNullOrEmpty(State)) deniedQuery["state"] = State;
|
||||||
deniedUriBuilder.Query = deniedQuery.ToString();
|
deniedUriBuilder.Query = deniedQuery.ToString();
|
||||||
|
|
||||||
return Redirect(deniedUriBuilder.ToString());
|
return Redirect(deniedUriBuilder.ToString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -119,7 +206,7 @@ public class AuthorizeModel(OidcProviderService oidcService) : PageModel
|
|||||||
// Generate authorization code
|
// Generate authorization code
|
||||||
var authCode = await oidcService.GenerateAuthorizationCodeAsync(
|
var authCode = await oidcService.GenerateAuthorizationCodeAsync(
|
||||||
clientId: ClientId,
|
clientId: ClientId,
|
||||||
userId: User.Identity?.Name ?? string.Empty,
|
userId: currentUser.Id,
|
||||||
redirectUri: RedirectUri,
|
redirectUri: RedirectUri,
|
||||||
scopes: Scope?.Split(' ', StringSplitOptions.RemoveEmptyEntries) ?? Array.Empty<string>(),
|
scopes: Scope?.Split(' ', StringSplitOptions.RemoveEmptyEntries) ?? Array.Empty<string>(),
|
||||||
codeChallenge: CodeChallenge,
|
codeChallenge: CodeChallenge,
|
||||||
@ -129,20 +216,18 @@ public class AuthorizeModel(OidcProviderService oidcService) : PageModel
|
|||||||
// Build the redirect URI with the authorization code
|
// Build the redirect URI with the authorization code
|
||||||
var redirectUri = new UriBuilder(RedirectUri);
|
var redirectUri = new UriBuilder(RedirectUri);
|
||||||
var query = System.Web.HttpUtility.ParseQueryString(redirectUri.Query);
|
var query = System.Web.HttpUtility.ParseQueryString(redirectUri.Query);
|
||||||
|
|
||||||
// Add the authorization code
|
// Add the authorization code
|
||||||
query["code"] = authCode;
|
query["code"] = authCode;
|
||||||
|
|
||||||
// Add state if provided (for CSRF protection)
|
// Add state if provided (for CSRF protection)
|
||||||
if (!string.IsNullOrEmpty(State))
|
if (!string.IsNullOrEmpty(State))
|
||||||
{
|
|
||||||
query["state"] = State;
|
query["state"] = State;
|
||||||
}
|
|
||||||
|
|
||||||
// Set the query string
|
// Set the query string
|
||||||
redirectUri.Query = query.ToString();
|
redirectUri.Query = query.ToString();
|
||||||
|
|
||||||
// Redirect back to the client with the authorization code
|
// Redirect back to the client with the authorization code
|
||||||
return Redirect(redirectUri.ToString());
|
return Redirect(redirectUri.ToString());
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -26,7 +26,7 @@
|
|||||||
{
|
{
|
||||||
<div class="mb-4">
|
<div class="mb-4">
|
||||||
<form method="post" asp-page-handler="SelectFactor" class="w-full" id="factor-@factor.Id">
|
<form method="post" asp-page-handler="SelectFactor" class="w-full" id="factor-@factor.Id">
|
||||||
<input type="hidden" name="factorId" value="@factor.Id"/>
|
<input type="hidden" name="SelectedFactorId" value="@factor.Id"/>
|
||||||
|
|
||||||
@if (factor.Type == AccountAuthFactorType.EmailCode)
|
@if (factor.Type == AccountAuthFactorType.EmailCode)
|
||||||
{
|
{
|
||||||
|
@ -39,7 +39,7 @@ public class SelectFactorModel(
|
|||||||
var factor = await db.AccountAuthFactors.FindAsync(SelectedFactorId);
|
var factor = await db.AccountAuthFactors.FindAsync(SelectedFactorId);
|
||||||
if (factor?.EnabledAt == null || factor.Trustworthy <= 0)
|
if (factor?.EnabledAt == null || factor.Trustworthy <= 0)
|
||||||
return BadRequest("Invalid authentication method.");
|
return BadRequest("Invalid authentication method.");
|
||||||
|
|
||||||
// Store return URL in TempData to pass to the next step
|
// Store return URL in TempData to pass to the next step
|
||||||
if (!string.IsNullOrEmpty(ReturnUrl))
|
if (!string.IsNullOrEmpty(ReturnUrl))
|
||||||
{
|
{
|
||||||
@ -50,10 +50,14 @@ public class SelectFactorModel(
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
// For OTP factors that require code delivery
|
// For OTP factors that require code delivery
|
||||||
if (factor.Type == AccountAuthFactorType.EmailCode
|
if (
|
||||||
&& string.IsNullOrWhiteSpace(Hint))
|
factor.Type == AccountAuthFactorType.EmailCode
|
||||||
|
&& string.IsNullOrWhiteSpace(Hint)
|
||||||
|
)
|
||||||
{
|
{
|
||||||
ModelState.AddModelError(string.Empty, $"Please provide a {factor.Type.ToString().ToLower().Replace("code", "")} to send the code to.");
|
ModelState.AddModelError(string.Empty,
|
||||||
|
$"Please provide a {factor.Type.ToString().ToLower().Replace("code", "")} to send the code to."
|
||||||
|
);
|
||||||
await LoadChallengeAndFactors();
|
await LoadChallengeAndFactors();
|
||||||
return Page();
|
return Page();
|
||||||
}
|
}
|
||||||
@ -62,31 +66,30 @@ public class SelectFactorModel(
|
|||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
ModelState.AddModelError(string.Empty, $"An error occurred while sending the verification code: {ex.Message}");
|
ModelState.AddModelError(string.Empty,
|
||||||
|
$"An error occurred while sending the verification code: {ex.Message}");
|
||||||
await LoadChallengeAndFactors();
|
await LoadChallengeAndFactors();
|
||||||
return Page();
|
return Page();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Redirect to verify page with return URL if available
|
// Redirect to verify page with return URL if available
|
||||||
if (!string.IsNullOrEmpty(ReturnUrl))
|
return !string.IsNullOrEmpty(ReturnUrl)
|
||||||
{
|
? RedirectToPage("VerifyFactor", new { id = Id, factorId = factor.Id, returnUrl = ReturnUrl })
|
||||||
return RedirectToPage("VerifyFactor", new { id = Id, factorId = factor.Id, returnUrl = ReturnUrl });
|
: RedirectToPage("VerifyFactor", new { id = Id, factorId = factor.Id });
|
||||||
}
|
|
||||||
return RedirectToPage("VerifyFactor", new { id = Id, factorId = factor.Id });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task LoadChallengeAndFactors()
|
private async Task LoadChallengeAndFactors()
|
||||||
{
|
{
|
||||||
AuthChallenge = await db.AuthChallenges
|
AuthChallenge = await db.AuthChallenges
|
||||||
.Include(e => e.Account)
|
.Include(e => e.Account)
|
||||||
.ThenInclude(e => e.AuthFactors)
|
|
||||||
.FirstOrDefaultAsync(e => e.Id == Id);
|
.FirstOrDefaultAsync(e => e.Id == Id);
|
||||||
|
|
||||||
if (AuthChallenge != null)
|
if (AuthChallenge != null)
|
||||||
{
|
{
|
||||||
AuthFactors = AuthChallenge.Account.AuthFactors
|
AuthFactors = await db.AccountAuthFactors
|
||||||
.Where(e => e is { EnabledAt: not null, Trustworthy: >= 1 })
|
.Where(e => e.AccountId == AuthChallenge.Account.Id)
|
||||||
.ToList();
|
.Where(e => e.EnabledAt != null && e.Trustworthy >= 1)
|
||||||
|
.ToListAsync();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -8,54 +8,35 @@ using NodaTime;
|
|||||||
|
|
||||||
namespace DysonNetwork.Sphere.Pages.Auth
|
namespace DysonNetwork.Sphere.Pages.Auth
|
||||||
{
|
{
|
||||||
public class VerifyFactorModel : PageModel
|
public class VerifyFactorModel(
|
||||||
|
AppDatabase db,
|
||||||
|
AccountService accounts,
|
||||||
|
AuthService auth,
|
||||||
|
ActionLogService als,
|
||||||
|
IConfiguration configuration,
|
||||||
|
IHttpClientFactory httpClientFactory
|
||||||
|
)
|
||||||
|
: PageModel
|
||||||
{
|
{
|
||||||
private readonly AppDatabase _db;
|
[BindProperty(SupportsGet = true)] public Guid Id { get; set; }
|
||||||
private readonly AccountService _accounts;
|
|
||||||
private readonly AuthService _auth;
|
|
||||||
private readonly ActionLogService _als;
|
|
||||||
private readonly IConfiguration _configuration;
|
|
||||||
private readonly IHttpClientFactory _httpClientFactory;
|
|
||||||
|
|
||||||
[BindProperty(SupportsGet = true)]
|
[BindProperty(SupportsGet = true)] public Guid FactorId { get; set; }
|
||||||
public Guid Id { get; set; }
|
|
||||||
|
|
||||||
[BindProperty(SupportsGet = true)]
|
[BindProperty(SupportsGet = true)] public string? ReturnUrl { get; set; }
|
||||||
public Guid FactorId { get; set; }
|
|
||||||
|
|
||||||
[BindProperty(SupportsGet = true)]
|
|
||||||
public string? ReturnUrl { get; set; }
|
|
||||||
|
|
||||||
[BindProperty, Required]
|
[BindProperty, Required] public string Code { get; set; } = string.Empty;
|
||||||
public string Code { get; set; } = string.Empty;
|
|
||||||
|
|
||||||
public Challenge? AuthChallenge { get; set; }
|
public Challenge? AuthChallenge { get; set; }
|
||||||
public AccountAuthFactor? Factor { get; set; }
|
public AccountAuthFactor? Factor { get; set; }
|
||||||
public AccountAuthFactorType FactorType => Factor?.Type ?? AccountAuthFactorType.EmailCode;
|
public AccountAuthFactorType FactorType => Factor?.Type ?? AccountAuthFactorType.EmailCode;
|
||||||
|
|
||||||
public VerifyFactorModel(
|
|
||||||
AppDatabase db,
|
|
||||||
AccountService accounts,
|
|
||||||
AuthService auth,
|
|
||||||
ActionLogService als,
|
|
||||||
IConfiguration configuration,
|
|
||||||
IHttpClientFactory httpClientFactory)
|
|
||||||
{
|
|
||||||
_db = db;
|
|
||||||
_accounts = accounts;
|
|
||||||
_auth = auth;
|
|
||||||
_als = als;
|
|
||||||
_configuration = configuration;
|
|
||||||
_httpClientFactory = httpClientFactory;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<IActionResult> OnGetAsync()
|
public async Task<IActionResult> OnGetAsync()
|
||||||
{
|
{
|
||||||
await LoadChallengeAndFactor();
|
await LoadChallengeAndFactor();
|
||||||
if (AuthChallenge == null) return NotFound("Challenge not found or expired.");
|
if (AuthChallenge == null) return NotFound("Challenge not found or expired.");
|
||||||
if (Factor == null) return NotFound("Authentication method not found.");
|
if (Factor == null) return NotFound("Authentication method not found.");
|
||||||
if (AuthChallenge.StepRemain == 0) return await ExchangeTokenAndRedirect();
|
if (AuthChallenge.StepRemain == 0) return await ExchangeTokenAndRedirect();
|
||||||
|
|
||||||
return Page();
|
return Page();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -73,25 +54,25 @@ namespace DysonNetwork.Sphere.Pages.Auth
|
|||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (await _accounts.VerifyFactorCode(Factor, Code))
|
if (await accounts.VerifyFactorCode(Factor, Code))
|
||||||
{
|
{
|
||||||
AuthChallenge.StepRemain -= Factor.Trustworthy;
|
AuthChallenge.StepRemain -= Factor.Trustworthy;
|
||||||
AuthChallenge.StepRemain = Math.Max(0, AuthChallenge.StepRemain);
|
AuthChallenge.StepRemain = Math.Max(0, AuthChallenge.StepRemain);
|
||||||
AuthChallenge.BlacklistFactors.Add(Factor.Id);
|
AuthChallenge.BlacklistFactors.Add(Factor.Id);
|
||||||
_db.Update(AuthChallenge);
|
db.Update(AuthChallenge);
|
||||||
|
|
||||||
_als.CreateActionLogFromRequest(ActionLogType.ChallengeSuccess,
|
als.CreateActionLogFromRequest(ActionLogType.ChallengeSuccess,
|
||||||
new Dictionary<string, object>
|
new Dictionary<string, object>
|
||||||
{
|
{
|
||||||
{ "challenge_id", AuthChallenge.Id },
|
{ "challenge_id", AuthChallenge.Id },
|
||||||
{ "factor_id", Factor?.Id.ToString() ?? string.Empty }
|
{ "factor_id", Factor?.Id.ToString() ?? string.Empty }
|
||||||
}, Request, AuthChallenge.Account);
|
}, Request, AuthChallenge.Account);
|
||||||
|
|
||||||
await _db.SaveChangesAsync();
|
await db.SaveChangesAsync();
|
||||||
|
|
||||||
if (AuthChallenge.StepRemain == 0)
|
if (AuthChallenge.StepRemain == 0)
|
||||||
{
|
{
|
||||||
_als.CreateActionLogFromRequest(ActionLogType.NewLogin,
|
als.CreateActionLogFromRequest(ActionLogType.NewLogin,
|
||||||
new Dictionary<string, object>
|
new Dictionary<string, object>
|
||||||
{
|
{
|
||||||
{ "challenge_id", AuthChallenge.Id },
|
{ "challenge_id", AuthChallenge.Id },
|
||||||
@ -104,7 +85,7 @@ namespace DysonNetwork.Sphere.Pages.Auth
|
|||||||
else
|
else
|
||||||
{
|
{
|
||||||
// If more steps are needed, redirect back to select factor
|
// If more steps are needed, redirect back to select factor
|
||||||
return RedirectToPage("SelectFactor", new { id = Id });
|
return RedirectToPage("SelectFactor", new { id = Id, returnUrl = ReturnUrl });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
@ -117,10 +98,10 @@ namespace DysonNetwork.Sphere.Pages.Auth
|
|||||||
if (AuthChallenge != null)
|
if (AuthChallenge != null)
|
||||||
{
|
{
|
||||||
AuthChallenge.FailedAttempts++;
|
AuthChallenge.FailedAttempts++;
|
||||||
_db.Update(AuthChallenge);
|
db.Update(AuthChallenge);
|
||||||
await _db.SaveChangesAsync();
|
await db.SaveChangesAsync();
|
||||||
|
|
||||||
_als.CreateActionLogFromRequest(ActionLogType.ChallengeFailure,
|
als.CreateActionLogFromRequest(ActionLogType.ChallengeFailure,
|
||||||
new Dictionary<string, object>
|
new Dictionary<string, object>
|
||||||
{
|
{
|
||||||
{ "challenge_id", AuthChallenge.Id },
|
{ "challenge_id", AuthChallenge.Id },
|
||||||
@ -136,30 +117,30 @@ namespace DysonNetwork.Sphere.Pages.Auth
|
|||||||
|
|
||||||
private async Task LoadChallengeAndFactor()
|
private async Task LoadChallengeAndFactor()
|
||||||
{
|
{
|
||||||
AuthChallenge = await _db.AuthChallenges
|
AuthChallenge = await db.AuthChallenges
|
||||||
.Include(e => e.Account)
|
.Include(e => e.Account)
|
||||||
.FirstOrDefaultAsync(e => e.Id == Id);
|
.FirstOrDefaultAsync(e => e.Id == Id);
|
||||||
|
|
||||||
if (AuthChallenge?.Account != null)
|
if (AuthChallenge?.Account != null)
|
||||||
{
|
{
|
||||||
Factor = await _db.AccountAuthFactors
|
Factor = await db.AccountAuthFactors
|
||||||
.FirstOrDefaultAsync(e => e.Id == FactorId &&
|
.FirstOrDefaultAsync(e => e.Id == FactorId &&
|
||||||
e.AccountId == AuthChallenge.Account.Id &&
|
e.AccountId == AuthChallenge.Account.Id &&
|
||||||
e.EnabledAt != null &&
|
e.EnabledAt != null &&
|
||||||
e.Trustworthy > 0);
|
e.Trustworthy > 0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<IActionResult> ExchangeTokenAndRedirect()
|
private async Task<IActionResult> ExchangeTokenAndRedirect()
|
||||||
{
|
{
|
||||||
var challenge = await _db.AuthChallenges
|
var challenge = await db.AuthChallenges
|
||||||
.Include(e => e.Account)
|
.Include(e => e.Account)
|
||||||
.FirstOrDefaultAsync(e => e.Id == Id);
|
.FirstOrDefaultAsync(e => e.Id == Id);
|
||||||
|
|
||||||
if (challenge == null) return BadRequest("Authorization code not found or expired.");
|
if (challenge == null) return BadRequest("Authorization code not found or expired.");
|
||||||
if (challenge.StepRemain != 0) return BadRequest("Challenge not yet completed.");
|
if (challenge.StepRemain != 0) return BadRequest("Challenge not yet completed.");
|
||||||
|
|
||||||
var session = await _db.AuthSessions
|
var session = await db.AuthSessions
|
||||||
.FirstOrDefaultAsync(e => e.ChallengeId == challenge.Id);
|
.FirstOrDefaultAsync(e => e.ChallengeId == challenge.Id);
|
||||||
|
|
||||||
if (session == null)
|
if (session == null)
|
||||||
@ -171,15 +152,15 @@ namespace DysonNetwork.Sphere.Pages.Auth
|
|||||||
Account = challenge.Account,
|
Account = challenge.Account,
|
||||||
Challenge = challenge,
|
Challenge = challenge,
|
||||||
};
|
};
|
||||||
_db.AuthSessions.Add(session);
|
db.AuthSessions.Add(session);
|
||||||
await _db.SaveChangesAsync();
|
await db.SaveChangesAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
var token = _auth.CreateToken(session);
|
var token = auth.CreateToken(session);
|
||||||
Response.Cookies.Append("access_token", token, new CookieOptions
|
Response.Cookies.Append(AuthConstants.CookieTokenName, token, new CookieOptions
|
||||||
{
|
{
|
||||||
HttpOnly = true,
|
HttpOnly = true,
|
||||||
Secure = !_configuration.GetValue<bool>("Debug"),
|
Secure = !configuration.GetValue<bool>("Debug"),
|
||||||
SameSite = SameSiteMode.Strict,
|
SameSite = SameSiteMode.Strict,
|
||||||
Path = "/"
|
Path = "/"
|
||||||
});
|
});
|
||||||
@ -189,9 +170,10 @@ namespace DysonNetwork.Sphere.Pages.Auth
|
|||||||
{
|
{
|
||||||
return Redirect(ReturnUrl);
|
return Redirect(ReturnUrl);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check TempData for return URL (in case it was passed through multiple steps)
|
// Check TempData for return URL (in case it was passed through multiple steps)
|
||||||
if (TempData.TryGetValue("ReturnUrl", out var tempReturnUrl) && tempReturnUrl is string returnUrl && !string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
|
if (TempData.TryGetValue("ReturnUrl", out var tempReturnUrl) && tempReturnUrl is string returnUrl &&
|
||||||
|
!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
|
||||||
{
|
{
|
||||||
return Redirect(returnUrl);
|
return Redirect(returnUrl);
|
||||||
}
|
}
|
||||||
@ -199,4 +181,4 @@ namespace DysonNetwork.Sphere.Pages.Auth
|
|||||||
return RedirectToPage("/Index");
|
return RedirectToPage("/Index");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -17,7 +17,7 @@
|
|||||||
<div class="flex items-center ml-auto">
|
<div class="flex items-center ml-auto">
|
||||||
@if (Context.Request.Cookies.TryGetValue(AuthConstants.CookieTokenName, out _))
|
@if (Context.Request.Cookies.TryGetValue(AuthConstants.CookieTokenName, out _))
|
||||||
{
|
{
|
||||||
<a href="/Account/Profile" class="text-gray-900 dark:text-white hover:text-gray-700 dark:hover:text-gray-300 px-3 py-2 rounded-md text-sm font-medium">Profile</a>
|
<a href="/web/account/profile" class="text-gray-900 dark:text-white hover:text-gray-700 dark:hover:text-gray-300 px-3 py-2 rounded-md text-sm font-medium">Profile</a>
|
||||||
<form method="post" asp-page="/Account/Profile" asp-page-handler="Logout" class="inline">
|
<form method="post" asp-page="/Account/Profile" asp-page-handler="Logout" class="inline">
|
||||||
<button type="submit" class="text-gray-900 dark:text-white hover:text-gray-700 dark:hover:text-gray-300 px-3 py-2 rounded-md text-sm font-medium">Logout</button>
|
<button type="submit" class="text-gray-900 dark:text-white hover:text-gray-700 dark:hover:text-gray-300 px-3 py-2 rounded-md text-sm font-medium">Logout</button>
|
||||||
</form>
|
</form>
|
||||||
@ -31,20 +31,11 @@
|
|||||||
</nav>
|
</nav>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
@* The header 64px + The footer 56px = 118px *@
|
@* The header 64px *@
|
||||||
<main class="h-full">
|
<main class="h-full">
|
||||||
@RenderBody()
|
@RenderBody()
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
<footer class="bg-white dark:bg-gray-800 fixed bottom-0 left-0 right-0 shadow-[0_-1px_3px_0_rgba(0,0,0,0.1)]">
|
|
||||||
<div class="container-default" style="padding: 1rem 0;">
|
|
||||||
<p class="text-center text-gray-500 dark:text-gray-400">
|
|
||||||
© @DateTime.Now.Year Solsynth LLC. All
|
|
||||||
rights reserved.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</footer>
|
|
||||||
|
|
||||||
@await RenderSectionAsync("Scripts", required: false)
|
@await RenderSectionAsync("Scripts", required: false)
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Authorization;
|
|||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using NodaTime;
|
using NodaTime;
|
||||||
|
using NpgsqlTypes;
|
||||||
|
|
||||||
namespace DysonNetwork.Sphere.Post;
|
namespace DysonNetwork.Sphere.Post;
|
||||||
|
|
||||||
@ -18,14 +19,16 @@ public class PostController(
|
|||||||
PostService ps,
|
PostService ps,
|
||||||
PublisherService pub,
|
PublisherService pub,
|
||||||
RelationshipService rels,
|
RelationshipService rels,
|
||||||
IServiceScopeFactory factory,
|
|
||||||
ActionLogService als
|
ActionLogService als
|
||||||
)
|
)
|
||||||
: ControllerBase
|
: ControllerBase
|
||||||
{
|
{
|
||||||
[HttpGet]
|
[HttpGet]
|
||||||
public async Task<ActionResult<List<Post>>> ListPosts([FromQuery] int offset = 0, [FromQuery] int take = 20,
|
public async Task<ActionResult<List<Post>>> ListPosts(
|
||||||
[FromQuery(Name = "pub")] string? pubName = null)
|
[FromQuery] int offset = 0,
|
||||||
|
[FromQuery] int take = 20,
|
||||||
|
[FromQuery(Name = "pub")] string? pubName = null
|
||||||
|
)
|
||||||
{
|
{
|
||||||
HttpContext.Items.TryGetValue("CurrentUser", out var currentUserValue);
|
HttpContext.Items.TryGetValue("CurrentUser", out var currentUserValue);
|
||||||
var currentUser = currentUserValue as Account.Account;
|
var currentUser = currentUserValue as Account.Account;
|
||||||
@ -83,6 +86,50 @@ public class PostController(
|
|||||||
return Ok(post);
|
return Ok(post);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[HttpGet("search")]
|
||||||
|
public async Task<ActionResult<List<Post>>> SearchPosts(
|
||||||
|
[FromQuery] string query,
|
||||||
|
[FromQuery] int offset = 0,
|
||||||
|
[FromQuery] int take = 20,
|
||||||
|
[FromQuery] bool useVector = true
|
||||||
|
)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(query))
|
||||||
|
return BadRequest("Search query cannot be empty");
|
||||||
|
|
||||||
|
HttpContext.Items.TryGetValue("CurrentUser", out var currentUserValue);
|
||||||
|
var currentUser = currentUserValue as Account.Account;
|
||||||
|
var userFriends = currentUser is null ? [] : await rels.ListAccountFriends(currentUser);
|
||||||
|
var userPublishers = currentUser is null ? [] : await pub.GetUserPublishers(currentUser.Id);
|
||||||
|
|
||||||
|
var queryable = db.Posts
|
||||||
|
.FilterWithVisibility(currentUser, userFriends, userPublishers, isListing: true)
|
||||||
|
.AsQueryable();
|
||||||
|
if (useVector)
|
||||||
|
queryable = queryable.Where(p => p.SearchVector.Matches(EF.Functions.ToTsQuery(query)));
|
||||||
|
else
|
||||||
|
queryable = queryable.Where(p => EF.Functions.ILike(p.Title, $"%{query}%") ||
|
||||||
|
EF.Functions.ILike(p.Description, $"%{query}%") ||
|
||||||
|
EF.Functions.ILike(p.Content, $"%{query}%")
|
||||||
|
);
|
||||||
|
|
||||||
|
var totalCount = await queryable.CountAsync();
|
||||||
|
|
||||||
|
var posts = await queryable
|
||||||
|
.Include(e => e.RepliedPost)
|
||||||
|
.Include(e => e.ForwardedPost)
|
||||||
|
.Include(e => e.Categories)
|
||||||
|
.Include(e => e.Tags)
|
||||||
|
.OrderByDescending(e => e.PublishedAt ?? e.CreatedAt)
|
||||||
|
.Skip(offset)
|
||||||
|
.Take(take)
|
||||||
|
.ToListAsync();
|
||||||
|
posts = await ps.LoadPostInfo(posts, currentUser, true);
|
||||||
|
|
||||||
|
Response.Headers["X-Total"] = totalCount.ToString();
|
||||||
|
return Ok(posts);
|
||||||
|
}
|
||||||
|
|
||||||
[HttpGet("{id:guid}/replies")]
|
[HttpGet("{id:guid}/replies")]
|
||||||
public async Task<ActionResult<List<Post>>> ListReplies(Guid id, [FromQuery] int offset = 0,
|
public async Task<ActionResult<List<Post>>> ListReplies(Guid id, [FromQuery] int offset = 0,
|
||||||
[FromQuery] int take = 20)
|
[FromQuery] int take = 20)
|
||||||
|
@ -35,6 +35,7 @@ public class Publisher : ModelBase, IIdentifiedResource
|
|||||||
[JsonIgnore] public ICollection<Post.Post> Posts { get; set; } = new List<Post.Post>();
|
[JsonIgnore] public ICollection<Post.Post> Posts { get; set; } = new List<Post.Post>();
|
||||||
[JsonIgnore] public ICollection<PostCollection> Collections { get; set; } = new List<PostCollection>();
|
[JsonIgnore] public ICollection<PostCollection> Collections { get; set; } = new List<PostCollection>();
|
||||||
[JsonIgnore] public ICollection<PublisherMember> Members { get; set; } = new List<PublisherMember>();
|
[JsonIgnore] public ICollection<PublisherMember> Members { get; set; } = new List<PublisherMember>();
|
||||||
|
[JsonIgnore] public ICollection<PublisherFeature> Features { get; set; } = new List<PublisherFeature>();
|
||||||
|
|
||||||
[JsonIgnore]
|
[JsonIgnore]
|
||||||
public ICollection<PublisherSubscription> Subscriptions { get; set; } = new List<PublisherSubscription>();
|
public ICollection<PublisherSubscription> Subscriptions { get; set; } = new List<PublisherSubscription>();
|
||||||
@ -98,6 +99,6 @@ public class PublisherFeature : ModelBase
|
|||||||
|
|
||||||
public abstract class PublisherFeatureFlag
|
public abstract class PublisherFeatureFlag
|
||||||
{
|
{
|
||||||
public static List<string> AllFlags => [Developer];
|
public static List<string> AllFlags => [Develop];
|
||||||
public static string Developer = "develop";
|
public static string Develop = "develop";
|
||||||
}
|
}
|
@ -8,6 +8,13 @@ namespace DysonNetwork.Sphere.Publisher;
|
|||||||
|
|
||||||
public class PublisherService(AppDatabase db, FileReferenceService fileRefService, ICacheService cache)
|
public class PublisherService(AppDatabase db, FileReferenceService fileRefService, ICacheService cache)
|
||||||
{
|
{
|
||||||
|
public async Task<Publisher?> GetPublisherByName(string name)
|
||||||
|
{
|
||||||
|
return await db.Publishers
|
||||||
|
.Where(e => e.Name == name)
|
||||||
|
.FirstOrDefaultAsync();
|
||||||
|
}
|
||||||
|
|
||||||
private const string UserPublishersCacheKey = "accounts:{0}:publishers";
|
private const string UserPublishersCacheKey = "accounts:{0}:publishers";
|
||||||
|
|
||||||
public async Task<List<Publisher>> GetUserPublishers(Guid userId)
|
public async Task<List<Publisher>> GetUserPublishers(Guid userId)
|
||||||
@ -336,7 +343,7 @@ public class PublisherService(AppDatabase db, FileReferenceService fileRefServic
|
|||||||
f.PublisherId == publisherId && f.Flag == flag &&
|
f.PublisherId == publisherId && f.Flag == flag &&
|
||||||
(f.ExpiredAt == null || f.ExpiredAt > now)
|
(f.ExpiredAt == null || f.ExpiredAt > now)
|
||||||
);
|
);
|
||||||
if (featureFlag is not null) isEnabled = true;
|
isEnabled = featureFlag is not null;
|
||||||
|
|
||||||
await cache.SetAsync(cacheKey, isEnabled!.Value, TimeSpan.FromMinutes(5));
|
await cache.SetAsync(cacheKey, isEnabled!.Value, TimeSpan.FromMinutes(5));
|
||||||
return isEnabled.Value;
|
return isEnabled.Value;
|
||||||
|
@ -54,13 +54,13 @@ public class AbuseReportController(
|
|||||||
[RequiredPermission("safety", "reports.view")]
|
[RequiredPermission("safety", "reports.view")]
|
||||||
[ProducesResponseType<List<AbuseReport>>(StatusCodes.Status200OK)]
|
[ProducesResponseType<List<AbuseReport>>(StatusCodes.Status200OK)]
|
||||||
public async Task<ActionResult<List<AbuseReport>>> GetReports(
|
public async Task<ActionResult<List<AbuseReport>>> GetReports(
|
||||||
[FromQuery] int skip = 0,
|
[FromQuery] int offset = 0,
|
||||||
[FromQuery] int take = 20,
|
[FromQuery] int take = 20,
|
||||||
[FromQuery] bool includeResolved = false
|
[FromQuery] bool includeResolved = false
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
var totalCount = await safety.CountReports(includeResolved);
|
var totalCount = await safety.CountReports(includeResolved);
|
||||||
var reports = await safety.GetReports(skip, take, includeResolved);
|
var reports = await safety.GetReports(offset, take, includeResolved);
|
||||||
Response.Headers["X-Total"] = totalCount.ToString();
|
Response.Headers["X-Total"] = totalCount.ToString();
|
||||||
return Ok(reports);
|
return Ok(reports);
|
||||||
}
|
}
|
||||||
@ -70,14 +70,15 @@ public class AbuseReportController(
|
|||||||
[ProducesResponseType<List<AbuseReport>>(StatusCodes.Status200OK)]
|
[ProducesResponseType<List<AbuseReport>>(StatusCodes.Status200OK)]
|
||||||
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
|
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
|
||||||
public async Task<ActionResult<List<AbuseReport>>> GetMyReports(
|
public async Task<ActionResult<List<AbuseReport>>> GetMyReports(
|
||||||
[FromQuery] int skip = 0,
|
[FromQuery] int offset = 0,
|
||||||
[FromQuery] int take = 20,
|
[FromQuery] int take = 20,
|
||||||
[FromQuery] bool includeResolved = false)
|
[FromQuery] bool includeResolved = false
|
||||||
|
)
|
||||||
{
|
{
|
||||||
if (HttpContext.Items["CurrentUser"] is not Account.Account currentUser) return Unauthorized();
|
if (HttpContext.Items["CurrentUser"] is not Account.Account currentUser) return Unauthorized();
|
||||||
|
|
||||||
var totalCount = await safety.CountUserReports(currentUser.Id, includeResolved);
|
var totalCount = await safety.CountUserReports(currentUser.Id, includeResolved);
|
||||||
var reports = await safety.GetUserReports(currentUser.Id, skip, take, includeResolved);
|
var reports = await safety.GetUserReports(currentUser.Id, offset, take, includeResolved);
|
||||||
Response.Headers["X-Total"] = totalCount.ToString();
|
Response.Headers["X-Total"] = totalCount.ToString();
|
||||||
return Ok(reports);
|
return Ok(reports);
|
||||||
}
|
}
|
||||||
|
@ -24,6 +24,7 @@ using NodaTime.Serialization.SystemTextJson;
|
|||||||
using StackExchange.Redis;
|
using StackExchange.Redis;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using System.Threading.RateLimiting;
|
using System.Threading.RateLimiting;
|
||||||
|
using DysonNetwork.Sphere.Auth.OidcProvider.Options;
|
||||||
using DysonNetwork.Sphere.Auth.OidcProvider.Services;
|
using DysonNetwork.Sphere.Auth.OidcProvider.Services;
|
||||||
using DysonNetwork.Sphere.Connection.WebReader;
|
using DysonNetwork.Sphere.Connection.WebReader;
|
||||||
using DysonNetwork.Sphere.Developer;
|
using DysonNetwork.Sphere.Developer;
|
||||||
@ -235,6 +236,8 @@ public static class ServiceCollectionExtensions
|
|||||||
services.AddScoped<SafetyService>();
|
services.AddScoped<SafetyService>();
|
||||||
services.AddScoped<DiscoveryService>();
|
services.AddScoped<DiscoveryService>();
|
||||||
services.AddScoped<CustomAppService>();
|
services.AddScoped<CustomAppService>();
|
||||||
|
|
||||||
|
services.Configure<OidcProviderOptions>(configuration.GetSection("OidcProvider"));
|
||||||
services.AddScoped<OidcProviderService>();
|
services.AddScoped<OidcProviderService>();
|
||||||
|
|
||||||
return services;
|
return services;
|
||||||
|
@ -2,6 +2,7 @@ using System.Security.Cryptography;
|
|||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using System.Text.Json.Serialization;
|
using System.Text.Json.Serialization;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
using NodaTime;
|
using NodaTime;
|
||||||
|
|
||||||
namespace DysonNetwork.Sphere.Wallet.PaymentHandlers;
|
namespace DysonNetwork.Sphere.Wallet.PaymentHandlers;
|
||||||
@ -51,7 +52,7 @@ public class AfdianPaymentHandler(
|
|||||||
var sign = CalculateSign(token, userId, paramsJson, ts);
|
var sign = CalculateSign(token, userId, paramsJson, ts);
|
||||||
|
|
||||||
var client = _httpClientFactory.CreateClient();
|
var client = _httpClientFactory.CreateClient();
|
||||||
var request = new HttpRequestMessage(HttpMethod.Post, "https://afdian.com/open/query-order")
|
var request = new HttpRequestMessage(HttpMethod.Post, "https://afdian.com/api/open/query-order")
|
||||||
{
|
{
|
||||||
Content = new StringContent(JsonSerializer.Serialize(new
|
Content = new StringContent(JsonSerializer.Serialize(new
|
||||||
{
|
{
|
||||||
@ -107,7 +108,7 @@ public class AfdianPaymentHandler(
|
|||||||
var sign = CalculateSign(token, userId, paramsJson, ts);
|
var sign = CalculateSign(token, userId, paramsJson, ts);
|
||||||
|
|
||||||
var client = _httpClientFactory.CreateClient();
|
var client = _httpClientFactory.CreateClient();
|
||||||
var request = new HttpRequestMessage(HttpMethod.Post, "https://afdian.com/open/query-order")
|
var request = new HttpRequestMessage(HttpMethod.Post, "https://afdian.com/api/open/query-order")
|
||||||
{
|
{
|
||||||
Content = new StringContent(JsonSerializer.Serialize(new
|
Content = new StringContent(JsonSerializer.Serialize(new
|
||||||
{
|
{
|
||||||
@ -176,7 +177,7 @@ public class AfdianPaymentHandler(
|
|||||||
var sign = CalculateSign(token, userId, paramsJson, ts);
|
var sign = CalculateSign(token, userId, paramsJson, ts);
|
||||||
|
|
||||||
var client = _httpClientFactory.CreateClient();
|
var client = _httpClientFactory.CreateClient();
|
||||||
var request = new HttpRequestMessage(HttpMethod.Post, "https://afdian.com/open/query-order")
|
var request = new HttpRequestMessage(HttpMethod.Post, "https://afdian.com/api/open/query-order")
|
||||||
{
|
{
|
||||||
Content = new StringContent(JsonSerializer.Serialize(new
|
Content = new StringContent(JsonSerializer.Serialize(new
|
||||||
{
|
{
|
||||||
@ -442,4 +443,4 @@ public class SkuDetailItem
|
|||||||
[JsonPropertyName("album_id")] public string AlbumId { get; set; } = null!;
|
[JsonPropertyName("album_id")] public string AlbumId { get; set; } = null!;
|
||||||
|
|
||||||
[JsonPropertyName("pic")] public string Picture { get; set; } = null!;
|
[JsonPropertyName("pic")] public string Picture { get; set; } = null!;
|
||||||
}
|
}
|
||||||
|
@ -7,16 +7,43 @@ namespace DysonNetwork.Sphere.Wallet;
|
|||||||
|
|
||||||
public record class SubscriptionTypeData(
|
public record class SubscriptionTypeData(
|
||||||
string Identifier,
|
string Identifier,
|
||||||
decimal BasePrice
|
string? GroupIdentifier,
|
||||||
|
string Currency,
|
||||||
|
decimal BasePrice,
|
||||||
|
int? RequiredLevel = null
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
public static readonly Dictionary<string, SubscriptionTypeData> SubscriptionDict =
|
public static readonly Dictionary<string, SubscriptionTypeData> SubscriptionDict =
|
||||||
new()
|
new()
|
||||||
{
|
{
|
||||||
[SubscriptionType.Twinkle] = new SubscriptionTypeData(SubscriptionType.Twinkle, 0),
|
[SubscriptionType.Twinkle] = new SubscriptionTypeData(
|
||||||
[SubscriptionType.Stellar] = new SubscriptionTypeData(SubscriptionType.Stellar, 10),
|
SubscriptionType.Twinkle,
|
||||||
[SubscriptionType.Nova] = new SubscriptionTypeData(SubscriptionType.Nova, 20),
|
SubscriptionType.StellarProgram,
|
||||||
[SubscriptionType.Supernova] = new SubscriptionTypeData(SubscriptionType.Supernova, 30)
|
WalletCurrency.SourcePoint,
|
||||||
|
0,
|
||||||
|
1
|
||||||
|
),
|
||||||
|
[SubscriptionType.Stellar] = new SubscriptionTypeData(
|
||||||
|
SubscriptionType.Stellar,
|
||||||
|
SubscriptionType.StellarProgram,
|
||||||
|
WalletCurrency.SourcePoint,
|
||||||
|
1200,
|
||||||
|
3
|
||||||
|
),
|
||||||
|
[SubscriptionType.Nova] = new SubscriptionTypeData(
|
||||||
|
SubscriptionType.Nova,
|
||||||
|
SubscriptionType.StellarProgram,
|
||||||
|
WalletCurrency.SourcePoint,
|
||||||
|
2400,
|
||||||
|
6
|
||||||
|
),
|
||||||
|
[SubscriptionType.Supernova] = new SubscriptionTypeData(
|
||||||
|
SubscriptionType.Supernova,
|
||||||
|
SubscriptionType.StellarProgram,
|
||||||
|
WalletCurrency.SourcePoint,
|
||||||
|
3600,
|
||||||
|
9
|
||||||
|
)
|
||||||
};
|
};
|
||||||
|
|
||||||
public static readonly Dictionary<string, string> SubscriptionHumanReadable =
|
public static readonly Dictionary<string, string> SubscriptionHumanReadable =
|
||||||
@ -65,7 +92,7 @@ public abstract class SubscriptionPaymentMethod
|
|||||||
public enum SubscriptionStatus
|
public enum SubscriptionStatus
|
||||||
{
|
{
|
||||||
Unpaid,
|
Unpaid,
|
||||||
Paid,
|
Active,
|
||||||
Expired,
|
Expired,
|
||||||
Cancelled
|
Cancelled
|
||||||
}
|
}
|
||||||
@ -125,7 +152,7 @@ public class Subscription : ModelBase
|
|||||||
if (BegunAt > now) return false;
|
if (BegunAt > now) return false;
|
||||||
if (EndedAt.HasValue && now > EndedAt.Value) return false;
|
if (EndedAt.HasValue && now > EndedAt.Value) return false;
|
||||||
if (RenewalAt.HasValue && now > RenewalAt.Value) return false;
|
if (RenewalAt.HasValue && now > RenewalAt.Value) return false;
|
||||||
if (Status != SubscriptionStatus.Paid) return false;
|
if (Status != SubscriptionStatus.Active) return false;
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
@ -180,11 +180,12 @@ public class SubscriptionController(SubscriptionService subscriptions, AfdianPay
|
|||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost("order/restore/afdian")]
|
[HttpPost("order/restore/afdian")]
|
||||||
|
[Authorize]
|
||||||
public async Task<IActionResult> RestorePurchaseFromAfdian([FromBody] RestorePurchaseRequest request)
|
public async Task<IActionResult> RestorePurchaseFromAfdian([FromBody] RestorePurchaseRequest request)
|
||||||
{
|
{
|
||||||
var order = await afdian.GetOrderAsync(request.OrderId);
|
var order = await afdian.GetOrderAsync(request.OrderId);
|
||||||
if (order is null) return NotFound($"Order with ID {request.OrderId} was not found.");
|
if (order is null) return NotFound($"Order with ID {request.OrderId} was not found.");
|
||||||
|
|
||||||
var subscription = await subscriptions.CreateSubscriptionFromOrder(order);
|
var subscription = await subscriptions.CreateSubscriptionFromOrder(order);
|
||||||
return Ok(subscription);
|
return Ok(subscription);
|
||||||
}
|
}
|
||||||
@ -200,4 +201,4 @@ public class SubscriptionController(SubscriptionService subscriptions, AfdianPay
|
|||||||
|
|
||||||
return Ok(response);
|
return Ok(response);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -29,7 +29,7 @@ public class SubscriptionRenewalJob(
|
|||||||
// Find subscriptions that need renewal (due for renewal and are still active)
|
// Find subscriptions that need renewal (due for renewal and are still active)
|
||||||
var subscriptionsToRenew = await db.WalletSubscriptions
|
var subscriptionsToRenew = await db.WalletSubscriptions
|
||||||
.Where(s => s.RenewalAt.HasValue && s.RenewalAt.Value <= now) // Due for renewal
|
.Where(s => s.RenewalAt.HasValue && s.RenewalAt.Value <= now) // Due for renewal
|
||||||
.Where(s => s.Status == SubscriptionStatus.Paid) // Only paid subscriptions
|
.Where(s => s.Status == SubscriptionStatus.Active) // Only paid subscriptions
|
||||||
.Where(s => s.IsActive) // Only active subscriptions
|
.Where(s => s.IsActive) // Only active subscriptions
|
||||||
.Where(s => !s.IsFreeTrial) // Exclude free trials
|
.Where(s => !s.IsFreeTrial) // Exclude free trials
|
||||||
.OrderBy(s => s.RenewalAt) // Process oldest first
|
.OrderBy(s => s.RenewalAt) // Process oldest first
|
||||||
@ -49,6 +49,17 @@ public class SubscriptionRenewalJob(
|
|||||||
"Processing renewal for subscription {SubscriptionId} (Identifier: {Identifier}) for account {AccountId}",
|
"Processing renewal for subscription {SubscriptionId} (Identifier: {Identifier}) for account {AccountId}",
|
||||||
subscription.Id, subscription.Identifier, subscription.AccountId);
|
subscription.Id, subscription.Identifier, subscription.AccountId);
|
||||||
|
|
||||||
|
if (subscription.RenewalAt is null)
|
||||||
|
{
|
||||||
|
logger.LogWarning(
|
||||||
|
"Subscription {SubscriptionId} (Identifier: {Identifier}) has no renewal date or has been cancelled.",
|
||||||
|
subscription.Id, subscription.Identifier);
|
||||||
|
subscription.Status = SubscriptionStatus.Cancelled;
|
||||||
|
db.WalletSubscriptions.Update(subscription);
|
||||||
|
await db.SaveChangesAsync();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
// Calculate next cycle duration based on current cycle
|
// Calculate next cycle duration based on current cycle
|
||||||
var currentCycle = subscription.EndedAt!.Value - subscription.BegunAt;
|
var currentCycle = subscription.EndedAt!.Value - subscription.BegunAt;
|
||||||
|
|
||||||
|
@ -32,21 +32,39 @@ public class SubscriptionService(
|
|||||||
bool noop = false
|
bool noop = false
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
var subscriptionTemplate = SubscriptionTypeData
|
var subscriptionInfo = SubscriptionTypeData
|
||||||
.SubscriptionDict.TryGetValue(identifier, out var template)
|
.SubscriptionDict.TryGetValue(identifier, out var template)
|
||||||
? template
|
? template
|
||||||
: null;
|
: null;
|
||||||
if (subscriptionTemplate is null)
|
if (subscriptionInfo is null)
|
||||||
throw new ArgumentOutOfRangeException(nameof(identifier), $@"Subscription {identifier} was not found.");
|
throw new ArgumentOutOfRangeException(nameof(identifier), $@"Subscription {identifier} was not found.");
|
||||||
|
var subscriptionsInGroup = subscriptionInfo.GroupIdentifier is not null
|
||||||
|
? SubscriptionTypeData.SubscriptionDict
|
||||||
|
.Where(s => s.Value.GroupIdentifier == subscriptionInfo.GroupIdentifier)
|
||||||
|
.Select(s => s.Value.Identifier)
|
||||||
|
.ToArray()
|
||||||
|
: [identifier];
|
||||||
|
|
||||||
cycleDuration ??= Duration.FromDays(30);
|
cycleDuration ??= Duration.FromDays(30);
|
||||||
|
|
||||||
var existingSubscription = await GetSubscriptionAsync(account.Id, identifier);
|
var existingSubscription = await GetSubscriptionAsync(account.Id, subscriptionsInGroup);
|
||||||
if (existingSubscription is not null && !noop)
|
if (existingSubscription is not null && !noop)
|
||||||
throw new InvalidOperationException($"Active subscription with identifier {identifier} already exists.");
|
throw new InvalidOperationException($"Active subscription with identifier {identifier} already exists.");
|
||||||
if (existingSubscription is not null)
|
if (existingSubscription is not null)
|
||||||
return existingSubscription;
|
return existingSubscription;
|
||||||
|
|
||||||
|
if (subscriptionInfo.RequiredLevel > 0)
|
||||||
|
{
|
||||||
|
var profile = await db.AccountProfiles
|
||||||
|
.Where(p => p.AccountId == account.Id)
|
||||||
|
.FirstOrDefaultAsync();
|
||||||
|
if (profile is null) throw new InvalidOperationException("Account profile was not found.");
|
||||||
|
if (profile.Level < subscriptionInfo.RequiredLevel)
|
||||||
|
throw new InvalidOperationException(
|
||||||
|
$"Account level must be at least {subscriptionInfo.RequiredLevel} to subscribe to {identifier}."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
if (isFreeTrial)
|
if (isFreeTrial)
|
||||||
{
|
{
|
||||||
var prevFreeTrial = await db.WalletSubscriptions
|
var prevFreeTrial = await db.WalletSubscriptions
|
||||||
@ -77,7 +95,7 @@ public class SubscriptionService(
|
|||||||
Status = SubscriptionStatus.Unpaid,
|
Status = SubscriptionStatus.Unpaid,
|
||||||
PaymentMethod = paymentMethod,
|
PaymentMethod = paymentMethod,
|
||||||
PaymentDetails = paymentDetails,
|
PaymentDetails = paymentDetails,
|
||||||
BasePrice = subscriptionTemplate.BasePrice,
|
BasePrice = subscriptionInfo.BasePrice,
|
||||||
CouponId = couponData?.Id,
|
CouponId = couponData?.Id,
|
||||||
Coupon = couponData,
|
Coupon = couponData,
|
||||||
RenewalAt = (isFreeTrial || !isAutoRenewal) ? null : now.Plus(cycleDuration.Value),
|
RenewalAt = (isFreeTrial || !isAutoRenewal) ? null : now.Plus(cycleDuration.Value),
|
||||||
@ -140,7 +158,7 @@ public class SubscriptionService(
|
|||||||
existingSubscription.PaymentDetails.OrderId = order.Id;
|
existingSubscription.PaymentDetails.OrderId = order.Id;
|
||||||
existingSubscription.EndedAt = order.BegunAt.Plus(cycleDuration);
|
existingSubscription.EndedAt = order.BegunAt.Plus(cycleDuration);
|
||||||
existingSubscription.RenewalAt = order.BegunAt.Plus(cycleDuration);
|
existingSubscription.RenewalAt = order.BegunAt.Plus(cycleDuration);
|
||||||
existingSubscription.Status = SubscriptionStatus.Paid;
|
existingSubscription.Status = SubscriptionStatus.Active;
|
||||||
|
|
||||||
db.Update(existingSubscription);
|
db.Update(existingSubscription);
|
||||||
await db.SaveChangesAsync();
|
await db.SaveChangesAsync();
|
||||||
@ -153,7 +171,7 @@ public class SubscriptionService(
|
|||||||
BegunAt = order.BegunAt,
|
BegunAt = order.BegunAt,
|
||||||
EndedAt = order.BegunAt.Plus(cycleDuration),
|
EndedAt = order.BegunAt.Plus(cycleDuration),
|
||||||
IsActive = true,
|
IsActive = true,
|
||||||
Status = SubscriptionStatus.Paid,
|
Status = SubscriptionStatus.Active,
|
||||||
Identifier = subscriptionIdentifier,
|
Identifier = subscriptionIdentifier,
|
||||||
PaymentMethod = provider,
|
PaymentMethod = provider,
|
||||||
PaymentDetails = new PaymentDetails
|
PaymentDetails = new PaymentDetails
|
||||||
@ -186,10 +204,15 @@ public class SubscriptionService(
|
|||||||
var subscription = await GetSubscriptionAsync(accountId, identifier);
|
var subscription = await GetSubscriptionAsync(accountId, identifier);
|
||||||
if (subscription is null)
|
if (subscription is null)
|
||||||
throw new InvalidOperationException($"Subscription with identifier {identifier} was not found.");
|
throw new InvalidOperationException($"Subscription with identifier {identifier} was not found.");
|
||||||
if (subscription.Status == SubscriptionStatus.Cancelled)
|
if (subscription.Status != SubscriptionStatus.Active)
|
||||||
throw new InvalidOperationException("Subscription is already cancelled.");
|
throw new InvalidOperationException("Subscription is already cancelled.");
|
||||||
|
if (subscription.RenewalAt is null)
|
||||||
|
throw new InvalidOperationException("Subscription is no need to be cancelled.");
|
||||||
|
if (subscription.PaymentMethod != SubscriptionPaymentMethod.InAppWallet)
|
||||||
|
throw new InvalidOperationException(
|
||||||
|
"Only in-app wallet subscription can be cancelled. For other payment methods, please head to the payment provider."
|
||||||
|
);
|
||||||
|
|
||||||
subscription.Status = SubscriptionStatus.Cancelled;
|
|
||||||
subscription.RenewalAt = null;
|
subscription.RenewalAt = null;
|
||||||
|
|
||||||
await db.SaveChangesAsync();
|
await db.SaveChangesAsync();
|
||||||
@ -221,9 +244,15 @@ public class SubscriptionService(
|
|||||||
.FirstOrDefaultAsync();
|
.FirstOrDefaultAsync();
|
||||||
if (subscription is null) throw new InvalidOperationException("No matching subscription found.");
|
if (subscription is null) throw new InvalidOperationException("No matching subscription found.");
|
||||||
|
|
||||||
|
var subscriptionInfo = SubscriptionTypeData.SubscriptionDict
|
||||||
|
.TryGetValue(subscription.Identifier, out var template)
|
||||||
|
? template
|
||||||
|
: null;
|
||||||
|
if (subscriptionInfo is null) throw new InvalidOperationException("No matching subscription found.");
|
||||||
|
|
||||||
return await payment.CreateOrderAsync(
|
return await payment.CreateOrderAsync(
|
||||||
null,
|
null,
|
||||||
WalletCurrency.GoldenPoint,
|
subscriptionInfo.Currency,
|
||||||
subscription.FinalPrice,
|
subscription.FinalPrice,
|
||||||
appIdentifier: SubscriptionOrderIdentifier,
|
appIdentifier: SubscriptionOrderIdentifier,
|
||||||
meta: new Dictionary<string, object>()
|
meta: new Dictionary<string, object>()
|
||||||
@ -264,7 +293,7 @@ public class SubscriptionService(
|
|||||||
subscription.EndedAt = nextEndedAt;
|
subscription.EndedAt = nextEndedAt;
|
||||||
}
|
}
|
||||||
|
|
||||||
subscription.Status = SubscriptionStatus.Paid;
|
subscription.Status = SubscriptionStatus.Active;
|
||||||
|
|
||||||
db.Update(subscription);
|
db.Update(subscription);
|
||||||
await db.SaveChangesAsync();
|
await db.SaveChangesAsync();
|
||||||
@ -294,7 +323,7 @@ public class SubscriptionService(
|
|||||||
// Find active subscriptions that have passed their end date
|
// Find active subscriptions that have passed their end date
|
||||||
var expiredSubscriptions = await db.WalletSubscriptions
|
var expiredSubscriptions = await db.WalletSubscriptions
|
||||||
.Where(s => s.IsActive)
|
.Where(s => s.IsActive)
|
||||||
.Where(s => s.Status == SubscriptionStatus.Paid)
|
.Where(s => s.Status == SubscriptionStatus.Active)
|
||||||
.Where(s => s.EndedAt.HasValue && s.EndedAt.Value < now)
|
.Where(s => s.EndedAt.HasValue && s.EndedAt.Value < now)
|
||||||
.Take(batchSize)
|
.Take(batchSize)
|
||||||
.ToListAsync();
|
.ToListAsync();
|
||||||
@ -319,7 +348,7 @@ public class SubscriptionService(
|
|||||||
{
|
{
|
||||||
var account = await db.Accounts.FirstOrDefaultAsync(a => a.Id == subscription.AccountId);
|
var account = await db.Accounts.FirstOrDefaultAsync(a => a.Id == subscription.AccountId);
|
||||||
if (account is null) return;
|
if (account is null) return;
|
||||||
|
|
||||||
AccountService.SetCultureInfo(account);
|
AccountService.SetCultureInfo(account);
|
||||||
|
|
||||||
var humanReadableName =
|
var humanReadableName =
|
||||||
@ -345,10 +374,10 @@ public class SubscriptionService(
|
|||||||
|
|
||||||
private const string SubscriptionCacheKeyPrefix = "subscription:";
|
private const string SubscriptionCacheKeyPrefix = "subscription:";
|
||||||
|
|
||||||
public async Task<Subscription?> GetSubscriptionAsync(Guid accountId, string identifier)
|
public async Task<Subscription?> GetSubscriptionAsync(Guid accountId, params string[] identifiers)
|
||||||
{
|
{
|
||||||
// Create a unique cache key for this subscription
|
// Create a unique cache key for this subscription
|
||||||
var cacheKey = $"{SubscriptionCacheKeyPrefix}{accountId}:{identifier}";
|
var cacheKey = $"{SubscriptionCacheKeyPrefix}{accountId}:{string.Join(",", identifiers)}";
|
||||||
|
|
||||||
// Try to get the subscription from cache first
|
// Try to get the subscription from cache first
|
||||||
var (found, cachedSubscription) = await cache.GetAsyncWithStatus<Subscription>(cacheKey);
|
var (found, cachedSubscription) = await cache.GetAsyncWithStatus<Subscription>(cacheKey);
|
||||||
@ -359,15 +388,13 @@ public class SubscriptionService(
|
|||||||
|
|
||||||
// If not in cache, get from database
|
// If not in cache, get from database
|
||||||
var subscription = await db.WalletSubscriptions
|
var subscription = await db.WalletSubscriptions
|
||||||
.Where(s => s.AccountId == accountId && s.Identifier == identifier)
|
.Where(s => s.AccountId == accountId && identifiers.Contains(s.Identifier))
|
||||||
.OrderByDescending(s => s.BegunAt)
|
.OrderByDescending(s => s.BegunAt)
|
||||||
.FirstOrDefaultAsync();
|
.FirstOrDefaultAsync();
|
||||||
|
|
||||||
// Cache the result if found (with 30 minutes expiry)
|
// Cache the result if found (with 30 minutes expiry)
|
||||||
if (subscription != null)
|
if (subscription != null)
|
||||||
{
|
|
||||||
await cache.SetAsync(cacheKey, subscription, TimeSpan.FromMinutes(30));
|
await cache.SetAsync(cacheKey, subscription, TimeSpan.FromMinutes(30));
|
||||||
}
|
|
||||||
|
|
||||||
return subscription;
|
return subscription;
|
||||||
}
|
}
|
||||||
|
@ -23,10 +23,19 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"Jwt": {
|
"AuthToken": {
|
||||||
"PublicKeyPath": "Keys/PublicKey.pem",
|
"PublicKeyPath": "Keys/PublicKey.pem",
|
||||||
"PrivateKeyPath": "Keys/PrivateKey.pem"
|
"PrivateKeyPath": "Keys/PrivateKey.pem"
|
||||||
},
|
},
|
||||||
|
"OidcProvider": {
|
||||||
|
"IssuerUri": "https://nt.solian.app",
|
||||||
|
"PublicKeyPath": "Keys/PublicKey.pem",
|
||||||
|
"PrivateKeyPath": "Keys/PrivateKey.pem",
|
||||||
|
"AccessTokenLifetime": "01:00:00",
|
||||||
|
"RefreshTokenLifetime": "30.00:00:00",
|
||||||
|
"AuthorizationCodeLifetime": "00:30:00",
|
||||||
|
"RequireHttpsMetadata": true
|
||||||
|
},
|
||||||
"Tus": {
|
"Tus": {
|
||||||
"StorePath": "Uploads"
|
"StorePath": "Uploads"
|
||||||
},
|
},
|
||||||
@ -117,4 +126,4 @@
|
|||||||
"127.0.0.1",
|
"127.0.0.1",
|
||||||
"::1"
|
"::1"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
@ -50,6 +50,7 @@
|
|||||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AITusStore_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2024_002E3_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F8bb08a178b5b43c5bac20a5a54159a5b2a800_003Fb1_003F7e861de5_003FITusStore_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AITusStore_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2024_002E3_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F8bb08a178b5b43c5bac20a5a54159a5b2a800_003Fb1_003F7e861de5_003FITusStore_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AJsonSerializerOptions_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2025_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F5703920a18f94462b4354fab05326e6519a200_003F35_003F8536fc49_003FJsonSerializerOptions_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AJsonSerializerOptions_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2025_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F5703920a18f94462b4354fab05326e6519a200_003F35_003F8536fc49_003FJsonSerializerOptions_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AJwtBearerExtensions_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2025_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003Ff611a1225a3445458f2ca3f102eed5bdcd10_003F07_003F030df6ba_003FJwtBearerExtensions_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AJwtBearerExtensions_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2025_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003Ff611a1225a3445458f2ca3f102eed5bdcd10_003F07_003F030df6ba_003FJwtBearerExtensions_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||||
|
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AJwtSecurityTokenHandler_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2025_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F19f907d47c6f4a2ea68238bf22de133a16600_003Fa0_003F66d8c35f_003FJwtSecurityTokenHandler_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AJwtSecurityTokenHandler_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2025_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F477051138f1f40de9077b7b1cdc55c6215fb0_003Ff5_003Fd716e016_003FJwtSecurityTokenHandler_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AJwtSecurityTokenHandler_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2025_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F477051138f1f40de9077b7b1cdc55c6215fb0_003Ff5_003Fd716e016_003FJwtSecurityTokenHandler_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AKestrelServerLimits_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2025_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F1e2e5dfcafad4407b569dd5df56a2fbf274e00_003Fa4_003F39445f62_003FKestrelServerLimits_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AKestrelServerLimits_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2025_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F1e2e5dfcafad4407b569dd5df56a2fbf274e00_003Fa4_003F39445f62_003FKestrelServerLimits_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AKnownResamplers_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2025_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003Fef3339e864a448e2b1ec6fa7bbf4c6661fee00_003Fb3_003Fcdb3e080_003FKnownResamplers_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AKnownResamplers_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2025_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003Fef3339e864a448e2b1ec6fa7bbf4c6661fee00_003Fb3_003Fcdb3e080_003FKnownResamplers_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||||
@ -60,6 +61,7 @@
|
|||||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003ANotFoundResult_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2024_002E3_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F0b5acdd962e549369896cece0026e556214600_003F28_003F290250f5_003FNotFoundResult_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003ANotFoundResult_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2024_002E3_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F0b5acdd962e549369896cece0026e556214600_003F28_003F290250f5_003FNotFoundResult_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003ANotFound_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2024_002E3_003Fresharper_002Dhost_003FSourcesCache_003Ff2c049af93e430aac427e8ff3cc9edd8763d5c9f006d7121ed1c5921585cba_003FNotFound_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003ANotFound_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2024_002E3_003Fresharper_002Dhost_003FSourcesCache_003Ff2c049af93e430aac427e8ff3cc9edd8763d5c9f006d7121ed1c5921585cba_003FNotFound_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003ANpgsqlEntityTypeBuilderExtensions_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2025_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003Fccb1faacaea4420db96b09857fc56178a1600_003Fd9_003F9acf9507_003FNpgsqlEntityTypeBuilderExtensions_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003ANpgsqlEntityTypeBuilderExtensions_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2025_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003Fccb1faacaea4420db96b09857fc56178a1600_003Fd9_003F9acf9507_003FNpgsqlEntityTypeBuilderExtensions_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||||
|
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003ANullable_00601_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2025_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F3bef61b8a21d4c8e96872ecdd7782fa0e55000_003F79_003F4ab1c673_003FNullable_00601_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003ANullable_00601_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2025_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003Fb6f0571a6bc744b0b551fd4578292582e54c00_003F6a_003Fea17bf26_003FNullable_00601_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003ANullable_00601_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2025_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003Fb6f0571a6bc744b0b551fd4578292582e54c00_003F6a_003Fea17bf26_003FNullable_00601_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AOk_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2024_002E3_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F01d30b32e2ff422cb80129ca2a441c4242600_003F3b_003F237bf104_003FOk_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AOk_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2024_002E3_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F01d30b32e2ff422cb80129ca2a441c4242600_003F3b_003F237bf104_003FOk_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AOptionsConfigurationServiceCollectionExtensions_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2024_002E3_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F6622dea924b14dc7aa3ee69d7c84e5735000_003Fe0_003F024ba0b7_003FOptionsConfigurationServiceCollectionExtensions_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AOptionsConfigurationServiceCollectionExtensions_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2024_002E3_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F6622dea924b14dc7aa3ee69d7c84e5735000_003Fe0_003F024ba0b7_003FOptionsConfigurationServiceCollectionExtensions_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||||
@ -81,6 +83,7 @@
|
|||||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AStackFrameIterator_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2025_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003Fb6f0571a6bc744b0b551fd4578292582e54c00_003Fdf_003F3fcdc4d2_003FStackFrameIterator_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AStackFrameIterator_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2025_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003Fb6f0571a6bc744b0b551fd4578292582e54c00_003Fdf_003F3fcdc4d2_003FStackFrameIterator_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AStatusCodeResult_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2024_002E3_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F0b5acdd962e549369896cece0026e556214600_003F7c_003F8b7572ae_003FStatusCodeResult_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AStatusCodeResult_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2024_002E3_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F0b5acdd962e549369896cece0026e556214600_003F7c_003F8b7572ae_003FStatusCodeResult_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003ASyndicationFeed_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2025_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F5b43b9cf654743f8b9a2eee23c625dd21dd30_003Fad_003Fd26b4d73_003FSyndicationFeed_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003ASyndicationFeed_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2025_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F5b43b9cf654743f8b9a2eee23c625dd21dd30_003Fad_003Fd26b4d73_003FSyndicationFeed_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||||
|
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003ASyndicationItem_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2025_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F5b43b9cf654743f8b9a2eee23c625dd21dd30_003Fe1_003Fb136d7be_003FSyndicationItem_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003ATagging_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2024_002E3_003Fresharper_002Dhost_003FSourcesCache_003F36f4c2e6baa65ba603de42eedad12ea36845aa35a910a6a82d82baf688e3e1_003FTagging_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003ATagging_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2024_002E3_003Fresharper_002Dhost_003FSourcesCache_003F36f4c2e6baa65ba603de42eedad12ea36845aa35a910a6a82d82baf688e3e1_003FTagging_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AThrowHelper_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2025_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003Fb6f0571a6bc744b0b551fd4578292582e54c00_003F12_003Fe0a28ad6_003FThrowHelper_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AThrowHelper_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2025_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003Fb6f0571a6bc744b0b551fd4578292582e54c00_003F12_003Fe0a28ad6_003FThrowHelper_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003ATotp_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2025_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F48c9d2a1b3c84b32b36ebc6f20a927ea4600_003F7b_003Ff98e5727_003FTotp_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003ATotp_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2025_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F48c9d2a1b3c84b32b36ebc6f20a927ea4600_003F7b_003Ff98e5727_003FTotp_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||||
|
Reference in New Issue
Block a user