feat(api): validate account institution is connected and allow adding new account
This commit is contained in:
@@ -1,3 +1,5 @@
|
||||
using FiscalOS.Core.Accounts;
|
||||
|
||||
namespace FiscalOS.API.Accounts.Add;
|
||||
|
||||
internal static class Endpoint
|
||||
@@ -19,6 +21,7 @@ internal static class Endpoint
|
||||
var userId = httpContext.GetUserId();
|
||||
|
||||
var user = await appDbContext.Users
|
||||
.Include(u => u.Institutions.Where(i => i.Metadata is PlaidMetadata && ((PlaidMetadata)i.Metadata).PlaidId == request.PlaidInstitutionId))
|
||||
.Include(u => u.Accounts.Where(a => a.Metadata is PlaidAccountMetadata && ((PlaidAccountMetadata)a.Metadata).PlaidId == request.PlaidAccountId))
|
||||
.ThenInclude(a => a.Metadata)
|
||||
.SingleOrDefaultAsync(u => u.Id == userId, ct);
|
||||
@@ -28,13 +31,24 @@ internal static class Endpoint
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
|
||||
if (user.Institutions.Any() is false)
|
||||
{
|
||||
return Results.ValidationProblem(new Dictionary<string, string[]>
|
||||
{
|
||||
["PlaidInstitutionId"] = ["The PlaidInstitutionId field is invalid. No institution connected with the given PlaidInstitutionId was found for the user."],
|
||||
});
|
||||
}
|
||||
|
||||
if (user.Accounts.Any())
|
||||
{
|
||||
return Results.Conflict();
|
||||
}
|
||||
|
||||
// TODO: This is new account
|
||||
// so we should add to the database
|
||||
var accountMetadata = PlaidAccountMetadata.From(request.PlaidAccountId, request.PlaidAccountName);
|
||||
var account = Account.From(user.Institutions.First().Id, request.PlaidAccountName, accountMetadata);
|
||||
user.AddAccount(account);
|
||||
|
||||
await appDbContext.SaveChangesAsync(ct);
|
||||
|
||||
return Results.Ok();
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ public record Request : IValidatableObject
|
||||
{
|
||||
public string PlaidInstitutionId { get; init; } = string.Empty;
|
||||
public string PlaidAccountId { get; init; } = string.Empty;
|
||||
public string PlaidAccountName { get; init; } = string.Empty;
|
||||
|
||||
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
|
||||
{
|
||||
@@ -19,5 +20,11 @@ public record Request : IValidatableObject
|
||||
var fieldName = nameof(PlaidAccountId);
|
||||
yield return new($"The {fieldName} field is required.", [fieldName]);
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(PlaidAccountName))
|
||||
{
|
||||
var fieldName = nameof(PlaidAccountName);
|
||||
yield return new($"The {fieldName} field is required.", [fieldName]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
using Institution = FiscalOS.Core.Accounts.Institution;
|
||||
using Account = FiscalOS.Core.Accounts.Account;
|
||||
using Institution = FiscalOS.Core.Accounts.Institution;
|
||||
|
||||
namespace FiscalOS.API.Tests.Integration;
|
||||
|
||||
@@ -16,7 +16,7 @@ public class AddTests(TestApi testApi) : IntegrationTest(testApi)
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Add_WhenCalledWithoutInstitutionIdOrAccountId_ItShouldReturn400WithProblemDetails()
|
||||
public async Task Add_WhenCalledWithoutInstitutionIdOrAccountIdOrAccountName_ItShouldReturn400WithProblemDetails()
|
||||
{
|
||||
var jwt = JwtTokenBuilder.New()
|
||||
.WithClaim(JwtRegisteredClaimNames.Sub, Guid.NewGuid().ToString())
|
||||
@@ -35,6 +35,7 @@ public class AddTests(TestApi testApi) : IntegrationTest(testApi)
|
||||
{
|
||||
["PlaidInstitutionId"] = ["The PlaidInstitutionId field is required."],
|
||||
["PlaidAccountId"] = ["The PlaidAccountId field is required."],
|
||||
["PlaidAccountName"] = ["The PlaidAccountName field is required."],
|
||||
});
|
||||
}
|
||||
|
||||
@@ -45,7 +46,12 @@ public class AddTests(TestApi testApi) : IntegrationTest(testApi)
|
||||
.WithClaim(JwtRegisteredClaimNames.Sub, Guid.NewGuid().ToString())
|
||||
.Build();
|
||||
|
||||
using var content = new StringContent(JsonSerializer.Serialize(new { plaidAccountId = "accountId" }), Encoding.UTF8, "application/json");
|
||||
var json = JsonSerializer.Serialize(new
|
||||
{
|
||||
plaidAccountId = "accountId",
|
||||
plaidAccountName = "Some Account",
|
||||
});
|
||||
using var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, AddUri)
|
||||
{
|
||||
Content = content
|
||||
@@ -67,7 +73,12 @@ public class AddTests(TestApi testApi) : IntegrationTest(testApi)
|
||||
.WithClaim(JwtRegisteredClaimNames.Sub, Guid.NewGuid().ToString())
|
||||
.Build();
|
||||
|
||||
using var content = new StringContent(JsonSerializer.Serialize(new { plaidInstitutionId = "institutionId" }), Encoding.UTF8, "application/json");
|
||||
var json = JsonSerializer.Serialize(new
|
||||
{
|
||||
plaidInstitutionId = "institutionId",
|
||||
plaidAccountName = "Some Account",
|
||||
});
|
||||
using var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, AddUri)
|
||||
{
|
||||
Content = content
|
||||
@@ -82,6 +93,33 @@ public class AddTests(TestApi testApi) : IntegrationTest(testApi)
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Add_WhenCalledWithoutAccountName_ItShouldReturn400WithProblemDetails()
|
||||
{
|
||||
var jwt = JwtTokenBuilder.New()
|
||||
.WithClaim(JwtRegisteredClaimNames.Sub, Guid.NewGuid().ToString())
|
||||
.Build();
|
||||
|
||||
var json = JsonSerializer.Serialize(new
|
||||
{
|
||||
plaidInstitutionId = "institutionId",
|
||||
plaidAccountId = "accountId",
|
||||
});
|
||||
using var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, AddUri)
|
||||
{
|
||||
Content = content
|
||||
};
|
||||
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", jwt);
|
||||
|
||||
var response = await Client.SendAsync(request, TestContext.Current.CancellationToken);
|
||||
|
||||
await response.Should().BeValidationProblemDetails(new Dictionary<string, string[]>()
|
||||
{
|
||||
["PlaidAccountName"] = ["The PlaidAccountName field is required."],
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Add_WhenCalledWithNonExistentUser_ItShouldReturn401WithProblemDetails()
|
||||
{
|
||||
@@ -93,6 +131,7 @@ public class AddTests(TestApi testApi) : IntegrationTest(testApi)
|
||||
{
|
||||
plaidInstitutionId = "id",
|
||||
plaidAccountId = "id",
|
||||
plaidAccountName = "Some Account",
|
||||
});
|
||||
using var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, AddUri)
|
||||
@@ -106,6 +145,48 @@ public class AddTests(TestApi testApi) : IntegrationTest(testApi)
|
||||
await response.Should().BeProblemDetails(HttpStatusCode.Unauthorized);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Add_WhenCalledWithPlaidInstitutionIdThatHasNotBeenAdded_ItShouldReturn400WithProblemDetails()
|
||||
{
|
||||
var user = await ExecuteAsync(static async (context, ct, sp) =>
|
||||
{
|
||||
var passwordHasher = sp.GetRequiredService<IPasswordHasher>();
|
||||
var encryptor = sp.GetRequiredService<IEncryptor>();
|
||||
|
||||
var userEncryptionKey = await encryptor.GenerateEncryptedKeyAsync(ct);
|
||||
var user = User.From("User1", passwordHasher.Hash("@Password1"), userEncryptionKey);
|
||||
|
||||
|
||||
await context.AddAsync(user, ct);
|
||||
await context.SaveChangesAsync(ct);
|
||||
return user;
|
||||
}, TestContext.Current.CancellationToken);
|
||||
|
||||
var jwt = JwtTokenBuilder.New()
|
||||
.WithClaim(JwtRegisteredClaimNames.Sub, user.Id.ToString())
|
||||
.Build();
|
||||
|
||||
var json = JsonSerializer.Serialize(new
|
||||
{
|
||||
plaidInstitutionId = "id",
|
||||
plaidAccountId = "id",
|
||||
plaidAccountName = "Some Account",
|
||||
});
|
||||
using var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, AddUri)
|
||||
{
|
||||
Content = content,
|
||||
};
|
||||
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", jwt);
|
||||
|
||||
var response = await Client.SendAsync(request, TestContext.Current.CancellationToken);
|
||||
|
||||
await response.Should().BeValidationProblemDetails(new Dictionary<string, string[]>()
|
||||
{
|
||||
["PlaidInstitutionId"] = ["The PlaidInstitutionId field is invalid. No institution connected with the given PlaidInstitutionId was found for the user."],
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Add_WhenCalledWithPlaidAccountIdThatHasAlreadyBeenAdded_ItShouldReturn409WithProblemDetails()
|
||||
{
|
||||
@@ -143,6 +224,7 @@ public class AddTests(TestApi testApi) : IntegrationTest(testApi)
|
||||
{
|
||||
plaidInstitutionId = ((PlaidMetadata)institution.Metadata).PlaidId,
|
||||
plaidAccountId = ((PlaidAccountMetadata)account.Metadata).PlaidId,
|
||||
plaidAccountName = ((PlaidAccountMetadata)account.Metadata).PlaidName,
|
||||
});
|
||||
using var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, AddUri)
|
||||
@@ -155,4 +237,68 @@ public class AddTests(TestApi testApi) : IntegrationTest(testApi)
|
||||
|
||||
await response.Should().BeProblemDetails(HttpStatusCode.Conflict);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Add_WhenCalledWithNewAccount_ItShouldReturn200()
|
||||
{
|
||||
var (user, institution) = await ExecuteAsync(async (context, ct, sp) =>
|
||||
{
|
||||
var passwordHasher = sp.GetRequiredService<IPasswordHasher>();
|
||||
var encryptor = sp.GetRequiredService<IEncryptor>();
|
||||
var plaidClient = sp.GetRequiredService<PlaidClient>();
|
||||
|
||||
var userEncryptionKey = await encryptor.GenerateEncryptedKeyAsync(ct);
|
||||
var user = User.From("User1", passwordHasher.Hash("@Password1"), userEncryptionKey);
|
||||
|
||||
var encryptedAccessToken = await encryptor.EncryptAsyncFor(user, "accessToken", ct);
|
||||
var plaidMetadata = PlaidMetadata.From("id", "Some Bank", encryptedAccessToken);
|
||||
var institution = Institution.From("Some Bank", plaidMetadata);
|
||||
|
||||
user.AddInstitution(institution);
|
||||
|
||||
await context.AddAsync(user, ct);
|
||||
await context.SaveChangesAsync(ct);
|
||||
return (user, institution);
|
||||
}, TestContext.Current.CancellationToken);
|
||||
|
||||
var jwt = JwtTokenBuilder.New()
|
||||
.WithClaim(JwtRegisteredClaimNames.Sub, user.Id.ToString())
|
||||
.Build();
|
||||
|
||||
var newAccountId = "newAccountId";
|
||||
var newAccountName = "New Account";
|
||||
|
||||
var json = JsonSerializer.Serialize(new
|
||||
{
|
||||
plaidInstitutionId = ((PlaidMetadata)institution.Metadata).PlaidId,
|
||||
plaidAccountId = newAccountId,
|
||||
plaidAccountName = newAccountName,
|
||||
});
|
||||
using var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, AddUri)
|
||||
{
|
||||
Content = content,
|
||||
};
|
||||
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", jwt);
|
||||
|
||||
var response = await Client.SendAsync(request, TestContext.Current.CancellationToken);
|
||||
|
||||
response.StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
|
||||
var updatedUser = await ExecuteAsync(
|
||||
async (context, ct) => await context.Set<User>()
|
||||
.Include(u => u.Accounts)
|
||||
.ThenInclude(a => a.Metadata)
|
||||
.FirstAsync(u => u.Id == user.Id, ct),
|
||||
TestContext.Current.CancellationToken
|
||||
);
|
||||
|
||||
updatedUser.Accounts.Should().ContainSingle(
|
||||
a => a.Name == newAccountName &&
|
||||
a.InstitutionId == institution.Id &&
|
||||
a.Metadata is PlaidAccountMetadata &&
|
||||
((PlaidAccountMetadata)a.Metadata).PlaidId == newAccountId &&
|
||||
((PlaidAccountMetadata)a.Metadata).PlaidName == newAccountName
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user