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
14 changes: 14 additions & 0 deletions EasyPay.Data/Dtos/LoginDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EasyPay.Data.Dtos
{
public class LoginDto
{
public string UserId { get; set; }
public string Password { get; set; }
}
}
1 change: 1 addition & 0 deletions EasyPay.Logic/ITransactionManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,6 @@ public interface ITransactionManager
ApiResponse<decimal> GetBalance(string userId);
ApiResponse<string> TransferMoney(TransferRequestDto request);
ApiResponse<string> SetPassword(SetPasswordDto request);
ApiResponse<string> Login(LoginDto request);
}
}
56 changes: 50 additions & 6 deletions EasyPay.Logic/TransactionManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,60 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace EasyPay.Logic
{
public class TransactionManager : ITransactionManager
{
private readonly EasyPayDbContext _context;

public TransactionManager(EasyPayDbContext context)
private readonly IConfiguration _config;
public TransactionManager(EasyPayDbContext context, IConfiguration config)
{
_context = context;
_config = config;
}

// Login Method
public ApiResponse<string> Login(LoginDto request)
{
string logId = "LOGIN-" + Guid.NewGuid().ToString().Substring(0, 8).ToUpper();

// A. User Check
var user = _context.UserAccounts.FirstOrDefault(u => u.UserId == request.UserId);
if (user == null) return new ApiResponse<string> { LogId = logId, IsSuccess = false, Message = "User Not Found" };

// B. Password Check (Hash match)
string inputHash = SecurityHelper.HashPassword(request.Password);
if (user.PasswordHash != inputHash) return new ApiResponse<string> { LogId = logId, IsSuccess = false, Message = "Wrong Password" };

// C. Token Generation (Secret Key use karke)
var key = Encoding.ASCII.GetBytes(_config["JwtSettings:Key"]);
var tokenHandler = new JwtSecurityTokenHandler();

var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, user.UserId) }),
Expires = DateTime.UtcNow.AddMinutes(30),
Issuer = _config["JwtSettings:Issuer"],
Audience = _config["JwtSettings:Audience"],
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};

var token = tokenHandler.CreateToken(tokenDescriptor);
string finalToken = tokenHandler.WriteToken(token);

return new ApiResponse<string>
{
LogId = logId,
IsSuccess = true,
Message = "Login Successful",
Data = finalToken
};
}

// Helper to generate ID
Expand Down Expand Up @@ -151,7 +195,7 @@ public ApiResponse<string> SetPassword(SetPasswordDto request)
{
string logId = "PWD-" + Guid.NewGuid().ToString().Substring(0, 8).ToUpper();

// 1. User dhoondo
// 1. Find User
var user = _context.UserAccounts.FirstOrDefault(u => u.UserId == request.UserId);

if (user == null)
Expand All @@ -160,15 +204,15 @@ public ApiResponse<string> SetPassword(SetPasswordDto request)
{
LogId = logId,
IsSuccess = false,
Message = "User nahi mila!",
Message = "User not Found",
Data = null
};
}

// 2. Password ko Hash karo (Kachumar nikalo)
// 2. Password Hashing
string hashedPassword = SecurityHelper.HashPassword(request.NewPassword);

// 3. Database mein Hash save karo
// 3. Save Hash In DB
user.PasswordHash = hashedPassword;

_context.SaveChanges();
Expand Down
4 changes: 3 additions & 1 deletion EasyPay.WebAPI/Controllers/AccountController.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using EasyPay.Data.Dtos;
using EasyPay.Logic;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

Expand All @@ -23,7 +24,8 @@ public IActionResult GetBalance(string userId)
var response = _manager.GetBalance(userId);
return Ok(response);
}

// Transfer
[Authorize]
[HttpPost("transfer")]
public IActionResult Transfer([FromBody] TransferRequestDto request)
{
Expand Down
37 changes: 37 additions & 0 deletions EasyPay.WebAPI/Controllers/AuthController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using EasyPay.Logic;
using EasyPay.Data.Dtos;

namespace EasyPay.WebAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
private readonly ITransactionManager _manager;

// Dependency Injection (Logic Layer mangwaya)
public AuthController(ITransactionManager manager)
{
_manager = manager;
}

// POST: api/Auth/login
[HttpPost("login")]
public IActionResult Login([FromBody] LoginDto request)
{
// 1. Logic layer ko bulao
var response = _manager.Login(request);

// 2. Agar fail hua (Ghalat password/User nahi mila)
if (!response.IsSuccess)
{
return Unauthorized(response); // 401 Error wapas karo
}

// 3. Agar pass hua to Token wapas karo
return Ok(response);
}
}
}
5 changes: 5 additions & 0 deletions EasyPay.WebAPI/EasyPay.WebAPI.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

<ItemGroup>
<PackageReference Include="FluentValidation.AspNetCore" Version="11.3.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.4">
<PrivateAssets>all</PrivateAssets>
Expand All @@ -25,4 +26,8 @@
<ProjectReference Include="..\EasyPay.Logic\EasyPay.Logic.csproj" />
</ItemGroup>

<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>

