Make all code SQL injection safe #490

Open
opened 2026-04-22 07:53:45 +00:00 by a24timsv · 1 comment
Collaborator

Some code are not written in a safe SQL manner. Some parts could suffer from SQL injections. Even if it might not make a difference, it is a good standard to always write in a safe way.

This can either be done by using bind Parms (as we did in the Database Construction course) or using procedures in the database itself.

Some code are not written in a safe SQL manner. Some parts could suffer from SQL injections. Even if it might not make a difference, it is a good standard to always write in a safe way. This can either be done by using bind Parms (as we did in the Database Construction course) or using procedures in the database itself.
Collaborator

A possible solution (example) for a service is:

  public async Task<UserRow?> GetByEmailAsync(string email)
    {
        await using NpgsqlConnection connection = await dataSource.OpenConnectionAsync();
        const string sql = """
                           SELECT
                               id as Id,
                               username as Username,
                               email as Email,
                               password_hash as PasswordHash,
                               role as Role,
                               deleted_at as DeletedAt,
                               created_at as CreatedAt,
                               updated_at as UpdatedAt
                               
                           FROM
                               users
                           WHERE username = @Username AND deleted_at IS NULL;
                           """;
        IEnumerable<UserRow> rows = await connection.QueryAsync<UserRow>(sql, new { Username = email });
        return rows.FirstOrDefault();
    }

A possible solution (example) for a service is: ```cs public async Task<UserRow?> GetByEmailAsync(string email) { await using NpgsqlConnection connection = await dataSource.OpenConnectionAsync(); const string sql = """ SELECT id as Id, username as Username, email as Email, password_hash as PasswordHash, role as Role, deleted_at as DeletedAt, created_at as CreatedAt, updated_at as UpdatedAt FROM users WHERE username = @Username AND deleted_at IS NULL; """; IEnumerable<UserRow> rows = await connection.QueryAsync<UserRow>(sql, new { Username = email }); return rows.FirstOrDefault(); } ```
Sign in to join this conversation.
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Andras/BoundlessFlowCampus2K#490
No description provided.