Search code examples
pythonauthenticationodoo

Odoo API returns 'Invalid credentials' even with correct username and password


I’m working with Odoo (version 15) and trying to implement a login API. I have created a controller that checks the username and password, but it always returns "Invalid credentials" even when I use the correct login information.

Here’s my code:

    # -*- coding: utf-8 -*-
    from odoo import http
    
    class TestApi(http.Controller):
        @http.route("/api/check_login", methods=["POST"], type="json", auth="public", csrf=False)
        def check_login(self, **kwargs):
            username = kwargs.get('username')
            password = kwargs.get('password')
            
            if username == "admin" and password == "admin":  # Replace with actual validation
                return {
                    "message": "User is logged in.",
                    "username": username
                }
            else:
                return {
                    "error": "Invalid credentials."
                }

Steps Taken: .I tested the API using Postman with a POST request to http:///api/check_login. .I used the following JSON body:

    {
        "username": "admin",
        "password": "admin"
    }

.I confirmed that the credentials work in the Odoo web interface. Questions: What might be causing the API to not recognize valid credentials? Are there any additional configurations I should check? Is there a better method to handle user authentication in Odoo?


Solution

  • The issue is that the original code expected data in kwargs, which only works for query parameters or form-encoded data. Since the request sent contains a JSON payload in the request body, the username and password were not being retrieved. The modified code resolves this by explicitly parsing the JSON data from the request body using json.loads(), ensuring the credentials are correctly accessed and processed.

    # -*- coding: utf-8 -*-
    
    from odoo import http
    import json
        
    
    class TestApi(http.Controller):
       @http.route("/api/check_login", methods=["POST"], type="json",
                    auth="public", csrf=False)
        def check_login(self):
            request_data = json.loads(request.httprequest.data)
            username = request_data.get('username')
            password = request_data.get('password')
    
            if username == "admin" and password == "admin":  # Replace with actual validation
                return {
                    "message": "User is logged in.",
                    "username": username
                }
            else:
                return {
                    "error": "Invalid credentials."
                }