Skip to content

Commit aa461db

Browse files
ok auth
1 parent f6ad20f commit aa461db

File tree

10 files changed

+315
-2
lines changed

10 files changed

+315
-2
lines changed

Controllers/ProjectController.cs

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
using Microsoft.AspNetCore.Authorization;
2+
using Microsoft.AspNetCore.Mvc;
3+
using PaymentCoreServiceApi.Services;
4+
5+
namespace PaymentCoreServiceApi.Controllers;
6+
7+
[ApiController]
8+
[Route("api/[controller]")]
9+
[Authorize]
10+
public class ProjectController : ControllerBase
11+
{
12+
private readonly ICurrentUser _currentUser;
13+
14+
public ProjectController(ICurrentUser currentUser)
15+
{
16+
_currentUser = currentUser;
17+
}
18+
19+
[HttpGet("my-projects")]
20+
public IActionResult GetUserProjects()
21+
{
22+
// Simulate getting projects for the current user
23+
var userProjects = new[]
24+
{
25+
new {
26+
Id = 1,
27+
Name = "Project A",
28+
OwnerId = _currentUser.Id,
29+
OwnerName = _currentUser.UserName,
30+
CreatedAt = DateTime.UtcNow.AddDays(-5)
31+
},
32+
new {
33+
Id = 2,
34+
Name = "Project B",
35+
OwnerId = _currentUser.Id,
36+
OwnerName = _currentUser.UserName,
37+
CreatedAt = DateTime.UtcNow.AddDays(-2)
38+
}
39+
};
40+
41+
return Ok(new
42+
{
43+
UserId = _currentUser.Id,
44+
UserEmail = _currentUser.Email,
45+
Projects = userProjects
46+
});
47+
}
48+
49+
[HttpGet("{projectId}")]
50+
public IActionResult GetProjectById(int projectId)
51+
{
52+
// Simulate getting a specific project with validation
53+
if (!_currentUser.IsAuthenticated)
54+
{
55+
return Unauthorized();
56+
}
57+
58+
// Simulate project data (in real app, this would come from a database)
59+
var project = new
60+
{
61+
Id = projectId,
62+
Name = $"Project {projectId}",
63+
Description = "Project description here",
64+
OwnerId = _currentUser.Id,
65+
OwnerName = _currentUser.UserName,
66+
OwnerEmail = _currentUser.Email,
67+
CreatedAt = DateTime.UtcNow,
68+
Status = "Active",
69+
Members = new[]
70+
{
71+
new { Id = _currentUser.Id, Name = _currentUser.UserName, Role = "Owner" }
72+
}
73+
};
74+
75+
return Ok(project);
76+
}
77+
78+
[HttpPost("create")]
79+
public IActionResult CreateProject([FromBody] CreateProjectRequest request)
80+
{
81+
if (!ModelState.IsValid)
82+
{
83+
return BadRequest(ModelState);
84+
}
85+
86+
// Simulate creating a new project
87+
var newProject = new
88+
{
89+
Id = new Random().Next(100, 999), // Simulate generated ID
90+
Name = request.Name,
91+
Description = request.Description,
92+
OwnerId = _currentUser.Id,
93+
OwnerName = _currentUser.UserName,
94+
CreatedAt = DateTime.UtcNow,
95+
Status = "Active"
96+
};
97+
98+
return CreatedAtAction(nameof(GetProjectById), new { projectId = newProject.Id }, newProject);
99+
}
100+
}
101+
102+
public class CreateProjectRequest
103+
{
104+
public string Name { get; set; } = string.Empty;
105+
public string Description { get; set; } = string.Empty;
106+
}

Controllers/TestController.cs

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
using Microsoft.AspNetCore.Authorization;
2+
using Microsoft.AspNetCore.Mvc;
3+
using PaymentCoreServiceApi.Services;
4+
5+
namespace PaymentCoreServiceApi.Controllers;
6+
7+
[ApiController]
8+
[Route("api/[controller]")]
9+
[Authorize]
10+
public class TestController : ControllerBase
11+
{
12+
private readonly ICurrentUser _currentUser;
13+
14+
public TestController(ICurrentUser currentUser)
15+
{
16+
_currentUser = currentUser;
17+
}
18+
19+
[HttpGet("current-user")]
20+
public IActionResult GetCurrentUserInfo()
21+
{
22+
var userInfo = new
23+
{
24+
UserId = _currentUser.Id,
25+
Username = _currentUser.UserName,
26+
Email = _currentUser.Email,
27+
IsAuthenticated = _currentUser.IsAuthenticated
28+
};
29+
30+
return Ok(userInfo);
31+
}
32+
33+
[HttpGet("protected-resource")]
34+
public IActionResult GetProtectedResource()
35+
{
36+
if (!_currentUser.IsAuthenticated)
37+
{
38+
return Unauthorized();
39+
}
40+
41+
return Ok(new
42+
{
43+
Message = $"This is protected data for user: {_currentUser.UserName}",
44+
UserId = _currentUser.Id,
45+
Timestamp = DateTime.UtcNow
46+
});
47+
}
48+
}

Controllers/UsersController.cs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
using Microsoft.AspNetCore.Authorization;
33
using Microsoft.AspNetCore.Mvc;
44
using PaymentCoreServiceApi.Features.Users.Commands;
5+
using PaymentCoreServiceApi.Features.Users.Queries;
56

67
namespace PaymentCoreServiceApi.Controllers;
78

@@ -24,4 +25,11 @@ public async Task<IActionResult> Create([FromBody] CreateUserCommand command)
2425
var user = await _mediator.Send(command);
2526
return Ok(user);
2627
}
28+
29+
[HttpGet("profile")]
30+
public async Task<IActionResult> GetProfile()
31+
{
32+
var profile = await _mediator.Send(new GetUserProfileQuery());
33+
return Ok(profile);
34+
}
2735
}

Features/Auth/Commands/LoginCommandHandler.cs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,25 @@
11
using MediatR;
22
using Microsoft.EntityFrameworkCore;
3+
using PaymentCoreServiceApi.Core.Interfaces.Repositories.Write;
34
using PaymentCoreServiceApi.Infrastructure.DbContexts;
5+
using PaymentCoreServiceApi.Services;
46

57
namespace PaymentCoreServiceApi.Features.Auth.Commands;
68

79
public class LoginCommandHandler : IRequestHandler<LoginCommand, LoginResponse>
810
{
911
private readonly AppDbContext _context;
1012
private readonly IJwtService _jwtService;
13+
private readonly ICurrentUser _currentUser;
1114

12-
public LoginCommandHandler(AppDbContext context, IJwtService jwtService)
15+
public LoginCommandHandler(
16+
AppDbContext context,
17+
IJwtService jwtService,
18+
ICurrentUser currentUser)
1319
{
1420
_context = context;
1521
_jwtService = jwtService;
22+
_currentUser = currentUser;
1623
}
1724

1825
public async Task<LoginResponse> Handle(LoginCommand request, CancellationToken cancellationToken)
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
using MediatR;
2+
using Microsoft.EntityFrameworkCore;
3+
using PaymentCoreServiceApi.Infrastructure.DbContexts;
4+
using PaymentCoreServiceApi.Services;
5+
6+
namespace PaymentCoreServiceApi.Features.Users.Queries;
7+
8+
public class GetUserProfileQuery : IRequest<UserProfileResponse>
9+
{
10+
// Empty because we'll get the user ID from the current context
11+
}
12+
13+
public class UserProfileResponse
14+
{
15+
public string Id { get; set; } = string.Empty;
16+
public string UserName { get; set; } = string.Empty;
17+
public string Email { get; set; } = string.Empty;
18+
public DateTime LastLogin { get; set; }
19+
public int ProjectsCount { get; set; }
20+
}
21+
22+
public class GetUserProfileQueryHandler : IRequestHandler<GetUserProfileQuery, UserProfileResponse>
23+
{
24+
private readonly AppDbContext _context;
25+
private readonly ICurrentUser _currentUser;
26+
27+
public GetUserProfileQueryHandler(
28+
AppDbContext context,
29+
ICurrentUser currentUser)
30+
{
31+
_context = context;
32+
_currentUser = currentUser;
33+
}
34+
35+
public async Task<UserProfileResponse> Handle(GetUserProfileQuery request, CancellationToken cancellationToken)
36+
{
37+
if (!_currentUser.IsAuthenticated)
38+
{
39+
throw new UnauthorizedAccessException("User is not authenticated");
40+
}
41+
42+
var user = await _context.Users
43+
.FirstOrDefaultAsync(u => u.Id.ToString() == _currentUser.Id, cancellationToken);
44+
45+
if (user == null)
46+
{
47+
throw new KeyNotFoundException($"User with ID {_currentUser.Id} not found");
48+
}
49+
50+
return new UserProfileResponse
51+
{
52+
Id = user.Id.ToString(),
53+
UserName = user.UserName,
54+
Email = user.Email,
55+
LastLogin = DateTime.UtcNow, // You might want to store this in the database
56+
ProjectsCount = 0 // You can add a Projects table and count them here
57+
};
58+
}
59+
}

Infrastructure/Extensions/ServiceCollectionExtensions.cs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
using PaymentCoreServiceApi.Features.Auth;
88
using PaymentCoreServiceApi.Infrastructure.Repositories.Write;
99
using PaymentCoreServiceApi.Middlewares;
10+
using PaymentCoreServiceApi.Services;
1011

1112
namespace PaymentCoreServiceApi.Infrastructure.Extensions;
1213

@@ -23,6 +24,14 @@ public static IServiceCollection AddRepositories(this IServiceCollection service
2324
return services;
2425
}
2526

27+
public static IServiceCollection AddHttpContextServices(this IServiceCollection services)
28+
{
29+
services.AddHttpContextAccessor();
30+
services.AddScoped<ICurrentUser, CurrentUser>();
31+
32+
return services;
33+
}
34+
2635
public static IServiceCollection AddJwtAuthentication(this IServiceCollection services, IConfiguration configuration)
2736
{
2837
// Register JWT Services

Program.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,8 @@
2424
// Register Services
2525
builder.Services
2626
.AddRepositories()
27-
.AddJwtAuthentication(builder.Configuration);
27+
.AddJwtAuthentication(builder.Configuration)
28+
.AddHttpContextServices();
2829

2930
var app = builder.Build();
3031

Project.http

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
@host = http://localhost:5000
2+
@authToken = your-jwt-token-here
3+
4+
### Login to get token
5+
# @name login
6+
POST {{host}}/api/auth/login
7+
Content-Type: application/json
8+
9+
{
10+
"email": "[email protected]",
11+
"password": "your-password"
12+
}
13+
14+
### Get All User's Projects
15+
GET {{host}}/api/project/my-projects
16+
Authorization: Bearer {{authToken}}
17+
18+
### Get Specific Project by ID
19+
GET {{host}}/api/project/1
20+
Authorization: Bearer {{authToken}}
21+
22+
### Create New Project
23+
POST {{host}}/api/project/create
24+
Authorization: Bearer {{authToken}}
25+
Content-Type: application/json
26+
27+
{
28+
"name": "New Test Project",
29+
"description": "This is a test project created via API"
30+
}

Services/CurrentUser.cs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
using System.Security.Claims;
2+
using Microsoft.AspNetCore.Http;
3+
4+
namespace PaymentCoreServiceApi.Services;
5+
6+
public interface ICurrentUser
7+
{
8+
string? Id { get; }
9+
string? UserName { get; }
10+
string? Email { get; }
11+
bool IsAuthenticated { get; }
12+
}
13+
14+
public class CurrentUser : ICurrentUser
15+
{
16+
private readonly IHttpContextAccessor _httpContextAccessor;
17+
18+
public CurrentUser(IHttpContextAccessor httpContextAccessor)
19+
{
20+
_httpContextAccessor = httpContextAccessor;
21+
}
22+
23+
public string? Id => _httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.NameIdentifier);
24+
public string? UserName => _httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.Name);
25+
public string? Email => _httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.Email);
26+
public bool IsAuthenticated => _httpContextAccessor.HttpContext?.User?.Identity?.IsAuthenticated ?? false;
27+
}

Test.http

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
@host = http://localhost:5000
2+
3+
### Login to get token
4+
POST {{host}}/api/auth/login
5+
Content-Type: application/json
6+
7+
{
8+
"email": "[email protected]",
9+
"password": "your-password"
10+
}
11+
12+
### Test Current User Info
13+
GET {{host}}/api/test/current-user
14+
Authorization: Bearer {{auth_token}}
15+
16+
### Test Protected Resource
17+
GET {{host}}/api/test/protected-resource
18+
Authorization: Bearer {{auth_token}}

0 commit comments

Comments
 (0)