feat: integrate PYMS payment gateway, add blog/sitepage/image services, local file manager
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m44s
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m44s
Payment Gateway: - Add PYMSPaymentService: IPaymentGatewayService via gRPC to PYMS microservice - Add ZarinPalPaymentService: direct ZarinPal integration (backup) - Register 'pyms' payment provider in DI ConfigureServices - Add PYMS proto files (pyms_transaction.proto, pyms_public_messages.proto) - Fix VerifyDiscountWalletCharge: pass 'OK' as status instead of Authority - Update appsettings: PaymentProvider=pyms, sandbox mode, merchant ID Blog System: - Add BlogCategory, BlogPost, BlogPostImage entities and CQRS - Add proto files and gRPC services for blog management - Add Mapster profiles for blog responses Content Management: - Add SitePage entity and CQRS for static pages - Add proto and gRPC service for site pages Image/File Management: - Add LocalFileManager with disk storage + base64 serving + FMS fallback - Add ImagePathResolverInterceptor for gRPC responses - Add ImageResolverService for explicit image resolution - Add UploadsController for public file serving with FMS fallback - Add PaymentCallbackController for discount order payment callbacks Database: - Add blog and content entity migrations - Remove ImagePath MaxLength constraints - Remove old FileManagementService (replaced by LocalFileManager)
This commit is contained in:
+24
-10
@@ -24,15 +24,9 @@ public class AcceptContractCommandHandler : IRequestHandler<AcceptContractComman
|
||||
|
||||
public async Task<AcceptContractResponseDto> Handle(AcceptContractCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// Verify OTP first
|
||||
var otpToken = await _context.OtpTokens
|
||||
.Where(x => x.Mobile == _currentUserService.Username && x.Purpose == "signContract" && !x.IsUsed)
|
||||
.OrderByDescending(x => x.Id)
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
|
||||
var secret = _cfg["Otp:Secret"] ?? throw new InvalidOperationException("Otp:Secret not set");
|
||||
if (otpToken == null || !otpToken.IsValid() || !_hashService.VerifyHmacSha256Hex(request.Code, otpToken.CodeHash, secret))
|
||||
return new AcceptContractResponseDto { IsSuccess = false, Message = "کد تایید نامعتبر است" };
|
||||
// پیدا کردن کاربر بر اساس UserId از توکن JWT
|
||||
if (!long.TryParse(_currentUserService.UserId, out var userId))
|
||||
return new AcceptContractResponseDto { IsSuccess = false, Message = "کاربر احراز هویت نشده است" };
|
||||
|
||||
var user = await _context.Users
|
||||
.Include(u => u.UserContracts)
|
||||
@@ -40,12 +34,22 @@ public class AcceptContractCommandHandler : IRequestHandler<AcceptContractComman
|
||||
.Include(u => u.UserRoles)
|
||||
.ThenInclude(ur => ur.Role)
|
||||
.Include(u => u.ClubMembership)
|
||||
.Where(x => x.Mobile == _currentUserService.Username)
|
||||
.Where(x => x.Id == userId)
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
|
||||
if (user == null)
|
||||
return new AcceptContractResponseDto { IsSuccess = false, Message = "کاربر یافت نشد" };
|
||||
|
||||
// جستجوی OTP بر اساس شماره موبایل کاربر (نه Username)
|
||||
var otpToken = await _context.OtpTokens
|
||||
.Where(x => x.Mobile == user.Mobile && x.Purpose == "signContract" && !x.IsUsed)
|
||||
.OrderByDescending(x => x.Id)
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
|
||||
var secret = _cfg["Otp:Secret"] ?? throw new InvalidOperationException("Otp:Secret not set");
|
||||
if (otpToken == null || !otpToken.IsValid() || !_hashService.VerifyHmacSha256Hex(request.Code, otpToken.CodeHash, secret))
|
||||
return new AcceptContractResponseDto { IsSuccess = false, Message = "کد تایید نامعتبر است" };
|
||||
|
||||
// Create user contract
|
||||
var userContract = new UserContract
|
||||
{
|
||||
@@ -62,6 +66,16 @@ public class AcceptContractCommandHandler : IRequestHandler<AcceptContractComman
|
||||
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
|
||||
// بارگذاری مجدد کاربر با تمام روابط برای تولید JWT صحیح
|
||||
user = await _context.Users
|
||||
.Include(u => u.UserContracts)
|
||||
.ThenInclude(uc => uc.Contract)
|
||||
.Include(u => u.UserRoles)
|
||||
.ThenInclude(ur => ur.Role)
|
||||
.Include(u => u.ClubMembership)
|
||||
.Where(x => x.Id == userId)
|
||||
.FirstAsync(cancellationToken);
|
||||
|
||||
// Generate JWT token with updated contract status
|
||||
var token = await _generateJwt.GenerateJwtToken(user);
|
||||
|
||||
|
||||
+61
-26
@@ -1,6 +1,8 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using CMSMicroservice.Application.Common.Interfaces;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using CMSMicroservice.Domain.Entities;
|
||||
|
||||
namespace CMSMicroservice.Application.UserCQ.Commands.CreateNewOtpToken;
|
||||
@@ -9,41 +11,60 @@ public class CreateNewOtpTokenCommandHandler : IRequestHandler<CreateNewOtpToken
|
||||
{
|
||||
private readonly IApplicationDbContext _context;
|
||||
private readonly IKavenegarService _kavenegarService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IHashService _hashService;
|
||||
private readonly IConfiguration _cfg;
|
||||
|
||||
public CreateNewOtpTokenCommandHandler(IApplicationDbContext context, IKavenegarService kavenegarService, ICurrentUserService currentUserService)
|
||||
const int CodeLength = 6;
|
||||
const int MaxAttempts = 5;
|
||||
static readonly TimeSpan Ttl = TimeSpan.FromMinutes(2);
|
||||
static readonly TimeSpan Cooldown = TimeSpan.FromSeconds(60);
|
||||
|
||||
public CreateNewOtpTokenCommandHandler(
|
||||
IApplicationDbContext context,
|
||||
IKavenegarService kavenegarService,
|
||||
IHashService hashService,
|
||||
IConfiguration cfg)
|
||||
{
|
||||
_context = context;
|
||||
_kavenegarService = kavenegarService;
|
||||
_currentUserService = currentUserService;
|
||||
_hashService = hashService;
|
||||
_cfg = cfg;
|
||||
}
|
||||
|
||||
public async Task<CreateNewOtpTokenResponseDto> Handle(CreateNewOtpTokenCommand request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// Generate random 4-digit code
|
||||
var random = new Random();
|
||||
var code = random.Next(1000, 9999).ToString();
|
||||
var mobile = request.Mobile.NormalizeIranMobile();
|
||||
var purpose = request.Purpose?.ToLowerInvariant() ?? "login";
|
||||
var now = DateTime.Now;
|
||||
|
||||
// Invalidate previous unused tokens for this mobile and purpose
|
||||
var existingTokens = await _context.OtpTokens
|
||||
.Where(x => x.Mobile == request.Mobile && x.Purpose == request.Purpose && !x.IsUsed)
|
||||
.ToListAsync(cancellationToken);
|
||||
// ریتلیمیت: اگر هنوز کدی فعال و تازه داریم، اجازه نده
|
||||
var lastActive = await _context.OtpTokens
|
||||
.Where(o => o.Mobile == mobile && o.Purpose == purpose && !o.IsUsed && o.ExpiresAt > now)
|
||||
.OrderByDescending(o => o.Created)
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
|
||||
foreach (var token in existingTokens)
|
||||
{
|
||||
token.IsUsed = true;
|
||||
}
|
||||
if (lastActive is not null && (now - lastActive.Created) < Cooldown)
|
||||
return new CreateNewOtpTokenResponseDto
|
||||
{
|
||||
Success = false,
|
||||
Message = "لطفاً کمی بعد دوباره تلاش کنید."
|
||||
};
|
||||
|
||||
// تولید کد ۶ رقمی امن
|
||||
var code = GenerateNumericCode(CodeLength);
|
||||
var secret = _cfg["Otp:Secret"] ?? throw new InvalidOperationException("Otp:Secret not set");
|
||||
var codeHash = _hashService.ComputeHmacSha256Hex(code, secret);
|
||||
|
||||
// Create new OTP token
|
||||
var otpToken = new OtpToken
|
||||
{
|
||||
Mobile = request.Mobile,
|
||||
Purpose = request.Purpose,
|
||||
Code = code,
|
||||
CodeHash = BCrypt.Net.BCrypt.HashPassword(code), // Hash the code for security
|
||||
Mobile = mobile,
|
||||
Purpose = purpose,
|
||||
CodeHash = codeHash,
|
||||
IsUsed = false,
|
||||
ExpiresAt = DateTime.UtcNow.AddMinutes(5) // 5 minutes expiry
|
||||
Attempts = 0,
|
||||
ExpiresAt = now.Add(Ttl)
|
||||
};
|
||||
|
||||
_context.OtpTokens.Add(otpToken);
|
||||
@@ -51,24 +72,38 @@ public class CreateNewOtpTokenCommandHandler : IRequestHandler<CreateNewOtpToken
|
||||
|
||||
try
|
||||
{
|
||||
// Send SMS
|
||||
var user = await _context.Users
|
||||
.Where(x => x.Mobile == request.Mobile)
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
|
||||
await _kavenegarService.VerifyLookupAsync(request.Mobile, code);
|
||||
// برای امضای قرارداد، شناسه GUID هم در پیامک ارسال شود
|
||||
if ((purpose == "signcontract" || purpose == "signclubcontract") && !string.IsNullOrEmpty(request.SignGuid))
|
||||
{
|
||||
var message = $"کد تایید امضای قرارداد: {code}\nشناسه قرارداد: {request.SignGuid}";
|
||||
await _kavenegarService.SendAsync(mobile, message);
|
||||
}
|
||||
else
|
||||
{
|
||||
await _kavenegarService.VerifyLookupAsync(mobile, code);
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// Log error but don't fail the request
|
||||
// TODO: Add proper logging
|
||||
}
|
||||
|
||||
return new CreateNewOtpTokenResponseDto
|
||||
{
|
||||
Success = true,
|
||||
Message = "کد تایید با موفقیت ارسال شد",
|
||||
RemainingAttempts = MaxAttempts,
|
||||
RemainingSeconds = (int)Ttl.TotalSeconds,
|
||||
ExpiresAt = otpToken.ExpiresAt
|
||||
};
|
||||
}
|
||||
|
||||
private static string GenerateNumericCode(int len)
|
||||
{
|
||||
var bytes = new byte[len];
|
||||
RandomNumberGenerator.Fill(bytes);
|
||||
var sb = new StringBuilder(len);
|
||||
foreach (var b in bytes) sb.Append((b % 10).ToString());
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
+110
-12
@@ -1,5 +1,4 @@
|
||||
using CMSMicroservice.Application.Common.Interfaces;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using CMSMicroservice.Domain.Events;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
|
||||
namespace CMSMicroservice.Application.UserCQ.Commands.VerifyOtpToken;
|
||||
@@ -19,36 +18,134 @@ public class VerifyOtpTokenCommandHandler : IRequestHandler<VerifyOtpTokenComman
|
||||
_cfg = cfg;
|
||||
}
|
||||
|
||||
const int MaxAttempts = 5;
|
||||
|
||||
public async Task<VerifyOtpTokenResponseDto> Handle(VerifyOtpTokenCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var mobile = request.Mobile.NormalizeIranMobile();
|
||||
var purpose = request.Purpose?.ToLowerInvariant() ?? "login";
|
||||
var now = DateTime.Now;
|
||||
|
||||
var otpToken = await _context.OtpTokens
|
||||
.Where(x => x.Mobile == request.Mobile && x.Purpose == request.Purpose && !x.IsUsed)
|
||||
.Where(x => x.Mobile == mobile && x.Purpose == purpose && !x.IsUsed && x.ExpiresAt > now)
|
||||
.OrderByDescending(x => x.Id)
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
|
||||
if (otpToken == null)
|
||||
return new VerifyOtpTokenResponseDto { Success = false, Message = "کد تایید نامعتبر است" };
|
||||
return new VerifyOtpTokenResponseDto { Success = false, Message = "کد تایید منقضی شده یا وجود ندارد. لطفاً کد جدید دریافت کنید." };
|
||||
|
||||
// Check expiry and usage
|
||||
if (otpToken.IsUsed || DateTime.Now > otpToken.ExpiresAt)
|
||||
return new VerifyOtpTokenResponseDto { Success = false, Message = "کد تایید منقضی شده است" };
|
||||
// بررسی تعداد تلاش
|
||||
if (otpToken.Attempts >= MaxAttempts)
|
||||
return new VerifyOtpTokenResponseDto { Success = false, Message = "تعداد تلاشها زیاد است. لطفاً کد جدید دریافت کنید." };
|
||||
|
||||
// Verify using the same HMAC-SHA256 method used during creation
|
||||
otpToken.Attempts++;
|
||||
|
||||
// Verify using HMAC-SHA256
|
||||
var secret = _cfg["Otp:Secret"] ?? throw new InvalidOperationException("Otp:Secret not set");
|
||||
if (!_hashService.VerifyHmacSha256Hex(request.Code, otpToken.CodeHash, secret))
|
||||
return new VerifyOtpTokenResponseDto { Success = false, Message = "کد تایید نامعتبر است" };
|
||||
{
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
var remaining = MaxAttempts - otpToken.Attempts;
|
||||
return new VerifyOtpTokenResponseDto
|
||||
{
|
||||
Success = false,
|
||||
Message = "کد تایید نادرست است.",
|
||||
RemainingAttempts = remaining
|
||||
};
|
||||
}
|
||||
|
||||
// ── جستجوی کاربر ──
|
||||
var user = await _context.Users
|
||||
.Include(u => u.UserContracts)
|
||||
.ThenInclude(uc => uc.Contract)
|
||||
.Include(u => u.UserRoles)
|
||||
.ThenInclude(ur => ur.Role)
|
||||
.Include(u => u.ClubMembership)
|
||||
.Where(x => x.Mobile == request.Mobile)
|
||||
.Where(x => x.Mobile == mobile)
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
|
||||
// ── کاربر وجود ندارد → ثبتنام جدید ──
|
||||
if (user == null)
|
||||
return new VerifyOtpTokenResponseDto { Success = false, Message = "کاربر یافت نشد" };
|
||||
{
|
||||
// کد معرف الزامی است
|
||||
if (string.IsNullOrWhiteSpace(request.ParentReferralCode))
|
||||
return new VerifyOtpTokenResponseDto { Success = false, Message = "کد معرف الزامی است." };
|
||||
|
||||
// بررسی وجود معرف و فعال بودن عضویت باشگاه
|
||||
var parent = await _context.Users
|
||||
.Include(u => u.ClubMembership)
|
||||
.FirstOrDefaultAsync(u => u.ReferralCode == request.ParentReferralCode, cancellationToken);
|
||||
|
||||
if (parent == null)
|
||||
return new VerifyOtpTokenResponseDto { Success = false, Message = "معرف وجود ندارد." };
|
||||
|
||||
if (parent.ClubMembership == null || !parent.ClubMembership.IsActive)
|
||||
return new VerifyOtpTokenResponseDto
|
||||
{
|
||||
Success = false,
|
||||
Message = "لینک دعوت معرف فعال نیست. لطفاً از کد دعوت معتبر دیگری استفاده کنید."
|
||||
};
|
||||
|
||||
// بررسی ظرفیت معرف (حداکثر ۲ زیرمجموعه مستقیم)
|
||||
var existingChildren = await _context.Users
|
||||
.Where(x => x.NetworkParentId == parent.Id && !x.IsDeleted)
|
||||
.Select(x => x.LegPosition)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
if (existingChildren.Count > 1)
|
||||
return new VerifyOtpTokenResponseDto { Success = false, Message = "ظرفیت معرف تکمیل است!!" };
|
||||
|
||||
// تعیین موقعیت شاخه (چپ اول، بعد راست)
|
||||
NetworkLeg newUserLegPosition;
|
||||
if (!existingChildren.Any(x => x == NetworkLeg.Left))
|
||||
newUserLegPosition = NetworkLeg.Left;
|
||||
else if (!existingChildren.Any(x => x == NetworkLeg.Right))
|
||||
newUserLegPosition = NetworkLeg.Right;
|
||||
else
|
||||
return new VerifyOtpTokenResponseDto { Success = false, Message = "ظرفیت معرف تکمیل است!!" };
|
||||
|
||||
// ایجاد کاربر جدید
|
||||
user = new User
|
||||
{
|
||||
Mobile = mobile,
|
||||
ReferralCode = UtilExtensions.Generate(digits: 10, firstDigitNonZero: true),
|
||||
IsMobileVerified = true,
|
||||
MobileVerifiedAt = now,
|
||||
IsRulesAccepted = true,
|
||||
RulesAcceptedAt = now,
|
||||
NetworkParentId = parent.Id,
|
||||
LegPosition = newUserLegPosition
|
||||
};
|
||||
await _context.Users.AddAsync(user, cancellationToken);
|
||||
user.AddDomainEvent(new CreateNewUserEvent(user));
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
|
||||
// ایجاد نقش کاربری
|
||||
var userRole = new UserRole { UserId = user.Id, RoleId = 1 };
|
||||
await _context.UserRoles.AddAsync(userRole, cancellationToken);
|
||||
user.AddDomainEvent(new CreateNewUserRoleEvent(userRole));
|
||||
|
||||
// ایجاد کیف پول
|
||||
var userWallet = new UserWallet { UserId = user.Id, Balance = 0, NetworkBalance = 0 };
|
||||
await _context.UserWallets.AddAsync(userWallet, cancellationToken);
|
||||
user.AddDomainEvent(new CreateNewUserWalletEvent(userWallet));
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
|
||||
// بارگذاری مجدد کاربر با روابط کامل (برای تولید توکن)
|
||||
user = await _context.Users
|
||||
.Include(u => u.UserContracts)
|
||||
.ThenInclude(uc => uc.Contract)
|
||||
.Include(u => u.UserRoles)
|
||||
.ThenInclude(ur => ur.Role)
|
||||
.Include(u => u.ClubMembership)
|
||||
.FirstAsync(x => x.Id == user.Id, cancellationToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
// کاربر موجود — بهروزرسانی وضعیت تایید موبایل
|
||||
user.IsMobileVerified = true;
|
||||
user.MobileVerifiedAt ??= now;
|
||||
}
|
||||
|
||||
// Mark OTP as used
|
||||
otpToken.IsUsed = true;
|
||||
@@ -61,7 +158,8 @@ public class VerifyOtpTokenCommandHandler : IRequestHandler<VerifyOtpTokenComman
|
||||
{
|
||||
Success = true,
|
||||
Message = "کد تایید با موفقیت تایید شد",
|
||||
Token = token
|
||||
Token = token,
|
||||
RemainingAttempts = MaxAttempts
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user