Skip to content
Merged
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
1 change: 1 addition & 0 deletions SolarWatch/Controllers/AuthController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ public AuthController(IAuthService authenticationService)
public async Task<ActionResult<AuthResponse>> RenewToken()
{
var token = Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
// do a validation for a valid / not blacklisted token
var result = await _authenticationService.RenewTokenAsync(token);

if (!result.Success)
Expand Down
4 changes: 2 additions & 2 deletions SolarWatch/Controllers/SolarWatchController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public SolarWatchController(ILogger<SolarWatchController> logger, ISolarDataServ
_solarDataService = solarDataService;
}

[HttpGet("GeocodingData"), /*Authorize(Roles = "User, Admin")*/]
[HttpGet("GeocodingData"), Authorize(Roles = "User, Admin")]
public async Task<ActionResult<GeocodingData>> GetGeocodingData([Required] string location)
{
try
Expand All @@ -35,7 +35,7 @@ public async Task<ActionResult<GeocodingData>> GetGeocodingData([Required] strin
}


[HttpGet("SolarData"), /*Authorize(Roles = "User, Admin")*/]
[HttpGet("SolarData"), Authorize(Roles = "User, Admin")]
public async Task<ActionResult<SolarData>> GetSolarData([Required] DateOnly date, [Required] string location)
{
try
Expand Down
7 changes: 6 additions & 1 deletion SolarWatch/Services/Authentication/AuthService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@ public class AuthService : IAuthService
{
private readonly UserManager<IdentityUser> _userManager;
private readonly ITokenService _tokenService;
private readonly ITokenBlacklistService _tokenBlacklistService;

public AuthService(UserManager<IdentityUser> userManager, ITokenService tokenService)
public AuthService(UserManager<IdentityUser> userManager, ITokenService tokenService, ITokenBlacklistService tokenBlacklistService)
{
_userManager = userManager;
_tokenService = tokenService;
_tokenBlacklistService = tokenBlacklistService;
}

public async Task<AuthResult> RegisterAsync(string email, string username, string password, string role)
Expand Down Expand Up @@ -92,6 +94,7 @@ private static AuthResult FailedRegistration(IdentityResult result, string email

public async Task<AuthResult> RenewTokenAsync(string token)
{

var principal = _tokenService.GetPrincipalFromExpiredToken(token);
if (principal == null)
{
Expand All @@ -111,6 +114,8 @@ public async Task<AuthResult> RenewTokenAsync(string token)
return NoRolesAssigned(user.Email, user.UserName);
}

_tokenBlacklistService.AddTokenToBlacklist(token);

var newToken = _tokenService.CreateToken(user, roles[0]); // roles[0] might fail if there are more roles / user
return new AuthResult(true, user.Email, user.UserName, newToken);
}
Expand Down
2 changes: 1 addition & 1 deletion SolarWatch/SolarWatch.csproj.user
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ActiveDebugProfile>https</ActiveDebugProfile>
<ActiveDebugProfile>http</ActiveDebugProfile>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebuggerFlavor>ProjectDebugger</DebuggerFlavor>
Expand Down
1 change: 1 addition & 0 deletions SolarWatch/SolarWatch.sln.DotSettings.user
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@
&lt;TestAncestor&gt;&#xD;
&lt;TestId&gt;NUnit3x::799DCF59-930B-4FF3-BF8D-EDF88B1AAEB7::net9.0::SolarWatchTests.SolarWatchControllerTests&lt;/TestId&gt;&#xD;
&lt;TestId&gt;xUnit::799DCF59-930B-4FF3-BF8D-EDF88B1AAEB7::net9.0::SolarWatchTests.IntegrationTests&lt;/TestId&gt;&#xD;
&lt;TestId&gt;xUnit::799DCF59-930B-4FF3-BF8D-EDF88B1AAEB7::net9.0::SolarWatchTests.IntegrationTestForAuth&lt;/TestId&gt;&#xD;
&lt;/TestAncestor&gt;&#xD;
&lt;/SessionState&gt;</s:String></wpf:ResourceDictionary>
53 changes: 49 additions & 4 deletions SolarWatchTests/IntegrationTests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.AspNetCore.Mvc.Testing;
Expand All @@ -10,17 +13,23 @@
using SolarWatch;
using Microsoft.AspNetCore.Hosting;
using SolarWatch.Context;
using SolarWatch.Contracts;
using SolarWatch.Controllers;
using Assert = Xunit.Assert;

namespace SolarWatchTests
{
[Collection("IntegrationTests")]
public class IntegrationTests : IClassFixture<WebApplicationFactory<Program>>
public class IntegrationTestForAuth : IDisposable
{
private readonly string _dbName = Guid.NewGuid().ToString();
private readonly HttpClient _client;
public HttpClient Client { get; }
public string Token { get; private set; }

public IntegrationTests(WebApplicationFactory<Program> factory)
public IntegrationTestForAuth()
{
var factory = new WebApplicationFactory<Program>();

var webAppFactory = factory.WithWebHostBuilder(builder =>
{
builder.UseEnvironment("Test");
Expand Down Expand Up @@ -52,9 +61,45 @@ public IntegrationTests(WebApplicationFactory<Program> factory)
});
});

_client = webAppFactory.CreateClient();
Client = webAppFactory.CreateClient();
RegisterTestUser().GetAwaiter().GetResult(); // register a new user before tests for [Authorize] to work
}

private async Task RegisterTestUser()
{
var newUser = new RegistrationRequest("testuser@test.com", "testuser", "testuser");
var response = await Client.PostAsJsonAsync("/Auth/Register", newUser);
response.EnsureSuccessStatusCode();

var login = await Client.PostAsJsonAsync("/Auth/Login", new AuthController.AuthRequest("testuser@test.com", "testuser"));
var token = await login.Content.ReadFromJsonAsync<AuthController.AuthResponse>();
Token = token.Token;

Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token);
}

public void Dispose() => Client.Dispose();
}

public class IntegrationTests : IClassFixture<IntegrationTestForAuth>
{

private readonly HttpClient _client;

public IntegrationTests(IntegrationTestForAuth setupAuth)
{
_client = setupAuth.Client;
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", setupAuth.Token);
}

[Fact]
public async Task LoginTest()
{

var testEndpoint = await _client.GetAsync("/Auth/testUser");

Assert.Equal(HttpStatusCode.OK, testEndpoint.StatusCode);
}

[Fact]
public async Task GetGeocodingData_ValidLocation_ReturnsOk()
Expand Down
2 changes: 1 addition & 1 deletion SolarWatch_Frontend/vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export default defineConfig({
port: 3000,
proxy: {
'/api': {
target: process.env.VITE_API_BASE_URL,// || 'https://localhost:7119', // remove .env file and it will work
target: /* process.env.VITE_API_BASE_URL */ 'http://localhost:5158', // remove .env file and it will work
changeOrigin: true,
secure: false, // DO NOT USE IN PRODUCTION. GET A VALID SSL CERTIFICATE
rewrite: (path) => path.replace(/^\/api/, '')
Expand Down
Loading