token call;
This commit is contained in:
@ -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
|
||||
|
Reference in New Issue
Block a user