Skip to content

Commit

Permalink
update fixed dashboard api so login works
Browse files Browse the repository at this point in the history
error with dashboard api causing login to fail. dashboard api now works fully.
  • Loading branch information
Phinetwork committed Dec 10, 2024
1 parent 0dde3f2 commit 0de87e5
Show file tree
Hide file tree
Showing 7 changed files with 115 additions and 146 deletions.
Binary file modified .DS_Store
Binary file not shown.
Binary file modified backend/.DS_Store
Binary file not shown.
3 changes: 2 additions & 1 deletion backend/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,8 @@ def login():
if not user or not check_password_hash(user.hashed_password, password):
return jsonify({"error": "Invalid email or password!"}), 401

access_token = create_access_token(identity=user.id)
# Include a subject claim (sub) in the token
access_token = create_access_token(identity=user.id, additional_claims={"sub": str(user.id)})
return jsonify({"token": access_token}), 200
except Exception as e:
app.logger.error(f"Error in /api/login: {e}", exc_info=True)
Expand Down
71 changes: 50 additions & 21 deletions backend/routes/dashboard.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,58 @@
from flask import Blueprint, request, jsonify
from utils.token import verify_token
from models import User
import logging

dashboard = Blueprint('dashboard', __name__)

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("dashboard")

@dashboard.route('/api/dashboard', methods=['GET'])
def get_dashboard():
token = request.headers.get('Authorization')
if not token:
return jsonify({"message": "Token is missing"}), 401

user_id = verify_token(token)
if not user_id:
return jsonify({"message": "Invalid or expired token"}), 401

user = User.query.get(user_id)
if not user:
return jsonify({"message": "User not found"}), 404

# Example dashboard data
dashboard_data = {
"username": user.username,
"email": user.email,
"last_login": user.last_login, # Assuming a last_login field
"activity": [], # Fetch user-specific activity
}

return jsonify({"message": "Dashboard data fetched successfully", "data": dashboard_data}), 200
try:
# Step 1: Get token from Authorization header
token = request.headers.get('Authorization')
if not token:
logger.warning("Authorization token is missing")
return jsonify({"message": "Authorization token is missing"}), 401

# Extract the Bearer token
if token.startswith("Bearer "):
token = token.split(" ")[1]
else:
logger.warning("Invalid Authorization format")
return jsonify({"message": "Invalid Authorization format"}), 401

# Step 2: Verify the token and extract user_id
try:
user_id = verify_token(token) # Assumes verify_token returns user_id or raises an exception
if not user_id:
logger.warning("Invalid or expired token")
return jsonify({"message": "Invalid or expired token"}), 401
logger.info(f"Token verified successfully for user_id: {user_id}")
except Exception as e:
logger.error(f"Token verification failed: {e}")
return jsonify({"message": "Invalid or expired token"}), 401

# Step 3: Fetch the user from the database
user = User.query.get(user_id)
if not user:
logger.warning(f"User not found for user_id: {user_id}")
return jsonify({"message": "User not found"}), 404

# Step 4: Construct the dashboard data
dashboard_data = {
"username": user.username or "Unknown",
"email": user.email or "Not provided",
"last_login": getattr(user, "last_login", "Not tracked"), # Placeholder if last_login is not implemented
"activity": [] # Placeholder for user-specific activity
}

logger.info(f"Dashboard data prepared successfully for user_id: {user_id}")
return jsonify({"message": "Dashboard data fetched successfully", "data": dashboard_data}), 200

except Exception as e:
logger.error(f"Unexpected error in /api/dashboard: {e}", exc_info=True)
return jsonify({"message": "An unexpected error occurred"}), 500
109 changes: 62 additions & 47 deletions backend/test_api.py
Original file line number Diff line number Diff line change
@@ -1,76 +1,91 @@
import requests
import random
import string

BASE_URL = "http://127.0.0.1:5001" # Change this to your server's base URL
BASE_URL = "http://127.0.0.1:5001" # Ensure this matches your backend server
HEADERS = {"Content-Type": "application/json"}

