Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Authentication for the user endpoints and their tests. #127

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Giraf.IntegrationTests/Endpoints/ActivityEndpointTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,7 @@ public async Task UpdateActivity_ReturnsOk_WhenActivityExists()
StartTime: TimeOnly.FromDateTime(DateTime.UtcNow),
EndTime: TimeOnly.FromDateTime(DateTime.UtcNow.AddHours(1)),
IsCompleted: true,
PictogramId: null,
PictogramId: 1,
CitizenId: 1
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ public async Task GetOrganizationInvitation_ReturnsNotFound_WhenNoValidSenderExi

#endregion

#region Post Invitation - Tests 12-13
#region Post Invitation - Tests 12-13

[Fact]
//12. Succesfully posts a new invitation
Expand Down
19 changes: 16 additions & 3 deletions Giraf.IntegrationTests/Endpoints/OrganizationEndpointTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using GirafAPI.Entities.Organizations.DTOs;
using GirafAPI.Entities.Users;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

Expand Down Expand Up @@ -121,7 +122,7 @@ public async Task GetOrganizationById_ReturnsNotFound_WhenOrganizationDoesNotExi
#region Create Organization Tests

// 5. Test POST /organizations to create a new organization
[Fact]
[HttpPost][Fact]
public async Task PostOrganization_ReturnsCreated_WhenUserIsValid()
{
// Arrange
Expand All @@ -130,27 +131,39 @@ public async Task PostOrganization_ReturnsCreated_WhenUserIsValid()

using var scope = factory.Services.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<GirafDbContext>();

// Fetch a user from the database and assert it's not null
var user = await dbContext.Users.FirstOrDefaultAsync();
Assert.NotNull(user);
Assert.IsType<GirafUser>(user);

// Set up the test claims
TestAuthHandler.TestClaims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, user.Id)
};
Assert.Contains(TestAuthHandler.TestClaims, c => c.Type == ClaimTypes.NameIdentifier && c.Value == user.Id);

// Create DTO for the new organization
var newOrgDto = new CreateOrganizationDTO { Name = "New Organization" };
Assert.NotNull(newOrgDto);
Assert.Equal("New Organization", newOrgDto.Name); // Verify DTO has the correct name

// Act
var response = await client.PostAsJsonAsync($"/organizations", newOrgDto);
var response = await client.PostAsJsonAsync("/organizations", newOrgDto);

// Assert
response.EnsureSuccessStatusCode();
response.EnsureSuccessStatusCode(); // Ensure the response is successful
var createdOrganization = await response.Content.ReadFromJsonAsync<OrganizationDTO>();
Assert.NotNull(createdOrganization);
Assert.Equal("New Organization", createdOrganization.Name);

// Additional checks to verify created organization structure
Assert.IsType<OrganizationDTO>(createdOrganization);
Assert.NotEmpty(createdOrganization.Name);
}


// 6. Test POST /organizations when user does not exist
[Fact]
public async Task PostOrganization_ReturnsBadRequest_WhenUserDoesNotExist()
Expand Down
157 changes: 150 additions & 7 deletions Giraf.IntegrationTests/Endpoints/PictogramEndpointTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@
using Giraf.IntegrationTests.Utils;
using Giraf.IntegrationTests.Utils.DbSeeders;
using GirafAPI.Data;
using GirafAPI.Entities.Pictograms;
using GirafAPI.Entities.Pictograms.DTOs;
using GirafAPI.Entities.Users;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
Expand All @@ -28,11 +31,39 @@ public async Task CreatePictogram_ReturnsOk_WhenPictogramIsValid()
using (var scope = factory.Services.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<GirafDbContext>();
var organization = await context.Organizations.FirstOrDefaultAsync();
var organization = await context.Organizations
.Include(o => o.Users)
.FirstOrDefaultAsync();
Assert.NotNull(organization);
organizationId = organization.Id;

// Create and associate the test user
var testUser = new GirafUser
{
Id = "test-user-id",
UserName = "testuser",
FirstName = "Test",
LastName = "User",
Email = "[email protected]",
NormalizedUserName = "TESTUSER",
NormalizedEmail = "[email protected]",
PasswordHash = "TestPasswordHash",
SecurityStamp = Guid.NewGuid().ToString(),
ConcurrencyStamp = Guid.NewGuid().ToString()
};

organization.Users.Add(testUser);
context.Users.Add(testUser);
await context.SaveChangesAsync();
}

