mirror of
https://github.com/streetwriters/notesnook-sync-server.git
synced 2026-08-13 20:10:18 +02:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
28d614d80b | ||
|
|
ebb1d44edd |
@@ -42,7 +42,6 @@ namespace Notesnook.API.Accessors
|
||||
public SyncItemsRepository Colors { get; }
|
||||
public SyncItemsRepository Vaults { get; }
|
||||
public SyncItemsRepository Tags { get; }
|
||||
public SyncItemsRepository InboxItemsHistory { get; }
|
||||
public Repository<UserSettings> UsersSettings { get; }
|
||||
public Repository<Monograph> Monographs { get; }
|
||||
public Repository<InboxApiKey> InboxApiKey { get; }
|
||||
@@ -76,8 +75,6 @@ namespace Notesnook.API.Accessors
|
||||
IMongoCollection<SyncItem> vaults,
|
||||
[FromKeyedServices(Collections.TagsKey)]
|
||||
IMongoCollection<SyncItem> tags,
|
||||
[FromKeyedServices(Collections.InboxItemsHistoryKey)]
|
||||
IMongoCollection<SyncItem> inboxItemsHistory,
|
||||
|
||||
Repository<UserSettings> usersSettings,
|
||||
Repository<Monograph> monographs,
|
||||
@@ -105,7 +102,6 @@ namespace Notesnook.API.Accessors
|
||||
Colors = new SyncItemsRepository(dbContext, colors, logger);
|
||||
Vaults = new SyncItemsRepository(dbContext, vaults, logger);
|
||||
Tags = new SyncItemsRepository(dbContext, tags, logger);
|
||||
InboxItemsHistory = new SyncItemsRepository(dbContext, inboxItemsHistory, logger);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,5 @@ namespace Notesnook.API
|
||||
public const string InboxApiKeysKey = "inbox_api_keys";
|
||||
public const string SyncDevicesKey = "sync_devices";
|
||||
public const string DeviceIdsChunksKey = "device_ids_chunks";
|
||||
public const string InboxItemsHistoryKey = "inbox_items_history";
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,6 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Security.Claims;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
@@ -73,9 +72,9 @@ namespace Notesnook.API.Controllers
|
||||
{
|
||||
return BadRequest(new { error = "Api key name is required." });
|
||||
}
|
||||
if (request.ExpiryDate == null)
|
||||
if (request.ExpiryDate <= -1)
|
||||
{
|
||||
return BadRequest(new { error = "Expiry date is required." });
|
||||
return BadRequest(new { error = "Valid expiry date is required." });
|
||||
}
|
||||
|
||||
var count = await inboxApiKeysRepository.CountAsync(t => t.UserId == userId);
|
||||
@@ -134,7 +133,7 @@ namespace Notesnook.API.Controllers
|
||||
var userSetting = await userSettingsRepository.FindOneAsync(u => u.UserId == userId);
|
||||
if (string.IsNullOrWhiteSpace(userSetting?.InboxKeys?.Public))
|
||||
{
|
||||
return NotFound(new { error = "Inbox public key is not configured." });
|
||||
return BadRequest(new { error = "Inbox public key is not configured." });
|
||||
}
|
||||
return Ok(new { key = userSetting.InboxKeys.Public });
|
||||
}
|
||||
|
||||
@@ -183,8 +183,8 @@ namespace Notesnook.API.Controllers
|
||||
try
|
||||
{
|
||||
var userId = this.User.GetUserId();
|
||||
var size = await s3Service.GetObjectSizeAsync(userId, name); Response.Headers.ContentLength = size;
|
||||
Response.Headers["X-Object-Size"] = size.ToString();
|
||||
var size = await s3Service.GetObjectSizeAsync(userId, name);
|
||||
HttpContext.Response.Headers.ContentLength = size;
|
||||
return Ok();
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
@@ -57,9 +57,21 @@ namespace Notesnook.API.Hubs
|
||||
private ISyncItemsRepositoryAccessor Repositories { get; }
|
||||
private SyncDeviceService SyncDeviceService { get; }
|
||||
private readonly IUnitOfWork unit;
|
||||
private static readonly string[] CollectionKeys = [
|
||||
"settingitem",
|
||||
"attachment",
|
||||
"note",
|
||||
"notebook",
|
||||
"content",
|
||||
"shortcut",
|
||||
"reminder",
|
||||
"color",
|
||||
"tag",
|
||||
"vault",
|
||||
"relation", // relations must sync at the end to prevent invalid state
|
||||
];
|
||||
private readonly FrozenDictionary<string, Action<IEnumerable<SyncItem>, string, long>> UpsertActionsMap;
|
||||
private readonly CollectionDef[] BaseCollectionDefs;
|
||||
private readonly CollectionDef[] V4CollectionDefs;
|
||||
private readonly Func<string, IEnumerable<string>, bool, int, Task<IAsyncCursor<SyncItem>>>[] Collections;
|
||||
ILogger<SyncV2Hub> Logger { get; }
|
||||
|
||||
public SyncV2Hub(ISyncItemsRepositoryAccessor syncItemsRepositoryAccessor, IUnitOfWork unitOfWork, SyncDeviceService syncDeviceService, ILogger<SyncV2Hub> logger)
|
||||
@@ -69,32 +81,18 @@ namespace Notesnook.API.Hubs
|
||||
unit = unitOfWork;
|
||||
SyncDeviceService = syncDeviceService;
|
||||
|
||||
BaseCollectionDefs = [
|
||||
new("settingitem", Repositories.Settings.FindItemsById),
|
||||
new("attachment", Repositories.Attachments.FindItemsById),
|
||||
new("note", Repositories.Notes.FindItemsById),
|
||||
new("notebook", Repositories.Notebooks.FindItemsById),
|
||||
new("content", Repositories.Contents.FindItemsById),
|
||||
new("shortcut", Repositories.Shortcuts.FindItemsById),
|
||||
new("reminder", Repositories.Reminders.FindItemsById),
|
||||
new("color", Repositories.Colors.FindItemsById),
|
||||
new("tag", Repositories.Tags.FindItemsById),
|
||||
new("vault", Repositories.Vaults.FindItemsById),
|
||||
new("relation", Repositories.Relations.FindItemsById), // relations must sync at the end to prevent invalid state
|
||||
];
|
||||
V4CollectionDefs = [
|
||||
new("settingitem", Repositories.Settings.FindItemsById),
|
||||
new("attachment", Repositories.Attachments.FindItemsById),
|
||||
new("note", Repositories.Notes.FindItemsById),
|
||||
new("notebook", Repositories.Notebooks.FindItemsById),
|
||||
new("content", Repositories.Contents.FindItemsById),
|
||||
new("shortcut", Repositories.Shortcuts.FindItemsById),
|
||||
new("reminder", Repositories.Reminders.FindItemsById),
|
||||
new("color", Repositories.Colors.FindItemsById),
|
||||
new("tag", Repositories.Tags.FindItemsById),
|
||||
new("vault", Repositories.Vaults.FindItemsById),
|
||||
new("inboxitemhistory", Repositories.InboxItemsHistory.FindItemsById),
|
||||
new("relation", Repositories.Relations.FindItemsById), // relations must sync at the end to prevent invalid state
|
||||
Collections = [
|
||||
Repositories.Settings.FindItemsById,
|
||||
Repositories.Attachments.FindItemsById,
|
||||
Repositories.Notes.FindItemsById,
|
||||
Repositories.Notebooks.FindItemsById,
|
||||
Repositories.Contents.FindItemsById,
|
||||
Repositories.Shortcuts.FindItemsById,
|
||||
Repositories.Reminders.FindItemsById,
|
||||
Repositories.Colors.FindItemsById,
|
||||
Repositories.Tags.FindItemsById,
|
||||
Repositories.Vaults.FindItemsById,
|
||||
Repositories.Relations.FindItemsById,
|
||||
];
|
||||
UpsertActionsMap = new Dictionary<string, Action<IEnumerable<SyncItem>, string, long>> {
|
||||
{ "settingitem", Repositories.Settings.UpsertMany },
|
||||
@@ -108,7 +106,6 @@ namespace Notesnook.API.Hubs
|
||||
{ "color", Repositories.Colors.UpsertMany },
|
||||
{ "vault", Repositories.Vaults.UpsertMany },
|
||||
{ "tag", Repositories.Tags.UpsertMany },
|
||||
{ "inboxitemhistory", Repositories.InboxItemsHistory.UpsertMany },
|
||||
}.ToFrozenDictionary();
|
||||
}
|
||||
|
||||
@@ -125,19 +122,6 @@ namespace Notesnook.API.Hubs
|
||||
await base.OnConnectedAsync();
|
||||
}
|
||||
|
||||
public override async Task OnDisconnectedAsync(Exception? exception)
|
||||
{
|
||||
if (exception != null)
|
||||
{
|
||||
Logger.LogWarning(exception, "Connection {ConnectionId} disconnected with error (server-side drop)", Context.ConnectionId);
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.LogInformation("Connection {ConnectionId} disconnected cleanly (client-initiated)", Context.ConnectionId);
|
||||
}
|
||||
await base.OnDisconnectedAsync(exception);
|
||||
}
|
||||
|
||||
|
||||
public async Task<int> PushItems(string deviceId, SyncTransferItemV2 pushItem)
|
||||
{
|
||||
@@ -184,17 +168,17 @@ namespace Notesnook.API.Hubs
|
||||
return true;
|
||||
}
|
||||
|
||||
private async IAsyncEnumerable<SyncTransferItemV2> PrepareChunks(string userId, HashSet<ItemKey> ids, int size, bool resetSync, long maxBytes, CollectionDef[] collectionDefs)
|
||||
private async IAsyncEnumerable<SyncTransferItemV2> PrepareChunks(string userId, HashSet<ItemKey> ids, int size, bool resetSync, long maxBytes)
|
||||
{
|
||||
var itemsProcessed = 0;
|
||||
foreach (var def in collectionDefs)
|
||||
for (int i = 0; i < Collections.Length; i++)
|
||||
{
|
||||
var type = def.Key;
|
||||
var type = CollectionKeys[i];
|
||||
|
||||
var filteredIds = ids.Where((id) => id.Type == type).Select((id) => id.ItemId).ToArray();
|
||||
if (!resetSync && filteredIds.Length == 0) continue;
|
||||
|
||||
using var cursor = await def.FindItems(userId, filteredIds, resetSync, size);
|
||||
using var cursor = await Collections[i](userId, filteredIds, resetSync, size);
|
||||
|
||||
var chunk = new List<SyncItem>();
|
||||
long totalBytes = 0;
|
||||
@@ -236,25 +220,20 @@ namespace Notesnook.API.Hubs
|
||||
|
||||
public async Task<SyncV2Metadata> RequestFetch(string deviceId)
|
||||
{
|
||||
return await HandleRequestFetch(deviceId, false, false, BaseCollectionDefs);
|
||||
return await HandleRequestFetch(deviceId, false, false);
|
||||
}
|
||||
|
||||
public async Task<SyncV2Metadata> RequestFetchV2(string deviceId)
|
||||
{
|
||||
return await HandleRequestFetch(deviceId, true, false, BaseCollectionDefs);
|
||||
return await HandleRequestFetch(deviceId, true, false);
|
||||
}
|
||||
|
||||
public async Task<SyncV2Metadata> RequestFetchV3(string deviceId)
|
||||
{
|
||||
return await HandleRequestFetch(deviceId, true, true, BaseCollectionDefs);
|
||||
return await HandleRequestFetch(deviceId, true, true);
|
||||
}
|
||||
|
||||
public async Task<SyncV2Metadata> RequestFetchV4(string deviceId)
|
||||
{
|
||||
return await HandleRequestFetch(deviceId, true, true, V4CollectionDefs);
|
||||
}
|
||||
|
||||
private async Task<SyncV2Metadata> HandleRequestFetch(string deviceId, bool includeMonographs, bool includeInboxItems, CollectionDef[] collectionDefs)
|
||||
private async Task<SyncV2Metadata> HandleRequestFetch(string deviceId, bool includeMonographs, bool includeInboxItems)
|
||||
{
|
||||
var userId = Context.User?.FindFirstValue("sub") ?? throw new HubException("Please login to sync.");
|
||||
|
||||
@@ -278,8 +257,7 @@ namespace Notesnook.API.Hubs
|
||||
ids,
|
||||
size: 100,
|
||||
resetSync: device.IsSyncReset,
|
||||
maxBytes: 3 * 1024 * 1024,
|
||||
collectionDefs
|
||||
maxBytes: 3 * 1024 * 1024
|
||||
);
|
||||
|
||||
await foreach (var chunk in chunks)
|
||||
@@ -334,7 +312,7 @@ namespace Notesnook.API.Hubs
|
||||
var unsyncedInboxItemIds = ids.Where(k => k.Type == "inbox_item").Select(k => k.ItemId);
|
||||
var userInboxItems = device.IsSyncReset
|
||||
? await Repositories.InboxItems.FindAsync(m => m.UserId == userId)
|
||||
: await Repositories.InboxItems.FindAsync(m => m.UserId == userId && unsyncedInboxItemIds.Contains(m.ItemId));
|
||||
: await Repositories.InboxItems.FindAsync(m => m.UserId == userId && unsyncedInboxItemIds.Contains(m.ItemId ?? m.Id.ToString()));
|
||||
if (userInboxItems.Any() && !await Clients.Caller.SendInboxItems(userInboxItems).WaitAsync(TimeSpan.FromMinutes(10)))
|
||||
{
|
||||
throw new HubException("Client rejected inbox items.");
|
||||
@@ -353,11 +331,6 @@ namespace Notesnook.API.Hubs
|
||||
SyncEventCounterSource.Log.RecordFetchDuration(stopwatch.ElapsedMilliseconds);
|
||||
}
|
||||
}
|
||||
|
||||
private record CollectionDef(
|
||||
string Key,
|
||||
Func<string, IEnumerable<string>, bool, int, Task<IAsyncCursor<SyncItem>>> FindItems
|
||||
);
|
||||
}
|
||||
|
||||
[MessagePack.MessagePackObject]
|
||||
|
||||
@@ -38,7 +38,6 @@ namespace Notesnook.API.Interfaces
|
||||
SyncItemsRepository Colors { get; }
|
||||
SyncItemsRepository Vaults { get; }
|
||||
SyncItemsRepository Tags { get; }
|
||||
SyncItemsRepository InboxItemsHistory { get; }
|
||||
Repository<UserSettings> UsersSettings { get; }
|
||||
Repository<Monograph> Monographs { get; }
|
||||
Repository<InboxApiKey> InboxApiKey { get; }
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AngleSharp" Version="1.3.0" />
|
||||
<PackageReference Include="AspNetCore.HealthChecks.Aws.S3" Version="9.0.0" />
|
||||
<PackageReference Include="AspNetCore.HealthChecks.Redis" Version="9.0.0" />
|
||||
<PackageReference Include="AWSSDK.Core" Version="3.7.304.31" />
|
||||
<PackageReference Include="DotNetEnv" Version="2.3.0" />
|
||||
<PackageReference Include="IdentityModel.AspNetCore.OAuth2Introspection" Version="6.2.0" />
|
||||
|
||||
@@ -174,19 +174,18 @@ namespace Notesnook.API.Services
|
||||
else
|
||||
{
|
||||
userSettings.InboxKeys = keys.InboxKeys;
|
||||
var defaultInboxKey = new InboxApiKey
|
||||
{
|
||||
UserId = userId,
|
||||
Name = "Default",
|
||||
DateCreated = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
|
||||
ExpiryDate = DateTimeOffset.UtcNow.AddYears(1).ToUnixTimeMilliseconds(),
|
||||
LastUsedAt = 0
|
||||
};
|
||||
await Repositories.InboxApiKey.InsertAsync(defaultInboxKey);
|
||||
}
|
||||
|
||||
await Repositories.InboxItems.DeleteManyAsync(t => t.UserId == userId);
|
||||
await WampServers.MessengerServer.PublishMessageAsync(MessengerServerTopics.SendSSETopic, new SendSSEMessage
|
||||
{
|
||||
OriginTokenId = null,
|
||||
UserId = userId,
|
||||
Message = new Message
|
||||
{
|
||||
Type = "inboxUpdated",
|
||||
Data = JsonSerializer.Serialize(new { reason = "Inbox PGP keys added, updated, or removed." })
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
await Repositories.UsersSettings.UpdateAsync(userSettings.Id, userSettings);
|
||||
@@ -209,7 +208,6 @@ namespace Notesnook.API.Services
|
||||
Repositories.Colors.DeleteByUserId(userId);
|
||||
Repositories.Tags.DeleteByUserId(userId);
|
||||
Repositories.Vaults.DeleteByUserId(userId);
|
||||
Repositories.InboxItemsHistory.DeleteByUserId(userId);
|
||||
Repositories.UsersSettings.Delete((u) => u.UserId == userId);
|
||||
Repositories.Monographs.DeleteMany((m) => m.UserId == userId);
|
||||
Repositories.InboxApiKey.DeleteMany((t) => t.UserId == userId);
|
||||
@@ -271,7 +269,6 @@ namespace Notesnook.API.Services
|
||||
Repositories.Colors.DeleteByUserId(userId);
|
||||
Repositories.Tags.DeleteByUserId(userId);
|
||||
Repositories.Vaults.DeleteByUserId(userId);
|
||||
Repositories.InboxItemsHistory.DeleteByUserId(userId);
|
||||
Repositories.Monographs.DeleteMany((m) => m.UserId == userId);
|
||||
Repositories.InboxApiKey.DeleteMany((t) => t.UserId == userId);
|
||||
if (!await unit.Commit()) return false;
|
||||
|
||||
@@ -25,7 +25,6 @@ using System.Text;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Threading.Tasks;
|
||||
using Amazon.Runtime;
|
||||
using StackExchange.Redis;
|
||||
using IdentityModel.AspNetCore.OAuth2Introspection;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
@@ -197,8 +196,7 @@ namespace Notesnook.API
|
||||
.AddMongoCollection(Collections.ColorsKey)
|
||||
.AddMongoCollection(Collections.VaultsKey)
|
||||
.AddMongoCollection(Collections.InboxItemsKey)
|
||||
.AddMongoCollection(Collections.InboxApiKeysKey)
|
||||
.AddMongoCollection(Collections.InboxItemsHistoryKey);
|
||||
.AddMongoCollection(Collections.InboxApiKeysKey);
|
||||
|
||||
services.AddScoped<ISyncItemsRepositoryAccessor, SyncItemsRepositoryAccessor>();
|
||||
services.AddScoped<SyncDeviceService>();
|
||||
@@ -221,20 +219,7 @@ namespace Notesnook.API
|
||||
}).AddMessagePackProtocol().AddJsonProtocol();
|
||||
|
||||
if (!string.IsNullOrEmpty(Constants.SIGNALR_REDIS_CONNECTION_STRING))
|
||||
{
|
||||
services.AddHealthChecks()
|
||||
.AddRedis(Constants.SIGNALR_REDIS_CONNECTION_STRING, tags: ["ready"]);
|
||||
signalR.AddStackExchangeRedis(options =>
|
||||
{
|
||||
options.Configuration = ConfigurationOptions.Parse(Constants.SIGNALR_REDIS_CONNECTION_STRING);
|
||||
options.Configuration.AbortOnConnectFail = false;
|
||||
options.Configuration.ConnectRetry = 5;
|
||||
options.Configuration.ReconnectRetryPolicy = new ExponentialRetry(5000, 30000);
|
||||
options.Configuration.KeepAlive = 60;
|
||||
options.Configuration.ConnectTimeout = 5000;
|
||||
options.Configuration.SyncTimeout = 5000;
|
||||
});
|
||||
}
|
||||
signalR.AddStackExchangeRedis(Constants.SIGNALR_REDIS_CONNECTION_STRING);
|
||||
|
||||
services.AddResponseCompression(options =>
|
||||
{
|
||||
|
||||
@@ -17,7 +17,7 @@ const RawInboxItemSchema = z.object({
|
||||
notebookIds: z.array(z.string()).optional(),
|
||||
tagIds: z.array(z.string()).optional(),
|
||||
type: z.enum(["note"]),
|
||||
source: z.string().min(1, "Source is required"),
|
||||
source: z.string(),
|
||||
version: z.literal(1),
|
||||
content: z
|
||||
.object({
|
||||
@@ -56,9 +56,7 @@ async function encrypt(
|
||||
};
|
||||
}
|
||||
|
||||
async function getInboxPublicEncryptionKey(
|
||||
apiKey: string,
|
||||
): Promise<{ status: "unauthorized" } | { status: "ok"; key: string | null }> {
|
||||
async function getInboxPublicEncryptionKey(apiKey: string) {
|
||||
const response = await fetch(
|
||||
`${NOTESNOOK_API_SERVER_URL}/inbox/public-encryption-key`,
|
||||
{
|
||||
@@ -67,9 +65,6 @@ async function getInboxPublicEncryptionKey(
|
||||
},
|
||||
},
|
||||
);
|
||||
if (response.status === 401) {
|
||||
return { status: "unauthorized" };
|
||||
}
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`failed to fetch inbox public encryption key: ${await response.text()}`,
|
||||
@@ -77,7 +72,7 @@ async function getInboxPublicEncryptionKey(
|
||||
}
|
||||
|
||||
const data = (await response.json()) as unknown as any;
|
||||
return { status: "ok", key: (data?.key as string) || null };
|
||||
return (data?.key as string) || null;
|
||||
}
|
||||
|
||||
async function postEncryptedInboxItem(
|
||||
@@ -115,14 +110,10 @@ app.post("/", async (req, res) => {
|
||||
return res.status(401).json({ error: "unauthorized" });
|
||||
}
|
||||
|
||||
const encryptionKeyResult = await getInboxPublicEncryptionKey(apiKey);
|
||||
if (encryptionKeyResult.status === "unauthorized") {
|
||||
return res.status(401).json({ error: "unauthorized" });
|
||||
const inboxPublicKey = await getInboxPublicEncryptionKey(apiKey);
|
||||
if (!inboxPublicKey) {
|
||||
return res.status(403).json({ error: "inbox public key not found" });
|
||||
}
|
||||
if (!encryptionKeyResult.key) {
|
||||
return res.status(404).json({ error: "inbox public key not found" });
|
||||
}
|
||||
const inboxPublicKey = encryptionKeyResult.key;
|
||||
console.log("[info] fetched inbox public key");
|
||||
|
||||
const validationResult = RawInboxItemSchema.safeParse(req.body);
|
||||
|
||||
@@ -52,8 +52,7 @@ namespace Streetwriters.Common.Extensions
|
||||
b.WithOrigins(Constants.NOTESNOOK_CORS_ORIGINS);
|
||||
|
||||
b.AllowAnyMethod()
|
||||
.AllowAnyHeader()
|
||||
.WithExposedHeaders(["X-Object-Size", "Content-Length"]);
|
||||
.AllowAnyHeader();
|
||||
});
|
||||
});
|
||||
return services;
|
||||
|
||||
@@ -190,8 +190,8 @@ namespace Streetwriters.Identity.Controllers
|
||||
var client = Clients.FindClientById(form.ClientId);
|
||||
if (client == null) return BadRequest("Invalid client_id.");
|
||||
|
||||
var user = await UserManager.FindByEmailAsync(form.Email);
|
||||
if (user == null || !await UserService.IsUserValidAsync(UserManager, user, form.ClientId)) return Ok();
|
||||
var user = await UserManager.FindByEmailAsync(form.Email) ?? throw new Exception("User not found.");
|
||||
if (!await UserService.IsUserValidAsync(UserManager, user, form.ClientId)) return Ok();
|
||||
|
||||
var code = await UserManager.GenerateUserTokenAsync(user, TokenOptions.DefaultProvider, "ResetPassword");
|
||||
var callbackUrl = UrlExtensions.TokenLink(user.Id.ToString(), code, client.Id, TokenType.RESET_PASSWORD);
|
||||
|
||||
@@ -79,9 +79,12 @@ namespace Streetwriters.Identity.Controllers
|
||||
}
|
||||
|
||||
[HttpDelete]
|
||||
public IActionResult Disable2FA()
|
||||
public async Task<IActionResult> Disable2FA()
|
||||
{
|
||||
return BadRequest("2FA is mandatory and cannot be disabled.");
|
||||
var user = await UserManager.GetUserAsync(User) ?? throw new Exception("User not found.");
|
||||
if (!await UserManager.GetTwoFactorEnabledAsync(user)) return Ok();
|
||||
await MFAService.DisableMFAAsync(user);
|
||||
return Ok();
|
||||
}
|
||||
|
||||
[HttpGet("codes")]
|
||||
|
||||
@@ -24,7 +24,7 @@ namespace Streetwriters.Identity.Interfaces
|
||||
{
|
||||
public interface ISMSSender
|
||||
{
|
||||
Task<string?> SendOTPAsync(string number, IClient client);
|
||||
Task<string> SendOTPAsync(string number, IClient client);
|
||||
Task<bool> VerifyOTPAsync(string id, string code);
|
||||
}
|
||||
}
|
||||
@@ -186,8 +186,6 @@ namespace Streetwriters.Identity.Services
|
||||
ArgumentNullException.ThrowIfNull(form.PhoneNumber);
|
||||
await UserManager.SetPhoneNumberAsync(user, form.PhoneNumber);
|
||||
var id = await SMSSender.SendOTPAsync(form.PhoneNumber, client);
|
||||
if (string.IsNullOrEmpty(id)) throw new Exception("Failed to send SMS. Please try again.");
|
||||
|
||||
logger.LogInformation("SMS OTP sent for user: {UserId}, SMS ID: {SmsId}", user.Id, id);
|
||||
await this.ReplaceClaimAsync(user, MFAService.SMS_ID_CLAIM, id);
|
||||
break;
|
||||
|
||||
@@ -23,56 +23,36 @@ using Streetwriters.Common;
|
||||
using Twilio.Rest.Verify.V2.Service;
|
||||
using Twilio;
|
||||
using System.Threading.Tasks;
|
||||
using System;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Streetwriters.Identity.Services
|
||||
{
|
||||
public class SMSSender : ISMSSender
|
||||
{
|
||||
private readonly ILogger<SMSSender> Logger;
|
||||
public SMSSender(ILogger<SMSSender> logger)
|
||||
public SMSSender()
|
||||
{
|
||||
Logger = logger;
|
||||
if (!string.IsNullOrEmpty(Constants.TWILIO_ACCOUNT_SID) && !string.IsNullOrEmpty(Constants.TWILIO_AUTH_TOKEN))
|
||||
{
|
||||
TwilioClient.Init(Constants.TWILIO_ACCOUNT_SID, Constants.TWILIO_AUTH_TOKEN);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<string?> SendOTPAsync(string number, IClient app)
|
||||
public async Task<string> SendOTPAsync(string number, IClient app)
|
||||
{
|
||||
try
|
||||
{
|
||||
var verification = await VerificationResource.CreateAsync(
|
||||
to: number,
|
||||
channel: "sms",
|
||||
pathServiceSid: Constants.TWILIO_SERVICE_SID
|
||||
);
|
||||
return verification.Sid;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, "Error sending OTP with Twilio");
|
||||
return null;
|
||||
}
|
||||
var verification = await VerificationResource.CreateAsync(
|
||||
to: number,
|
||||
channel: "sms",
|
||||
pathServiceSid: Constants.TWILIO_SERVICE_SID
|
||||
);
|
||||
return verification.Sid;
|
||||
}
|
||||
|
||||
public async Task<bool> VerifyOTPAsync(string id, string code)
|
||||
{
|
||||
try
|
||||
{
|
||||
return (await VerificationCheckResource.CreateAsync(
|
||||
verificationSid: id,
|
||||
pathServiceSid: Constants.TWILIO_SERVICE_SID,
|
||||
code: code
|
||||
)).Status == "approved";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, "Error verifying OTP with Twilio");
|
||||
return false;
|
||||
}
|
||||
return (await VerificationCheckResource.CreateAsync(
|
||||
verificationSid: id,
|
||||
pathServiceSid: Constants.TWILIO_SERVICE_SID,
|
||||
code: code
|
||||
)).Status == "approved";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -34,12 +34,6 @@ namespace Streetwriters.Identity.Services
|
||||
var claims = await userManager.GetClaimsAsync(user);
|
||||
var marketingConsentClaim = claims.FirstOrDefault((claim) => claim.Type == $"{clientId}:marketing_consent");
|
||||
|
||||
if (await userManager.IsEmailConfirmedAsync(user) && !await userManager.GetTwoFactorEnabledAsync(user))
|
||||
{
|
||||
await mfaService.EnableMFAAsync(user, MFAMethods.Email);
|
||||
user = await userManager.FindByIdAsync(userId);
|
||||
ArgumentNullException.ThrowIfNull(user);
|
||||
}
|
||||
ArgumentNullException.ThrowIfNull(user.Email);
|
||||
|
||||
return new UserModel
|
||||
@@ -163,6 +157,7 @@ namespace Streetwriters.Identity.Services
|
||||
}
|
||||
else
|
||||
{
|
||||
await mfaService.EnableMFAAsync(user, MFAMethods.Email);
|
||||
if (userAgent != null) await userManager.AddClaimAsync(user, new Claim("platform", PlatformFromUserAgent(userAgent)));
|
||||
var code = await userManager.GenerateEmailConfirmationTokenAsync(user);
|
||||
var callbackUrl = UrlExtensions.TokenLink(user.Id.ToString(), code, client.Id, TokenType.CONFRIM_EMAIL);
|
||||
|
||||
@@ -504,6 +504,7 @@
|
||||
text-align: start;
|
||||
text-indent: 0px;
|
||||
text-transform: none;
|
||||
white-space: pre-wrap;
|
||||
widows: 2;
|
||||
word-spacing: 0px;
|
||||
-webkit-text-stroke-width: 0px;
|
||||
@@ -535,6 +536,7 @@
|
||||
text-align: start;
|
||||
text-indent: 0px;
|
||||
text-transform: none;
|
||||
white-space: pre-wrap;
|
||||
widows: 2;
|
||||
word-spacing: 0px;
|
||||
-webkit-text-stroke-width: 0px;
|
||||
@@ -565,6 +567,7 @@
|
||||
text-align: start;
|
||||
text-indent: 0px;
|
||||
text-transform: none;
|
||||
white-space: pre-wrap;
|
||||
widows: 2;
|
||||
word-spacing: 0px;
|
||||
-webkit-text-stroke-width: 0px;
|
||||
|
||||
@@ -309,6 +309,7 @@
|
||||
text-align: start;
|
||||
text-indent: 0px;
|
||||
text-transform: none;
|
||||
white-space: pre-wrap;
|
||||
widows: 2;
|
||||
word-spacing: 0px;
|
||||
-webkit-text-stroke-width: 0px;
|
||||
|
||||
@@ -401,6 +401,7 @@
|
||||
text-align: start;
|
||||
text-indent: 0px;
|
||||
text-transform: none;
|
||||
white-space: pre-wrap;
|
||||
word-spacing: 0px;
|
||||
-webkit-text-stroke-width: 0px;
|
||||
background-color: rgb(
|
||||
|
||||
@@ -467,6 +467,7 @@
|
||||
text-align: start;
|
||||
text-indent: 0px;
|
||||
text-transform: none;
|
||||
white-space: pre-wrap;
|
||||
widows: 2;
|
||||
word-spacing: 0px;
|
||||
-webkit-text-stroke-width: 0px;
|
||||
@@ -482,7 +483,9 @@
|
||||
display: inline;
|
||||
"
|
||||
><em
|
||||
>If you did not request to reset your account password, you can safely ignore this email.</em
|
||||
>If you did not request to reset
|
||||
your account password, you can
|
||||
safely ignore this email.</em
|
||||
></span
|
||||
>
|
||||
</div>
|
||||
@@ -551,6 +554,7 @@
|
||||
>
|
||||
<tbody>
|
||||
<tr>
|
||||
.
|
||||
<td
|
||||
style="
|
||||
padding: 18px 0px 18px 0px;
|
||||
|
||||
@@ -59,7 +59,6 @@ namespace Streetwriters.Identity.Validation
|
||||
|
||||
public string GrantType => Config.EMAIL_GRANT_TYPE;
|
||||
|
||||
|
||||
public async Task ValidateAsync(ExtensionGrantValidationContext context)
|
||||
{
|
||||
var email = context.Request.Raw["email"];
|
||||
@@ -76,8 +75,14 @@ namespace Streetwriters.Identity.Validation
|
||||
};
|
||||
|
||||
var isMultiFactor = await UserManager.GetTwoFactorEnabledAsync(user);
|
||||
if (!isMultiFactor)
|
||||
{
|
||||
context.Result.IsError = false;
|
||||
context.Result.Subject = await TokenGenerationService.TransformTokenRequestAsync(context.Request, user, GrantType, [Config.MFA_PASSWORD_GRANT_TYPE_SCOPE]);
|
||||
return;
|
||||
}
|
||||
|
||||
var primaryMethod = isMultiFactor ? MFAService.GetPrimaryMethod(user) : MFAMethods.Email;
|
||||
var primaryMethod = MFAService.GetPrimaryMethod(user);
|
||||
var secondaryMethod = MFAService.GetSecondaryMethod(user);
|
||||
var sendPhoneNumber = primaryMethod == MFAMethods.SMS || secondaryMethod == MFAMethods.SMS;
|
||||
|
||||
|
||||
@@ -18,49 +18,28 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
using System.Linq;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Lib.AspNetCore.ServerSentEvents;
|
||||
using System.Security.Claims;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Streetwriters.Messenger.Helpers
|
||||
{
|
||||
public class SSEHelper
|
||||
{
|
||||
public static async Task SendEventToUserAsync(string data, IServerSentEventsService sseService, string userId, string? originTokenId = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var clients = sseService.GetClients()
|
||||
.Where(c => c.User?.FindFirstValue("sub") == userId)
|
||||
.Where(c => originTokenId == null || c.User?.FindFirstValue("jti") != originTokenId);
|
||||
|
||||
await SendEventToClientsAsync(clients, data, cancellationToken);
|
||||
}
|
||||
|
||||
public static async Task SendEventToAllUsersAsync(string data, IServerSentEventsService sseService, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await SendEventToClientsAsync(sseService.GetClients(), data, cancellationToken);
|
||||
}
|
||||
|
||||
private static async Task SendEventToClientsAsync(IEnumerable<IServerSentEventsClient> clients, string data, CancellationToken cancellationToken)
|
||||
public static async Task SendEventToUserAsync(string data, IServerSentEventsService sseService, string userId, string? originTokenId = null)
|
||||
{
|
||||
var clients = sseService.GetClients().Where(c => c.User.FindFirstValue("sub") == userId);
|
||||
foreach (var client in clients)
|
||||
{
|
||||
if (originTokenId != null && client.User.FindFirstValue("jti") == originTokenId) continue;
|
||||
if (!client.IsConnected) continue;
|
||||
|
||||
try
|
||||
{
|
||||
await client.SendEventAsync(data, cancellationToken);
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
await client.SendEventAsync(data);
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task SendEventToAllUsersAsync(string data, IServerSentEventsService sseService)
|
||||
{
|
||||
await sseService.SendEventAsync(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,6 @@ using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Lib.AspNetCore.ServerSentEvents;
|
||||
using Streetwriters.Messenger.Helpers;
|
||||
using System.Text.Json;
|
||||
@@ -34,14 +33,12 @@ namespace Streetwriters.Messenger.Services
|
||||
private const string HEARTBEAT_MESSAGE_FORMAT = "Streetwriters Heartbeat ({0} UTC)";
|
||||
|
||||
private readonly IServerSentEventsService _serverSentEventsService;
|
||||
private readonly ILogger<HeartbeatService> _logger;
|
||||
#endregion
|
||||
|
||||
#region Constructor
|
||||
public HeartbeatService(IServerSentEventsService serverSentEventsService, ILogger<HeartbeatService> logger)
|
||||
public HeartbeatService(IServerSentEventsService serverSentEventsService)
|
||||
{
|
||||
_serverSentEventsService = serverSentEventsService;
|
||||
_logger = logger;
|
||||
}
|
||||
#endregion
|
||||
|
||||
@@ -50,28 +47,15 @@ namespace Streetwriters.Messenger.Services
|
||||
{
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
var message = JsonSerializer.Serialize(new
|
||||
{
|
||||
var message = JsonSerializer.Serialize(new
|
||||
type = "heartbeat",
|
||||
data = JsonSerializer.Serialize(new
|
||||
{
|
||||
type = "heartbeat",
|
||||
data = JsonSerializer.Serialize(new
|
||||
{
|
||||
t = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
|
||||
})
|
||||
});
|
||||
|
||||
await SSEHelper.SendEventToAllUsersAsync(message, _serverSentEventsService, stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Failed to send SSE heartbeat to one or more clients.");
|
||||
}
|
||||
|
||||
t = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
|
||||
})
|
||||
});
|
||||
await SSEHelper.SendEventToAllUsersAsync(message, _serverSentEventsService);
|
||||
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="DotNetEnv" Version="2.3.0" />
|
||||
<PackageReference Include="Lib.AspNetCore.ServerSentEvents" Version="9.1.0" />
|
||||
<PackageReference Include="Lib.AspNetCore.ServerSentEvents" Version="6.0.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.0"
|
||||
NoWarn="NU1605" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="5.0.0"
|
||||
|
||||
Reference in New Issue
Block a user