# Test endpoints
def log_error(response):
"""Log detailed error information for debugging."""
print(f"Status Code: {response.status_code}")
try:
print(f"Response JSON: {response.json()}")
except Exception as e:
print(f"Error decoding JSON: {e}")
print(f"Response Text: {response.text}")


def generate_random_user():
"""Generate a unique username and email."""
random_str = ''.join(random.choices(string.ascii_letters + string.digits, k=8))
username = f"user_{random_str}"
email = f"{username}@example.com"
return username, email, "testpassword"


def test_register():
"""Test the user registration endpoint."""
print("Testing /api/register...")
username, email, password = generate_random_user()
payload = {
"username": "testuser",
"email": "testuser@example.com",
"password": "testpassword"
"username": username,
"email": email,
"password": password
}
response = requests.post(f"{BASE_URL}/api/register", json=payload, headers=HEADERS)
print(f"Response: {response.status_code} - {response.json()}\n")
print(f"Response: {response.status_code}")
if response.status_code == 201:
print(f"User registered successfully: {username}, {email}")
else:
log_error(response)
return email, password


def test_login():
def test_login(email, password):
"""Test the user login endpoint."""
print("Testing /api/login...")
payload = {
"email": "testuser@example.com",
"password": "testpassword"
"email": email,
"password": password
}
response = requests.post(f"{BASE_URL}/api/login", json=payload, headers=HEADERS)
print(f"Response: {response.status_code} - {response.json()}\n")
print(f"Response: {response.status_code}")
if response.status_code == 200:
return response.json().get("token")
return None
token = response.json().get("token")
print(f"Login successful, token: {token}")
return token
else:
log_error(response)
return None


def test_dashboard(token):
"""Test the dashboard endpoint."""
print("Testing /api/dashboard...")
headers = {**HEADERS, "Authorization": f"Bearer {token}"}
response = requests.get(f"{BASE_URL}/api/dashboard", headers=headers)
print(f"Response: {response.status_code} - {response.json()}\n")

def test_matches():
print("Testing /api/matches...")
payload = {
"skills": ["python", "machine learning", "flask"]
}
response = requests.post(f"{BASE_URL}/api/matches", json=payload, headers=HEADERS)
print(f"Response: {response.status_code} - {response.json()}\n")
print(f"Response: {response.status_code}")
if response.status_code == 200:
print("Dashboard data fetched successfully!")
print(response.json())
else:
log_error(response)

def test_skills():
print("Testing /api/skills...")
payload = {
"interests": ["technology", "data science"]
}
response = requests.post(f"{BASE_URL}/api/skills", json=payload, headers=HEADERS)
print(f"Response: {response.status_code} - {response.json()}\n")

def test_habits():
print("Testing /api/habits...")
payload = {
"side_hustle": "freelance development"
}
response = requests.post(f"{BASE_URL}/api/habits", json=payload, headers=HEADERS)
print(f"Response: {response.status_code} - {response.json()}\n")
def run_tests():
"""Run all API tests."""
print("Starting API tests...\n")

def test_root():
print("Testing / (root)...")
response = requests.get(f"{BASE_URL}/")
print(f"Response: {response.status_code} - {response.json()}\n")
# Test user registration and login
email, password = test_register()
token = test_login(email, password)

# Run all tests
def run_tests():
test_root()
test_register()
token = test_login()
# Test dashboard if login is successful
if token:
test_dashboard(token)
test_matches()
test_skills()
test_habits()
else:
print("Login failed. Skipping dashboard test.")


if __name__ == "__main__":
run_tests()
76 changes: 0 additions & 76 deletions backend/utils/test_api.py

This file was deleted.

2 changes: 1 addition & 1 deletion backend/utils/token.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@

def generate_token(user_id):
expiration = datetime.utcnow() + timedelta(days=7)
return jwt.encode({"user_id": user_id, "exp": expiration}, SECRET_KEY, algorithm="HS
return jwt.encode({"sub": str(user_id), "exp": expiration}, SECRET_KEY, algorithm="HS256")

0 comments on commit 0de87e5

Please sign in to comment.