// Set up the test claims
TestAuthHandler.TestClaims = new List<Claim>
{
new(ClaimTypes.NameIdentifier, "test-user-id"),
new("OrgMember", organizationId.ToString())
};

// Prepare multipart form data
var formData = new MultipartFormDataContent();

Expand Down Expand Up @@ -124,6 +155,13 @@ public async Task CreatePictogram_ReturnsBadRequest_WhenPictogramNameIsMissing()
organizationId = organization.Id;
}

// Set up the test claims
TestAuthHandler.TestClaims = new List<Claim>
{
new(ClaimTypes.NameIdentifier, "test-user-id"),
new("OrgMember", organizationId.ToString())
};

// Prepare multipart form data without pictogramName
var formData = new MultipartFormDataContent();

Expand Down Expand Up @@ -154,15 +192,25 @@ public async Task GetPictogramById_ReturnsPictogram_WhenPictogramExists()
var client = factory.CreateClient();

int pictogramId;
int organizationId;

using (var scope = factory.Services.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<GirafDbContext>();
var pictogram = await context.Pictograms.FirstOrDefaultAsync();
var organization = await context.Organizations.FirstOrDefaultAsync();
Assert.NotNull(pictogram);
pictogramId = pictogram.Id;
organizationId = organization.Id;
}

// Set up the test claims
TestAuthHandler.TestClaims = new List<Claim>
{
new(ClaimTypes.NameIdentifier, "test-user-id"),
new("OrgMember", organizationId.ToString())
};

// Act
var response = await client.GetAsync($"/pictograms/{pictogramId}");

Expand All @@ -177,9 +225,25 @@ public async Task GetPictogramById_ReturnsPictogram_WhenPictogramExists()
public async Task GetPictogramById_ReturnsNotFound_WhenPictogramDoesNotExist()
{
// Arrange
var factory = new GirafWebApplicationFactory(_ => new EmptyDb());
var factory = new GirafWebApplicationFactory(_ => new BasicOrganizationSeeder());
var client = factory.CreateClient();
int nonExistentPictogramId = 9999;
int organizationId;

using (var scope = factory.Services.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<GirafDbContext>();
var organization = await context.Organizations.FirstOrDefaultAsync();
organizationId = organization.Id;
}

// Set up the test claims
TestAuthHandler.TestClaims = new List<Claim>
{
new(ClaimTypes.NameIdentifier, "test-user-id"),
new("OrgMember", organizationId.ToString())
};


// Act
var response = await client.GetAsync($"/pictograms/{nonExistentPictogramId}");
Expand Down Expand Up @@ -209,6 +273,14 @@ public async Task GetPictogramsByOrganizationId_ReturnsPictograms_WhenPictograms

var currentPage = 1;
var pageSize = 10;

// Set up the test claims
TestAuthHandler.TestClaims = new List<Claim>
{
new(ClaimTypes.NameIdentifier, "test-user-id"),
new("OrgMember", organizationId.ToString())
};


// Act
var response = await client.GetAsync($"/pictograms/organizationId:int?organizationId={organizationId}&currentPage={currentPage}&pageSize={pageSize}");
Expand Down Expand Up @@ -240,12 +312,15 @@ public async Task GetPictogramsByOrganizationId_ReturnsEmptyList_WhenNoPictogram
// Set up the test claims
TestAuthHandler.TestClaims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, "test-user-id"),
new Claim("OrgMember", organizationId.ToString())
new(ClaimTypes.NameIdentifier, "test-user-id"),
new("OrgMember", organizationId.ToString())
};

var currentPage = 1;
var pageSize = 10;

