Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -1,29 +1,63 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Identity.Domain.DTOs;
using Identity.Domain.Interfaces;

namespace Identity.API.Controllers;

[ApiController]
[Route("api/[controller]")]
public class IdentityController : ControllerBase
{
private readonly ILogger<IdentityController> _logger;
private readonly IIdentityService _identityService;

public IdentityController(ILogger<IdentityController> logger)
public IdentityController(IIdentityService identityService)
{
_logger = logger;
_identityService = identityService;
}

[HttpGet]
public IActionResult GetAll()
[HttpPost("register")]
[ProducesResponseType(typeof(AppUserDto), StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Register([FromBody] RegisterRequest request)
{
// TODO: Implement — migrate logic from monolith's IdentityController
return Ok(new { service = "Identity", status = "scaffold" });
var result = await _identityService.RegisterAsync(request);
if (!result.Success)
return BadRequest(new { error = result.ErrorMessage });
return CreatedAtAction(nameof(GetById), new { id = result.User!.Id }, result.User);
}

[HttpGet("{id}")]
public IActionResult GetById(int id)
[HttpPost("login")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> Login([FromBody] LoginRequest request)
{
// TODO: Implement — migrate logic from monolith
return Ok(new { service = "Identity", id });
var result = await _identityService.LoginAsync(request);
if (!result.Success)
return Unauthorized(new { error = result.ErrorMessage });
return Ok(new { token = result.Token });
}

[HttpGet("users")]
[Authorize]
[ProducesResponseType(typeof(IEnumerable<AppUserDto>), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> GetUsers()
{
var users = await _identityService.GetAllUsersAsync();
return Ok(users);
}

[HttpGet("users/{id:guid}")]
[Authorize]
[ProducesResponseType(typeof(AppUserDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> GetById(Guid id)
{
var user = await _identityService.GetUserByIdAsync(id);
if (user == null)
return NotFound();
return Ok(user);
}
}
3 changes: 3 additions & 0 deletions src/Services/Identity/Identity.API/Identity.API.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@
<ProjectReference Include="..\..\Shared\Shared.Infrastructure\Shared.Infrastructure.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="BCrypt.Net-Next" Version="4.*" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.*" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.*" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="7.*" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.*" />
</ItemGroup>
</Project>
33 changes: 33 additions & 0 deletions src/Services/Identity/Identity.API/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Identity.Domain.Interfaces;
using Identity.Infrastructure.Data;
using Identity.Infrastructure.Services;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);
Expand All @@ -8,9 +13,34 @@
builder.Services.AddSwaggerGen();
builder.Services.AddHealthChecks();

// JWT Authentication
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Secret"]!))
};
});

builder.Services.AddAuthorization();

builder.Services.AddDbContext<IdentityDbContext>(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));

builder.Services.AddScoped<IIdentityService, IdentityService>();

var app = builder.Build();

using (var scope = app.Services.CreateScope())
Expand All @@ -25,6 +55,9 @@
app.UseSwaggerUI();
}

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();
app.MapHealthChecks("/healthz");

Expand Down
6 changes: 6 additions & 0 deletions src/Services/Identity/Identity.API/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,11 @@
},
"ConnectionStrings": {
"DefaultConnection": "Host=localhost;Database=identitydb;Username=postgres;Password=postgres"
},
"Jwt": {
"Secret": "QuickApp_Microservices_SuperSecret_Key_For_Dev_Only_Min_32_Chars!",
"Issuer": "quickapp-identity",
"Audience": "quickapp-api",
"ExpirationMinutes": 60
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@
<ProjectReference Include="..\Identity.Domain\Identity.Domain.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="BCrypt.Net-Next" Version="4.*" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.*" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="10.*" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.*" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.*" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Identity.Domain.DTOs;
using Identity.Domain.Entities;
using Identity.Domain.Interfaces;
using Identity.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;

namespace Identity.Infrastructure.Services;

public class IdentityService : IIdentityService
{
private readonly IdentityDbContext _context;
private readonly IConfiguration _configuration;

public IdentityService(IdentityDbContext context, IConfiguration configuration)
{
_context = context;
_configuration = configuration;
}

public async Task<RegisterResult> RegisterAsync(RegisterRequest request)
{
if (await _context.Users.AnyAsync(u => u.UserName == request.UserName))
{
return new RegisterResult { Success = false, ErrorMessage = "Username is already taken." };
}

if (await _context.Users.AnyAsync(u => u.Email == request.Email))
{
return new RegisterResult { Success = false, ErrorMessage = "Email is already registered." };
}

var user = new AppUser
{
Id = Guid.NewGuid(),
UserName = request.UserName,
Email = request.Email,
PasswordHash = BCrypt.Net.BCrypt.HashPassword(request.Password),
FullName = request.FullName,
JobTitle = request.JobTitle,
IsEnabled = true,
CreatedAt = DateTime.UtcNow,
UpdatedAt = DateTime.UtcNow
};

_context.Users.Add(user);
await _context.SaveChangesAsync();

return new RegisterResult
{
Success = true,
User = MapToDto(user)
};
}

public async Task<LoginResult> LoginAsync(LoginRequest request)
{
var user = await _context.Users.FirstOrDefaultAsync(u => u.UserName == request.UserName);

if (user == null || !BCrypt.Net.BCrypt.Verify(request.Password, user.PasswordHash))
{
return new LoginResult { Success = false, ErrorMessage = "Invalid username or password." };
}
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.

if (!user.IsEnabled)
{
return new LoginResult { Success = false, ErrorMessage = "This account has been disabled." };
}
Comment on lines +64 to +72

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚩 Login verifies password before checking if account is disabled

In LoginAsync, the BCrypt password verification (IdentityService.cs:64) runs before the IsEnabled check (IdentityService.cs:69). This means: (1) expensive BCrypt work is performed for disabled accounts unnecessarily, and (2) a correct password on a disabled account yields a different error message ('This account has been disabled') than an incorrect one ('Invalid username or password'), which reveals account state to the caller. This may be intentional UX, but if not, reversing the order (check IsEnabled first, then verify password) would be both more efficient and more uniform in error responses.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is intentional UX — a legitimate user whose account was disabled should see a clear "account disabled" message rather than a generic credentials error (which would lead them to think they mistyped their password). The information disclosure tradeoff is acceptable here since username enumeration is already possible via the register endpoint's uniqueness check. The BCrypt cost on disabled accounts is negligible in practice.


var token = GenerateJwtToken(user);

return new LoginResult { Success = true, Token = token };
}

public async Task<AppUserDto?> GetUserByIdAsync(Guid id)
{
var user = await _context.Users.FindAsync(id);
return user == null ? null : MapToDto(user);
}

public async Task<IEnumerable<AppUserDto>> GetAllUsersAsync()
{
var users = await _context.Users.ToListAsync();
return users.Select(MapToDto);
}
Comment on lines +85 to +89

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚩 GetAllUsersAsync loads entire user table into memory without pagination

The GetAllUsersAsync method at IdentityService.cs:82 calls ToListAsync() on the entire Users table with no pagination, filtering, or limit. As the user base grows, this will load all user records into memory in a single query. The GetUsers controller endpoint (IdentityController.cs:46-49) is protected by [Authorize] but not by any role restriction, so any authenticated user can trigger this. This could become a performance concern at scale.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Acknowledged — this is a known limitation for now. Pagination would require changes to the IIdentityService interface in the Domain layer (which is out of scope for T3 per the task constraints). Can be addressed in a follow-up task.


private string GenerateJwtToken(AppUser user)
{
var secret = _configuration["Jwt:Secret"]!;
var issuer = _configuration["Jwt:Issuer"];
var audience = _configuration["Jwt:Audience"];
var expirationMinutes = int.Parse(_configuration["Jwt:ExpirationMinutes"]!);

var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
new Claim(JwtRegisteredClaimNames.Name, user.UserName),
new Claim(JwtRegisteredClaimNames.Email, user.Email),
new Claim(ClaimTypes.Role, "User")
};

var token = new JwtSecurityToken(
issuer: issuer,
audience: audience,
claims: claims,
expires: DateTime.UtcNow.AddMinutes(expirationMinutes),
signingCredentials: credentials);

return new JwtSecurityTokenHandler().WriteToken(token);
}

private static AppUserDto MapToDto(AppUser user)
{
return new AppUserDto
{
Id = user.Id,
UserName = user.UserName,
Email = user.Email,
FullName = user.FullName,
JobTitle = user.JobTitle,
IsEnabled = user.IsEnabled
};
}
}