Developer 02 38d05850e3 Refactor CreateEnvelopeAsync to use string formatting
Updated the `CreateEnvelopeAsync` method in the `EnvelopeExecutor` class to handle SQL parameters by directly formatting the SQL string with `string.Format`, replacing the previous parameterized query approach. This change enhances readability but may introduce potential SQL injection risks if not managed carefully.
2025-05-07 13:11:52 +02:00

37 lines
1.7 KiB
C#

using Dapper;
using DigitalData.UserManager.Application.Contracts.Repositories;
using EnvelopeGenerator.Application.Contracts.Repositories;
using EnvelopeGenerator.Application.Contracts.SQLExecutor;
using EnvelopeGenerator.Application.SQL;
using EnvelopeGenerator.Domain.Entities;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace EnvelopeGenerator.Infrastructure.Executor;
public class EnvelopeExecutor : SQLExecutor, IEnvelopeExecutor
{
private readonly IUserRepository _userRepository;
public EnvelopeExecutor(IServiceProvider provider, IOptions<SQLExecutorParams> sqlExecutorParamsOptions, IUserRepository userRepository) : base(provider, sqlExecutorParamsOptions)
{
_userRepository = userRepository;
}
public async Task<Envelope> CreateEnvelopeAsync(int userId, string title = "", string message = "", bool tfaEnabled = false, CancellationToken cancellation = default)
{
using var connection = new SqlConnection(Params.ConnectionString);
var sql = Provider.GetRequiredService<EnvelopeCreateReadSQL>();
var formattedSql = string.Format(sql.Raw, userId.ToSqlParam(), title.ToSqlParam(), tfaEnabled.ToSqlParam(), message.ToSqlParam());
await connection.OpenAsync(cancellation);
var envelopes = await connection.QueryAsync<Envelope>(formattedSql);
var envelope = envelopes.FirstOrDefault()
?? throw new InvalidOperationException($"Envelope creation failed. Parameters:" +
$"userId={userId}, title='{title}', message='{message}', tfaEnabled={tfaEnabled}."); ;
envelope.User = await _userRepository.ReadByIdAsync(envelope.UserId);
return envelope;
}
}