feat(sql): SQL Injection
This commit is contained in:
@@ -9,7 +9,16 @@ import (
|
||||
)
|
||||
|
||||
func UpdateSQL(s *schema.Table, data map[string]any, where string) (string, error) {
|
||||
// Create a map for quick field lookup
|
||||
if s == nil {
|
||||
return "", fmt.Errorf("nil table provided")
|
||||
}
|
||||
if s.Name == "" || !utils.IsValidIdentifier(s.Name) {
|
||||
return "", fmt.Errorf("invalid table name: %q", s.Name)
|
||||
}
|
||||
if s.PrimaryKey == "" || !utils.IsValidIdentifier(s.PrimaryKey) {
|
||||
return "", fmt.Errorf("invalid primary key: %q", s.PrimaryKey)
|
||||
}
|
||||
|
||||
fieldMap := make(map[string]*schema.Field)
|
||||
for i := range s.Schema {
|
||||
fieldMap[s.Schema[i].Name] = &s.Schema[i]
|
||||
@@ -17,7 +26,10 @@ func UpdateSQL(s *schema.Table, data map[string]any, where string) (string, erro
|
||||
|
||||
setClause := make([]string, 0, len(data))
|
||||
for field, value := range data {
|
||||
// Check if field is of type "hash" and needs hashing
|
||||
if !utils.IsValidIdentifier(field) {
|
||||
return "", fmt.Errorf("invalid field name: %q", field)
|
||||
}
|
||||
|
||||
if schemaField, exists := fieldMap[field]; exists && schemaField.Type == "hash" && schemaField.Algorithm != nil {
|
||||
valueStr := fmt.Sprintf("%v", value)
|
||||
hashed, err := utils.Hash(valueStr, *schemaField.Algorithm)
|
||||
@@ -26,8 +38,19 @@ func UpdateSQL(s *schema.Table, data map[string]any, where string) (string, erro
|
||||
}
|
||||
value = hashed
|
||||
}
|
||||
|
||||
setClause = append(setClause, fmt.Sprintf("%s = %s", utils.SQLQuoteIdent(field), utils.SQLQuoteValue(value)))
|
||||
}
|
||||
|
||||
setClause = append(setClause, "updated_at = CURRENT_TIMESTAMP")
|
||||
return fmt.Sprintf("UPDATE %s SET %s WHERE %s = %s", utils.SQLQuoteIdent(s.Name), strings.Join(setClause, ", "), utils.SQLQuoteIdent(s.PrimaryKey), utils.SQLQuoteValue(where)), nil
|
||||
|
||||
query := fmt.Sprintf(
|
||||
"UPDATE %s SET %s WHERE %s = %s",
|
||||
utils.SQLQuoteIdent(s.Name),
|
||||
strings.Join(setClause, ", "),
|
||||
utils.SQLQuoteIdent(s.PrimaryKey),
|
||||
utils.SQLQuoteValue(where),
|
||||
)
|
||||
|
||||
return query, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user