// Act
var response = await client.GetAsync($"/pictograms/organization/{organizationId}");
var response = await client.GetAsync($"/pictograms/organizationId:int?organizationId={organizationId}&currentPage={currentPage}&pageSize={pageSize}");

// Assert
response.EnsureSuccessStatusCode();
Expand All @@ -258,23 +333,76 @@ public async Task GetPictogramsByOrganizationId_ReturnsEmptyList_WhenNoPictogram

#region Delete Pictogram Tests

[Fact]
[HttpDelete][Fact]
public async Task DeletePictogram_ReturnsOk_WhenPictogramExists()
{
// Arrange
var factory = new GirafWebApplicationFactory(_ => new BasicPictogramSeeder());
var client = factory.CreateClient();

int pictogramId;
int organizationId;

using (var scope = factory.Services.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<GirafDbContext>();

// Fetch an organization and verify its existence
var organization = await context.Organizations
.Include(o => o.Users)
.FirstOrDefaultAsync();
Assert.NotNull(organization);

organizationId = organization.Id;
Assert.True(organizationId > 0, "Organization ID should be a positive integer.");

// Fetch a pictogram and verify its existence
var pictogram = await context.Pictograms.FirstOrDefaultAsync();
Assert.NotNull(pictogram);
pictogramId = pictogram.Id;
Assert.True(pictogramId > 0, "Pictogram ID should be a positive integer.");
Assert.Equal(organizationId, pictogram.OrganizationId);

// Create and associate the test user
var testUser = new GirafUser
{
Id = "test-user-id",
UserName = "testuser",
FirstName = "Test",
LastName = "User",
Email = "[email protected]",
NormalizedUserName = "TESTUSER",
NormalizedEmail = "[email protected]",
PasswordHash = "TestPasswordHash",
SecurityStamp = Guid.NewGuid().ToString(),
ConcurrencyStamp = Guid.NewGuid().ToString()
};
Assert.NotNull(testUser);
Assert.Equal("test-user-id", testUser.Id);

organization.Users.Add(testUser);
context.Users.Add(testUser);
context.Organizations.Update(organization);
await context.SaveChangesAsync();

Assert.NotEmpty(organization.Users);

// Verify user was added
var tester = await context.Users.FirstOrDefaultAsync(u => u.Id == "test-user-id");
Assert.NotNull(tester);
Assert.Equal("test-user-id", tester.Id);
Assert.Equal("[email protected]", tester.Email);
}

// Set up the test claims
TestAuthHandler.TestClaims = new List<Claim>
{
new(ClaimTypes.NameIdentifier, "test-user-id"),
new("OrgMember", organizationId.ToString())
};
Assert.Contains(TestAuthHandler.TestClaims, c => c.Type == ClaimTypes.NameIdentifier && c.Value == "test-user-id");
Assert.Contains(TestAuthHandler.TestClaims, c => c.Type == "OrgMember" && c.Value == organizationId.ToString());

// Act
var response = await client.DeleteAsync($"/pictograms/{pictogramId}");

Expand All @@ -294,10 +422,25 @@ public async Task DeletePictogram_ReturnsOk_WhenPictogramExists()
public async Task DeletePictogram_ReturnsNotFound_WhenPictogramDoesNotExist()
{
// Arrange
var factory = new GirafWebApplicationFactory(_ => new EmptyDb());
var factory = new GirafWebApplicationFactory(_ => new BasicOrganizationSeeder());
var client = factory.CreateClient();

int nonExistentPictogramId = 9999;
int organizationId;

using (var scope = factory.Services.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<GirafDbContext>();
var organization = await context.Organizations.FirstOrDefaultAsync();
organizationId = organization.Id;
}

// Set up the test claims
TestAuthHandler.TestClaims = new List<Claim>
{
new(ClaimTypes.NameIdentifier, "test-user-id"),
new("OrgMember", organizationId.ToString())
};

// Act
var response = await client.DeleteAsync($"/pictograms/{nonExistentPictogramId}");
Expand Down
Loading
Loading