token call;
This commit is contained in:
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
||||
api/proxy.log
|
@ -6,7 +6,7 @@ from urllib.parse import urlparse
|
||||
import logging
|
||||
|
||||
# Configure basic logging
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logging.basicConfig(filename='proxy.log', encoding='utf-8', level=logging.DEBUG)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Initialize Flask app
|
||||
@ -17,7 +17,8 @@ MyApp.config['SECRET_KEY'] = 'your-secret-key-here'
|
||||
class ResourceRouter:
|
||||
def __init__(self):
|
||||
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']},
|
||||
'register': {'backend_url': 'http://linepe.de:5004/register', 'methods': ['POST']},
|
||||
'listing': {'backend_url': 'http://linepe.de:5005/listing', 'methods': ['GET', 'POST', 'PUT', 'DELETE']},
|
||||
|
@ -8,8 +8,9 @@ from flask import Flask, request, jsonify
|
||||
from flask_cors import CORS
|
||||
from werkzeug.security import generate_password_hash, check_password_hash
|
||||
import pymysql
|
||||
from functools import wraps
|
||||
from pymysql.cursors import DictCursor
|
||||
|
||||
import requests
|
||||
|
||||
# Load environment variables
|
||||
load_dotenv()
|
||||
@ -21,6 +22,8 @@ app.secret_key = os.getenv('SECRET_KEY')
|
||||
if not app.secret_key:
|
||||
raise ValueError("SECRET_KEY must be set in the .env file")
|
||||
|
||||
TOKEN_VERIFICATION_URL = 'http://ww_user:5000/token'
|
||||
|
||||
db_config = {
|
||||
'host': os.getenv('DB_HOST'),
|
||||
'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():
|
||||
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'])
|
||||
@verify_token
|
||||
def add_listing():
|
||||
"""Commit (save) a new listing"""
|
||||
data = request.json
|
||||
@ -153,6 +187,7 @@ def get_listing(listing_id):
|
||||
connection.close()
|
||||
|
||||
@app.route('/listing/<int:listing_id>', methods=['DELETE'])
|
||||
@verify_token
|
||||
def delete_listing(listing_id):
|
||||
"""Delete a listing by ID"""
|
||||
try:
|
||||
@ -173,6 +208,7 @@ def delete_listing(listing_id):
|
||||
connection.close()
|
||||
|
||||
@app.route('/listing/<int:listing_id>', methods=['PUT'])
|
||||
@verify_token
|
||||
def change_listing(listing_id):
|
||||
"""Update listing details"""
|
||||
data = request.json
|
||||
|
@ -6,4 +6,6 @@ python-jose
|
||||
enum34
|
||||
python-dotenv
|
||||
pymysql
|
||||
gunicorn
|
||||
gunicorn
|
||||
functools
|
||||
requests
|
@ -155,6 +155,36 @@ def login():
|
||||
cursor.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'])
|
||||
def logout():
|
||||
try:
|
||||
|
Reference in New Issue
Block a user