</Project>
12 changes: 7 additions & 5 deletions EasyPay.WebAPI/Middlewares/LoggingMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
using System.IO;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Threading.Tasks;
using EasyPay.Data.GeneratedModels.Logs;


namespace EasyPay.WebAPI.Middlewares
{
Expand All @@ -17,7 +19,7 @@ public LoggingMiddleware(RequestDelegate next)
_next = next;
}

public async Task Invoke(HttpContext context, EasyPayDbContext dbContext)
public async Task Invoke(HttpContext context, EasyPayLogsDbContext logsdbContext)
{
// 1. Request Read
context.Request.EnableBuffering();
Expand Down Expand Up @@ -61,7 +63,7 @@ public async Task Invoke(HttpContext context, EasyPayDbContext dbContext)
context.Response.Body.Position = 0;

// 4. Save to DB
var log = new ApiLog
var log = new EasyPay.Data.GeneratedModels.Logs.ApiLog
{
RequestTime = DateTime.Now,
UserId = userId,
Expand All @@ -74,8 +76,8 @@ public async Task Invoke(HttpContext context, EasyPayDbContext dbContext)
Method = method,
};

dbContext.ApiLogs.Add(log);
await dbContext.SaveChangesAsync();
logsdbContext.ApiLogs.Add(log);
await logsdbContext.SaveChangesAsync();

await responseBody.CopyToAsync(originalBodyStream);
}
Expand Down
47 changes: 44 additions & 3 deletions EasyPay.WebAPI/Program.cs
Original file line number Diff line number Diff line change
@@ -1,21 +1,50 @@
using EasyPay.Data.GeneratedModels; // <-- Ye EasyPayDbContext ke liye hai
using EasyPay.Data.GeneratedModels.Logs;
using EasyPay.Logic; // <-- Ye TransactionManager ke liye hai
using EasyPay.WebAPI.Middlewares;
using FluentValidation;
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using System.Transactions;

var builder = WebApplication.CreateBuilder(args);

// 1. Controllers aur Validation add karna
builder.Services.AddControllers();
var jwtSettings = builder.Configuration.GetSection("JwtSettings");
var key = Encoding.ASCII.GetBytes(jwtSettings["Key"]);

builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = true,
ValidateAudience = true,
ValidIssuer = jwtSettings["Issuer"],
ValidAudience = jwtSettings["Audience"],
ClockSkew = TimeSpan.Zero
};
});
builder.Services.AddFluentValidationAutoValidation();
builder.Services.AddValidatorsFromAssemblyContaining<Program>();

// 2. Database Connection (Ab hum Scaffolded Context use kar rahe hain)
builder.Services.AddDbContext<EasyPayDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddDbContext<EasyPayLogsDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("LogsConnection")));

// 3. Logic Layer (Dependency Injection)
builder.Services.AddScoped<ITransactionManager, EasyPay.Logic.TransactionManager>();
Expand All @@ -24,6 +53,9 @@
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();




var app = builder.Build();

// Configure the HTTP request pipeline.
Expand All @@ -35,11 +67,20 @@

app.UseHttpsRedirection();

// 5. Jasoos Camera ON karna (Logging Middleware)
app.UseMiddleware<LoggingMiddleware>();
// 1. Pehle CORS (Agar hai)
app.UseCors("AllowAll");

// 2. Phir Routing
app.UseRouting();

// 3. Authentication (ID Card Check) <-- YE NAYA HAI
app.UseAuthentication();

// 4. Authorization (Gate Pass Check) <-- YE NAYA HAI
app.UseAuthorization();

app.MapControllers();
// 5. Logging (Jasoosi)
app.UseMiddleware<LoggingMiddleware>();

app.MapControllers();
app.Run();
10 changes: 8 additions & 2 deletions EasyPay.WebAPI/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,13 @@
},
"AllowedHosts": "*",
"ConnectionStrings": {
// Niche dekhein: Aapke Server ka poora naam dala hai (Double slash ke saath)
"DefaultConnection": "Server=DESKTOP-BNT57LQ\\MSSQLSERVER01;Database=EasyPayDb;Trusted_Connection=True;TrustServerCertificate=True;"
"DefaultConnection": "Data Source=DESKTOP-BNT57LQ\\MSSQLSERVER01;Initial Catalog=EasyPayDb;Integrated Security=True;TrustServerCertificate=True;MultipleActiveResultSets=true;Connection Timeout=30;Connection Lifetime=0;Min Pool Size=0;Max Pool Size=1000;Pooling=true",
"LogsConnection": "Data Source=DESKTOP-BNT57LQ\\MSSQLSERVER01;Initial Catalog=EasyPayLogsDB;Integrated Security=True;TrustServerCertificate=True;MultipleActiveResultSets=true;Connection Timeout=30;Connection Lifetime=0;Min Pool Size=0;Max Pool Size=1000;Pooling=true"
},
"JwtSettings": {
"Key": "YeMeraSuperSecretKeyHaiJo32CharsKaHonaChahiye123",
"Issuer": "EasyPayServer",
"Audience": "EasyPayClient"
}

}