travis_login / app.py
vinay0123's picture
Update app.py
38936f4 verified
from flask import Flask, request, jsonify
from pymongo import MongoClient
from flask_cors import CORS
from bson import ObjectId
import json
import os
app = Flask(__name__)
CORS(app)
print("applied CORS")
# MongoDB Connection
MONGO_URI = "mongodb+srv://nanduvinay719:76qqKRX4zC97yQun@travis.744fuyn.mongodb.net/?retryWrites=true&w=majority&appName=travis"
client = MongoClient(MONGO_URI)
print("connected to mongodb")
db = client["travisDB"]
# Define collections
user_collection = db["users"]
agent_collection = db["agents"]
# Helper function to convert ObjectId to string for JSON serialization
class JSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, ObjectId):
return str(obj)
return json.JSONEncoder.default(self, obj)
@app.route("/", methods=["GET"])
def home():
return jsonify({"message": "Travis Backend API is running"})
@app.route("/login", methods=["POST"])
def login():
data = request.json
email = data.get("email")
password = data.get("password")
role = data.get("role")
try:
# First, try to find the user based on email and role
user = None
# Try to find in the appropriate collection based on provided role
if role == "admin":
user = user_collection.find_one({"email": email, "password": password})
else:
user = agent_collection.find_one({"email": email, "password": password})
# If user is found, verify their role
if user:
# Return user information including their actual role from DB
return jsonify({
"success": True,
"role": user.get("role"),
"userId": str(user.get("_id"))
})
else:
# Try the other collection as fallback (in case the user selected the wrong role)
other_collection = agent_collection if role == "admin" else user_collection
other_user = other_collection.find_one({"email": email, "password": password})
if other_user:
# User exists but in the other collection
return jsonify({
"success": True,
"role": other_user.get("role"),
"userId": str(other_user.get("_id"))
})
else:
# No user found in either collection
return jsonify({"success": False, "message": "Invalid credentials"})
except Exception as e:
print(f"Login error: {e}")
return jsonify({"success": False, "message": "Server error"}), 500
@app.route("/register", methods=["POST"])
def register():
print(f"Registration request received: {request.json}")
data = request.json
email = data.get("email")
password = data.get("password")
if not email or not password:
print("Missing required fields")
return jsonify({
"success": False,
"message": "Email and password are required"
}), 400
try:
# Check if an agent with this email already exists
existing_agent = agent_collection.find_one({"email": email})
if existing_agent:
return jsonify({
"success": False,
"message": "An agent with this email already exists"
}), 400
# Check if a user with this email exists in the User collection
existing_user = user_collection.find_one({"email": email})
if existing_user:
return jsonify({
"success": False,
"message": "A user with this email already exists"
}), 400
# Create new agent with role explicitly set to "agent"
new_agent = {
"email": email,
"password": password,
"role": "agent" # Always set to "agent" as required
}
# Save the new agent to the database
result = agent_collection.insert_one(new_agent)
return jsonify({
"success": True,
"message": "Agent registered successfully",
"role": "agent"
}), 201
except Exception as e:
print(f"Registration error: {e}")
return jsonify({
"success": False,
"message": "Server error during registration"
}), 500
if __name__ == "__main__":
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 7860)))