Using flask library there is a python script where i get to run it from my local using python command: python odoo_login_via_api.py. Now with using static username and password variables, the endpoint /odoo_login is working fine But upon using the variable API_KEY instead of username and password, I get this error:
{"error":"Authentication failed"}
My Code:
import requests
from flask import Flask, redirect, jsonify, session, make_response
from flask_session import Session
app = Flask(__name__)
# Configure Flask session storage
app.config["SECRET_KEY"] = "supersecretkey"
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
# Odoo Credentials
ODOO_URL = "https://my-odoo-instance.odoo-test.com"
DB = "test_db"
USERNAME = "admin"
PASSWORD = "admin"
API_KEY = "82f762b0dcae925432a9b553f77421ff28649076"
def authenticate():
"""Authenticate with Odoo and return the session ID."""
auth_url = f"{ODOO_URL}/web/session/authenticate"
auth_data = {
"jsonrpc": "2.0",
"params": {
"db": DB,
"login": USERNAME,
"password": PASSWORD,
}
}
session_req = requests.Session()
response = session_req.post(auth_url, json=auth_data)
print("Response------>", response)
if response.status_code == 200 and response.json().get("result", {}).get("uid"):
session_id = session_req.cookies.get("session_id")
return session_id
return None
def check_session(session_id):
"""Check if the session is still valid in Odoo."""
session_check_url = f"{ODOO_URL}/web/session/ping"
cookies = {"session_id": session_id}
response = requests.get(session_check_url, cookies=cookies)
# If response is valid, the session is active.
return response.status_code == 200
@app.route("/odoo_login")
def login():
"""Handle login by checking stored session ID or authenticating again."""
if "session_id" in session:
stored_session_id = session["session_id"]
print(f"Using stored session_id: {stored_session_id}")
# Check if the session is still valid
if check_session(stored_session_id):
# Create response object and pass session_id in URL and cookies
response = make_response(redirect(f"{ODOO_URL}/web?session_id={stored_session_id}"))
response.set_cookie("session_id", stored_session_id, domain=".odoo-test.com", path="/", secure=True)
print(f"Redirecting to {ODOO_URL}/web with session_id.")
return response
else:
print("Session expired, Authenticating Again...")
# First-time login or expired session
new_session_id = authenticate()
if new_session_id:
session["session_id"] = new_session_id # Store session ID
print(f"New session_id created: {new_session_id}")
# Create response object and set session cookie for Odoo
response = make_response(redirect(f"{ODOO_URL}/web?session_id={new_session_id}"))
response.set_cookie("session_id", new_session_id, domain=".odoo-test.com", path="/", secure=True)
print(f"Redirecting to {ODOO_URL}/web with new session_id.")
return response
return jsonify({"error": "Authentication failed"}), 401
@app.route("/odoo_logout")
def logout():
"""Clear stored session ID."""
session.pop("session_id", None)
print("Logged out and session_id cleared.")
return jsonify({"message": "Logged out"})
if __name__ == "__main__":
app.run(debug=True)