token call;

This commit is contained in:
2025-03-06 19:11:25 +01:00
parent 513884fa74
commit 0ae473a055
5 changed files with 74 additions and 4 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
api/proxy.log

View File

@ -6,7 +6,7 @@ from urllib.parse import urlparse
import logging import logging
# Configure basic logging # Configure basic logging
logging.basicConfig(level=logging.INFO) logging.basicConfig(filename='proxy.log', encoding='utf-8', level=logging.DEBUG)
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
# Initialize Flask app # Initialize Flask app
@ -18,6 +18,7 @@ class ResourceRouter:
def __init__(self): def __init__(self):
self.resource_mappings = { self.resource_mappings = {
'login': {'backend_url': 'http://linepe.de:5004/login', 'methods': ['POST']}, 'login': {'backend_url': 'http://linepe.de:5004/login', 'methods': ['POST']},
'token': {'backend_url': 'http://linepe.de:5004/token', 'methods': ['POST']},
'logout': {'backend_url': 'http://linepe.de:5004/logout', 'methods': ['POST']}, 'logout': {'backend_url': 'http://linepe.de:5004/logout', 'methods': ['POST']},
'register': {'backend_url': 'http://linepe.de:5004/register', 'methods': ['POST']}, 'register': {'backend_url': 'http://linepe.de:5004/register', 'methods': ['POST']},
'listing': {'backend_url': 'http://linepe.de:5005/listing', 'methods': ['GET', 'POST', 'PUT', 'DELETE']}, 'listing': {'backend_url': 'http://linepe.de:5005/listing', 'methods': ['GET', 'POST', 'PUT', 'DELETE']},

View File

@ -8,8 +8,9 @@ from flask import Flask, request, jsonify
from flask_cors import CORS from flask_cors import CORS
from werkzeug.security import generate_password_hash, check_password_hash from werkzeug.security import generate_password_hash, check_password_hash
import pymysql import pymysql
from functools import wraps
from pymysql.cursors import DictCursor from pymysql.cursors import DictCursor
import requests
# Load environment variables # Load environment variables
load_dotenv() load_dotenv()
@ -21,6 +22,8 @@ app.secret_key = os.getenv('SECRET_KEY')
if not app.secret_key: if not app.secret_key:
raise ValueError("SECRET_KEY must be set in the .env file") raise ValueError("SECRET_KEY must be set in the .env file")
TOKEN_VERIFICATION_URL = 'http://ww_user:5000/token'
db_config = { db_config = {
'host': os.getenv('DB_HOST'), 'host': os.getenv('DB_HOST'),
'user': os.getenv('DB_USER'), 'user': os.getenv('DB_USER'),
@ -36,7 +39,38 @@ for var in ['DB_HOST', 'DB_USER', 'DB_PASSWORD', 'DB_NAME', 'DB_PORT']:
def get_db_connection(): def get_db_connection():
return pymysql.connect(**db_config) return pymysql.connect(**db_config)
def verify_token(f):
@wraps(f)
def wrapped(*args, **kwargs):
# Extract the token from the request headers
token = request.headers.get('Authorization', '').split()
if not token:
return jsonify({'error': 'No token provided'}), 401
token_type, token = token[0], token[1]
if token_type.lower() != 'bearer':
return jsonify({'error': 'Invalid token format'}), 400
try:
# Send the token to the verification service
response = requests.get(
TOKEN_VERIFICATION_URL,
headers={'Authorization': f'{token_type} {token}'}
)
if response.status_code == 200:
return f(*args, **kwargs)
else:
return jsonify({'error': 'Invalid token'}), 401
except requests.RequestException as e:
# Handle network or service errors
return jsonify({'error': 'Token verification failed'}), 500
@app.route('/listing', methods=['POST']) @app.route('/listing', methods=['POST'])
@verify_token
def add_listing(): def add_listing():
"""Commit (save) a new listing""" """Commit (save) a new listing"""
data = request.json data = request.json
@ -153,6 +187,7 @@ def get_listing(listing_id):
connection.close() connection.close()
@app.route('/listing/<int:listing_id>', methods=['DELETE']) @app.route('/listing/<int:listing_id>', methods=['DELETE'])
@verify_token
def delete_listing(listing_id): def delete_listing(listing_id):
"""Delete a listing by ID""" """Delete a listing by ID"""
try: try:
@ -173,6 +208,7 @@ def delete_listing(listing_id):
connection.close() connection.close()
@app.route('/listing/<int:listing_id>', methods=['PUT']) @app.route('/listing/<int:listing_id>', methods=['PUT'])
@verify_token
def change_listing(listing_id): def change_listing(listing_id):
"""Update listing details""" """Update listing details"""
data = request.json data = request.json

View File

@ -7,3 +7,5 @@ enum34
python-dotenv python-dotenv
pymysql pymysql
gunicorn gunicorn
functools
requests

View File

@ -155,6 +155,36 @@ def login():
cursor.close() cursor.close()
connection.close() connection.close()
@app.route('/token', methods=['POST'])
def verify_token():
try:
connection = get_db_connection()
cursor = connection.cursor()
token = request.headers.get('Authorization')
if not token:
return jsonify({'error': 'Missing token'}), 400
# Use the correct table name here (Tokens instead of user_tokens)
cursor.execute(
"SELECT id FROM Tokens WHERE token = %s AND expires_at > UNIX_TIMESTAMP()",
(token,)
)
result = cursor.fetchone()
if not result:
return jsonify({'error': 'Invalid or expired token'}), 401
return jsonify({'message': 'Token is valid'}), 200
except Exception as e:
logging.error(f"Verification error: {str(e)}")
return jsonify({'error': str(e)}), 500
finally:
if 'cursor' in locals():
cursor.close()
connection.close()
@app.route('/logout', methods=['POST']) @app.route('/logout', methods=['POST'])
def logout(): def logout():
try: try: