Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

in here i dont have ipadress: from fastapi import APIRouter, HTTPException, Depends,…

  1. User

    in here i dont have ip_adress: from fastapi import APIRouter, HTTPException, Depends, WebSocket, WebSocketDisconnect, Request import asyncio import pytz from datetime import timedelta, timezone from typing import Annotated from odoo.api import Environment from odoo import _ from ..dependencies import odoo_env, get_partner_with_session, get_partner_with_session_id from ..schemas.user_session_schema import UserStatus from odoo.addons.base.models.res_partner import Partner from odoo.addons.fastapi_addon.utils.redis_session import redis_session_manager from odoo.addons.fastapi_addon.utils.ip_geolocation import get_client_ip, geolocation_service from odoo.addons.fastapi_addon.schemas.user_session_schema import ( SessionSchema, SessionResponse, ) from datetime import datetime import logging

    _logger = logging.getLogger(name)

    router = APIRouter(tags=['User Session']) tashkent_tz = pytz.timezone("Asia/Tashkent")

    @router.get("/sessions", response_model=SessionResponse) async def get_sessions( request: Request, env: Annotated[Environment, Depends(odoo_env)], partner: Annotated[Partner, Depends(get_partner_with_session)], current_session_id: str = Depends(get_partner_with_session_id) ): user_id = partner.id session_ids = redis_session_manager.redis.smembers(f"user_sessions:{user_id}")

    current_session_data = redis_session_manager.get_session(current_session_id)
    if not current_session_data:
        raise HTTPException(status_code=404, detail=_("Current session not found"))
    
    if not current_session_data:
        _logger.critical("Current session data: %s", request)
        client_ip = get_client_ip(request)
        _logger.critical(f"Client IP: {client_ip}")
        if client_ip and (
            not current_session_data.get('ip_address') or
            current_session_data.get('ip_address') != client_ip
        ):
            location_data = await geolocation_service.get_location(client_ip)
            if location_data:
                current_session_data = {
                    'location': location_data['location_string'],
                    'ip_address': client_ip,
                    'location_data': location_data
                }
                redis_session_manager.update_session(current_session_id, current_session_data)
        else:
            raise HTTPException(status_code=404, detail=_("Current session not found"))
    
    response = SessionResponse(
        current_session=SessionSchema(
            session_id=current_session_id,
            app_version=current_session_data.get('app_version'),
            device_name=current_session_data.get('device_name'),
            ip_address=current_session_data.get('ip_address'),
            location=current_session_data.get('location'),
            last_activity=current_session_data.get('last_activity'),
            is_ios=current_session_data.get('is_ios') or False,
            status=current_session_data.get('status', UserStatus.OFFLINE)
        ),
        other_sessions=[]
    )
    
    for session_id in session_ids:
        if session_id != current_session_id:
            session_data = redis_session_manager.get_session(session_id)
            if session_data:
                session_info = SessionSchema(
                    session_id=session_id,
                    app_version=session_data.get('app_version'),
                    device_name=session_data.get('device_name'),
                    ip_address=session_data.get('ip_address'),
                    location=session_data.get('location'),
                    last_activity=session_data.get('last_activity'),
                    is_ios=session_data.get('is_ios') or False,
                    status=session_data.get('status', UserStatus.OFFLINE)
                )
                response.other_sessions.append(session_info)
    _logger.critical('Sessions dat: %s', current_session_data)
    _logger.critical('Sessions response: %s', response)
    return response
    

    @router.get("/session/{session_id}", response_model=SessionSchema) async def get_session_detail( session_id: str, env: Annotated[Environment, Depends(odoo_env)], partner: Annotated[Partner, Depends(get_partner_with_session)] ): user_id = partner.id user_sessions = redis_session_manager.redis.smembers(f"user_sessions:{user_id}")

    if session_id not in user_sessions:
        raise HTTPException(status_code=404, detail=_("Session not found"))
    
    session_data = redis_session_manager.get_session(session_id)
    if not session_data:
        raise HTTPException(status_code=404, detail=_("Session data not found"))
    
    session_detail = SessionSchema(
        session_id=session_id,
        app_version=session_data.get('app_version'),
        device_name=session_data.get('device_name'),
        location=session_data.get('location'),
        ip_address=session_data.get('ip_address'),
        last_activity=session_data.get('last_activity'),
        is_ios=session_data.get('is_ios') or False,
        status=session_data.get('status', UserStatus.OFFLINE)
    )
    
    return session_detail
    

    @router.delete("/logout/all-except-current", status_code=204) async def logout_all_except_current( env: Annotated[Environment, Depends(odoo_env)], partner: Annotated[Partner, Depends(get_partner_with_session)], current_session_id: str = Depends(get_partner_with_session_id) ): user_id = partner.id user_sessions = redis_session_manager.redis.smembers(f"user_sessions:{user_id}")

    for session_id in user_sessions:
        if session_id != current_session_id:
            session_data = redis_session_manager.get_session(current_session_id)
            if session_data:
                lock_timestamp = datetime.fromisoformat(session_data['lock_timestamp'])
                if (datetime.now(timezone.utc) - lock_timestamp) < timedelta(hours=24):
                    raise HTTPException(status_code=403, detail=_("Cannot end other sessions within 24 hours of login"))
    
            redis_session_manager.end_session(session_id)   
    
    return None
    

    @router.delete("/logout/current", status_code=204)
    async def logout_current_session( env: Annotated[Environment, Depends(odoo_env)], partner: Annotated[Partner, Depends(get_partner_with_session)], current_session_id: str = Depends(get_partner_with_session_id) ): redis_session_manager.end_session(current_session_id) return None

    @router.delete("/logout/{session_id}", status_code=204) async def logout_from_session( session_id: str, env: Annotated[Environment, Depends(odoo_env)], partner: Annotated[Partner, Depends(get_partner_with_session)], current_session_id: str = Depends(get_partner_with_session_id) ): user_id = partner.id user_sessions = redis_session_manager.redis.smembers(f"user_sessions:{user_id}")

    if session_id not in user_sessions:
        raise HTTPException(status_code=404, detail=_("Session not found"))
    
    if session_id == current_session_id:
        raise HTTPException(status_code=400, detail=_("Cannot logout from current session using this endpoint"))
    
    session_data = redis_session_manager.get_session(current_session_id)
    if session_data:
        lock_timestamp = datetime.fromisoformat(session_data['lock_timestamp'])
        if (datetime.now(timezone.utc) - lock_timestamp) < timedelta(hours=24):
            raise HTTPException(status_code=403, detail=_("Cannot end other sessions within 24 hours of login"))
    
    redis_session_manager.end_session(session_id)
    return None
    

    but in here i have: from odoo import http from odoo.http import request from dotenv import load_dotenv import os import json import logging from odoo.addons.fastapi_addon.utils.ip_geolocation import get_client_ip

    _logger = logging.getLogger(name)

    class CommetaApi(http.Controller): @http.route('/api/auth/generate-link', type='http', auth='public', methods=['GET']) def generate_commeta_auth_link(self): result = request.env['res.partner'].sudo().generate_commeta_oauth_link() # return result print(result) return http.request.make_response(json.dumps(result), headers={'Content-Type': 'application/json'})

    @http.route('/api/auth/callback', type='json', auth='public', methods=['POST'], csrf=False)
    def commeta_exchange(self, **kw):
        # Try to get parameters from both query string and request body
        try:
            # Manually parse JSON data from the request body
            body = request.httprequest.data.decode('utf-8')
            ip_address = get_client_ip(request)
            data = json.loads(body)
            code = data.get('code')
            code_verifier = data.get('code_verifier')
            device_data = {
                'device_name': data.get('device_name'),
                'device_unique_name': data.get('device_unique_name'),
                'is_ios': data.get('is_ios')
            }
        except json.JSONDecodeError:
            _logger.error("Failed to parse JSON body")
            return {"error": "Invalid JSON in request body"}
    
        if not code or not code_verifier:
            _logger.error("Authorization code and code verifier are required")
            return "Error: Authorization code and code verifier are required"
    
        try:
            token_data = request.env['res.partner'].sudo().commeta_exchange_code(code, code_verifier)
            if not token_data:
                _logger.error("Failed to exchange code for token")
                return "Error: Failed to exchange code for token"
    
            _logger.info(f"Token data received: {token_data}")
    
            result = request.env['res.partner'].sudo().commeta_authenticate(token_data, device_data, ip_address)
            if 'error' in result:
                _logger.error(f"Authentication error: {result['error']}")
                return f"Error: {result['error']}"
    
            _logger.info("Authentication successful")
            print(result, 'this is result')
            return result
    
        except Exception as e:
            _logger.exception("Exception during authentication process")
            return f"Error: An unexpected error occurred - {str(e)}"
    
    
    @http.route('/api/user_info', type='json', auth='public', methods=['GET'])
    def get_user_info(self, **post):
        token = request.httprequest.headers.get('Authorization')
        if not token:
            return {'error': 'No token provided'}
        user = request.env['res.partner'].sudo().validate_commeta_token(token)
        if not user:
            return {'error': "Invalid token"}
        return {
            'id': user.id,
            "name": user.name,
            "pnfl": user.pnfl,
            'language': user.language,
            'avatar': user.avatar.decode('utf-8') if user.avatar else None,
        }
    
    @http.route('/test', type='http', auth='public', methods=['GET'])
    def test(self, **kw):
        return 'hello', fix my router, but if i use odoo.http request, i faced errors
    
  2. Assistant

    To resolve the issue you're encountering with obtaining the ip_address in your FastAPI router while integrating with Odoo, it's essential to ensure that you correctly handle the request objects and dependencies within both frameworks. Mixing Odoo's http.request with FastAPI's Request can lead to unexpected errors because they are fundamentally different objects.

    Here's a step-by-step guide to fixing your router and properly obtaining the client's IP address in the FastAPI context:

    1. Avoid Mixing Odoo's http.request with FastAPI's Request

    Odoo's http.request is designed for traditional Odoo controllers and doesn't integrate seamlessly with FastAPI's asynchronous Request object. Instead, use FastAPI's Request exclusively within your FastAPI routes.

    2. Implement a Compatible get_client_ip Function for FastAPI

    Ensure that your get_client_ip function is compatible with FastAPI's Request object. Here's how you can redefine this function:

    from fastapi import Request
    from typing import Optional
    
    def get_client_ip(request: Request) -> Optional[str]:
        """Extract the client IP address from the FastAPI Request."""
        x_forwarded_for = request.headers.get('X-Forwarded-For')
        if x_forwarded_for:
            # In case of multiple IPs, take the first one
            ip = x_forwarded_for.split(',')[0].strip()
        else:
            ip = request.client.host
        return ip
    

    Notes:

    • Handling Proxies: If your FastAPI application is behind a proxy (like Nginx), ensure that the proxy correctly forwards the X-Forwarded-For header and that your FastAPI app is configured to trust these headers. You can use middleware like TrustedHostMiddleware or configure Uvicorn with --proxy-headers.

    3. Refactor Your FastAPI Router

    Given the initial FastAPI router you provided, let's refactor it to correctly obtain the client IP and handle session data without using Odoo's http.request.

    Here's the revised version of your router:

    from fastapi import APIRouter, HTTPException, Depends, Request
    from typing import Annotated
    from odoo.api import Environment
    from odoo import _
    from ..dependencies import odoo_env, get_partner_with_session, get_partner_with_session_id
    from ..schemas.user_session_schema import UserStatus, SessionSchema, SessionResponse
    from odoo.addons.base.models.res_partner import Partner
    from odoo.addons.fastapi_addon.utils.redis_session import redis_session_manager
    from odoo.addons.fastapi_addon.utils.ip_geolocation import get_client_ip, geolocation_service
    from datetime import datetime, timezone, timedelta
    import pytz
    import logging
    
    _logger = logging.getLogger(__name__)
    
    router = APIRouter(tags=['User Session'])
    tashkent_tz = pytz.timezone("Asia/Tashkent")
    
    
    @router.get("/sessions", response_model=SessionResponse)
    async def get_sessions(
        request: Request,
        env: Annotated[Environment, Depends(odoo_env)],
        partner: Annotated[Partner, Depends(get_partner_with_session)],
        current_session_id: str = Depends(get_partner_with_session_id)
    ):
        user_id = partner.id
        session_ids = redis_session_manager.redis.smembers(f"user_sessions:{user_id}")
    
        current_session_data = redis_session_manager.get_session(current_session_id)
        if not current_session_data:
            _logger.critical("Current session data not found for session_id: %s", current_session_id)
            client_ip = get_client_ip(request)
            _logger.critical(f"Client IP: {client_ip}")
    
            if client_ip:
                location_data = await geolocation_service.get_location(client_ip)
                if location_data:
                    current_session_data = {
                        'location': location_data.get('location_string', ''),
                        'ip_address': client_ip,
                        'location_data': location_data
                    }
                    redis_session_manager.update_session(current_session_id, current_session_data)
            else:
                raise HTTPException(status_code=404, detail=_("Current session not found"))
    
        # After attempting to update, check again
        if not current_session_data:
            raise HTTPException(status_code=404, detail=_("Current session not found"))
    
        response = SessionResponse(
            current_session=SessionSchema(
                session_id=current_session_id,
                app_version=current_session_data.get('app_version'),
                device_name=current_session_data.get('device_name'),
                ip_address=current_session_data.get('ip_address'),
                location=current_session_data.get('location'),
                last_activity=current_session_data.get('last_activity'),
                is_ios=current_session_data.get('is_ios') or False,
                status=current_session_data.get('status', UserStatus.OFFLINE)
            ),
            other_sessions=[]
        )
    
        for session_id in session_ids:
            if session_id != current_session_id:
                session_data = redis_session_manager.get_session(session_id)
                if session_data:
                    session_info = SessionSchema(
                        session_id=session_id,
                        app_version=session_data.get('app_version'),
                        device_name=session_data.get('device_name'),
                        ip_address=session_data.get('ip_address'),
                        location=session_data.get('location'),
                        last_activity=session_data.get('last_activity'),
                        is_ios=session_data.get('is_ios') or False,
                        status=session_data.get('status', UserStatus.OFFLINE)
                    )
                    response.other_sessions.append(session_info)
        
        _logger.critical('Sessions data: %s', current_session_data)
        _logger.critical('Sessions response: %s', response)
        return response
    

    Key Changes and Explanations:

    1. Revised get_client_ip Usage:

      • Function Call: We're using the newly defined get_client_ip function that takes FastAPI's request as an argument.
      • Error Handling: If the client IP isn't found, we raise a 404 error. Otherwise, we attempt to fetch the location data and update the session accordingly.
    2. Logical Flow Adjustment:

      • Session Data Check: After attempting to update current_session_data with the client IP and location, we re-check whether current_session_data exists before proceeding. This ensures that the session is valid and has the necessary information.
    3. Logging Enhancements:

      • Detailed Logs: Improved logging messages to better trace the flow and identify where issues might occur.
      • Sensitive Data Caution: Ensure that sensitive information (like IP addresses) isn't logged in production environments. Adjust the logging level and data accordingly based on your security requirements.

    4. Ensure Proper Middleware Configuration

    If your FastAPI application is behind a proxy (such as Nginx or a load balancer), you need to correctly handle X-Forwarded-For headers to accurately obtain the client's IP address. Here's how you can configure Uvicorn and FastAPI to respect these headers:

    • Running Uvicorn with Proxy Headers:

      When starting your FastAPI application with Uvicorn, include the --proxy-headers flag to allow it to read headers set by the proxy:

      uvicorn your_app:app --host 0.0.0.0 --port 8000 --proxy-headers
      
    • Using STARLETTE_TRUSTED_HOSTS Middleware:

      Alternatively, you can add middleware to trust certain headers. Here's an example using Starlette's TrustedHostMiddleware:

      from fastapi import FastAPI
      from starlette.middleware.trustedhost import TrustedHostMiddleware
      
      app = FastAPI()
      
      app.add_middleware(
          TrustedHostMiddleware,
          allowed_hosts=["your-domain.com", "www.your-domain.com", "localhost", "127.0.0.1"],
      )
      
      # Include your routers here
      

      Note: Adjust allowed_hosts to match the domains/IPs that should be trusted.

    5. Review and Refactor Other Routes (Optional)

    Ensure that other routes within your FastAPI router also adhere to the same principles—using FastAPI's Request instead of Odoo's http.request and correctly handling dependencies and session management.

    For instance, if you have a route that previously used Odoo's request object, refactor it similarly:

    @router.get("/session/{session_id}", response_model=SessionSchema)
    async def get_session_detail(
        session_id: str,
        env: Annotated[Environment, Depends(odoo_env)],
        partner: Annotated[Partner, Depends(get_partner_with_session)]
    ):
        user_id = partner.id
        user_sessions = redis_session_manager.redis.smembers(f"user_sessions:{user_id}")
    
        if session_id not in user_sessions:
            raise HTTPException(status_code=404, detail=_("Session not found"))
    
        session_data = redis_session_manager.get_session(session_id)
        if not session_data:
            raise HTTPException(status_code=404, detail=_("Session data not found"))
    
        session_detail = SessionSchema(
            session_id=session_id,
            app_version=session_data.get('app_version'),
            device_name=session_data.get('device_name'),
            location=session_data.get('location'),
            ip_address=session_data.get('ip_address'),
            last_activity=session_data.get('last_activity'),
            is_ios=session_data.get('is_ios') or False,
            status=session_data.get('status', UserStatus.OFFLINE)
        )
    
        return session_detail
    

    6. Handle Potential Errors and Edge Cases

    Ensure that all possible error scenarios are handled gracefully, and appropriate HTTP status codes are returned. For example:

    • Invalid Session ID: Return a 404 Not Found if the session ID doesn't exist.
    • Unauthorized Access: If a user attempts to access or modify another user's session, return a 403 Forbidden.
    • Internal Server Errors: Log unexpected exceptions and return a 500 Internal Server Error without exposing sensitive details.

    7. Testing

    After refactoring, thoroughly test your endpoints to ensure they behave as expected:

    • Local Testing: Start your FastAPI application locally and use tools like curl or Postman to test the endpoints.
    • Proxy Testing: If using a proxy, ensure that IP addresses are correctly forwarded and captured.
    • Edge Cases: Test scenarios where headers might be missing or malformed.

    8. Example of a Complete Refactored Router

    Here's the complete refactored router with the get_sessions endpoint as an example:

    from fastapi import APIRouter, HTTPException, Depends, Request
    from typing import Annotated
    from odoo.api import Environment
    from odoo import _
    from ..dependencies import odoo_env, get_partner_with_session, get_partner_with_session_id
    from ..schemas.user_session_schema import UserStatus, SessionSchema, SessionResponse
    from odoo.addons.base.models.res_partner import Partner
    from odoo.addons.fastapi_addon.utils.redis_session import redis_session_manager
    from odoo.addons.fastapi_addon.utils.ip_geolocation import get_client_ip, geolocation_service
    from datetime import datetime, timezone, timedelta
    import pytz
    import logging
    
    _logger = logging.getLogger(__name__)
    
    router = APIRouter(tags=['User Session'])
    tashkent_tz = pytz.timezone("Asia/Tashkent")
    
    
    def get_client_ip(request: Request) -> str:
        """Extract the client IP address from the FastAPI Request."""
        x_forwarded_for = request.headers.get('X-Forwarded-For')
        if x_forwarded_for:
            # In case of multiple IPs, take the first one
            ip = x_forwarded_for.split(',')[0].strip()
        else:
            ip = request.client.host
        return ip
    
    
    @router.get("/sessions", response_model=SessionResponse)
    async def get_sessions(
        request: Request,
        env: Annotated[Environment, Depends(odoo_env)],
        partner: Annotated[Partner, Depends(get_partner_with_session)],
        current_session_id: str = Depends(get_partner_with_session_id)
    ):
        user_id = partner.id
        session_ids = redis_session_manager.redis.smembers(f"user_sessions:{user_id}")
    
        current_session_data = redis_session_manager.get_session(current_session_id)
        if not current_session_data:
            _logger.critical("Current session data not found for session_id: %s", current_session_id)
            client_ip = get_client_ip(request)
            _logger.critical(f"Client IP: {client_ip}")
    
            if client_ip:
                location_data = await geolocation_service.get_location(client_ip)
                if location_data:
                    current_session_data = {
                        'location': location_data.get('location_string', ''),
                        'ip_address': client_ip,
                        'location_data': location_data
                    }
                    redis_session_manager.update_session(current_session_id, current_session_data)
            if not current_session_data:
                raise HTTPException(status_code=404, detail=_("Current session not found"))
    
        response = SessionResponse(
            current_session=SessionSchema(
                session_id=current_session_id,
                app_version=current_session_data.get('app_version'),
                device_name=current_session_data.get('device_name'),
                ip_address=current_session_data.get('ip_address'),
                location=current_session_data.get('location'),
                last_activity=current_session_data.get('last_activity'),
                is_ios=current_session_data.get('is_ios') or False,
                status=current_session_data.get('status', UserStatus.OFFLINE)
            ),
            other_sessions=[]
        )
    
        for session_id in session_ids:
            if session_id != current_session_id:
                session_data = redis_session_manager.get_session(session_id)
                if session_data:
                    session_info = SessionSchema(
                        session_id=session_id,
                        app_version=session_data.get('app_version'),
                        device_name=session_data.get('device_name'),
                        ip_address=session_data.get('ip_address'),
                        location=session_data.get('location'),
                        last_activity=session_data.get('last_activity'),
                        is_ios=session_data.get('is_ios') or False,
                        status=session_data.get('status', UserStatus.OFFLINE)
                    )
                    response.other_sessions.append(session_info)
        
        _logger.critical('Sessions data: %s', current_session_data)
        _logger.critical('Sessions response: %s', response)
        return response
    

    9. Final Recommendations

    • Separation of Concerns: Maintain a clear separation between Odoo controllers and FastAPI routes. Use FastAPI for API endpoints and Odoo's traditional controllers for web routes if necessary.

    • Asynchronous Operations: Ensure that all I/O-bound operations in FastAPI are handled asynchronously to leverage FastAPI’s performance benefits.

    • Security Considerations: Always validate and sanitize inputs, especially when dealing with session management and authentication to prevent security vulnerabilities.

    • Logging Practices: Use appropriate logging levels (debug, info, warning, error, critical) based on the importance of the messages, and avoid logging sensitive information in production environments.

    By following these steps and ensuring that your FastAPI router exclusively uses FastAPI’s Request object and compatible utility functions, you should be able to obtain the client's IP address without encountering errors related to Odoo's http.request.