Skip to content

Instantly share code, notes, and snippets.

@grittyninja
Created August 27, 2024 13:23
Show Gist options
  • Save grittyninja/6d15170f861d33845b1684eb10180546 to your computer and use it in GitHub Desktop.
Save grittyninja/6d15170f861d33845b1684eb10180546 to your computer and use it in GitHub Desktop.
# app.py
from flask import Flask, request, jsonify
import psycopg2
from psycopg2.extras import RealDictCursor
import os
app = Flask(__name__)
# Database connection
def get_db_connection():
return psycopg2.connect(
host=os.environ.get('DB_HOST', 'db'),
database=os.environ.get('DB_NAME', 'postgres'),
user=os.environ.get('DB_USER', 'postgres'),
password=os.environ.get('DB_PASSWORD', 'postgres')
)
# Update user endpoint
@app.route('/api/users/<int:id>', methods=['PUT'])
def update_user(id):
data = request.json
name = data.get('name')
address = data.get('address')
if not name or not address:
return jsonify({"error": "Name and address are required"}), 400
# UNSAFE: Directly interpolating user input into the SQL query
query = f"UPDATE users SET name = '{name}', address = '{address}' WHERE id = {id} RETURNING *"
try:
conn = get_db_connection()
cur = conn.cursor()
# UNSAFE: Executing the query with user input directly interpolated
cur.execute(query)
updated_user = cur.fetchone()
conn.commit()
cur.close()
conn.close()
if updated_user:
return jsonify({"message": "User updated", "user": updated_user}), 200
else:
return jsonify({"error": "User not found"}), 404
except Exception as e:
return jsonify({"error": str(e)}), 500
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment