i have odoo17 enterprise and fastapi project and we need to add location to sessions list and detail and we get it from ip adress of user that we get from request, heres my files, dont use external libraries for location:
redis_session.py: import redis
from datetime import datetime, timezone
import json
import uuid
import asyncio
from ..schemas.user_session_schema import UserStatus
class IntegratedAuthSessionManager:
def init(self, redis_url):
self.redis = redis.Redis(host=redis_url, port=6379, decode_responses=True)
self.cleanup_interval = 60
self.activity_timeout = 300 # 5 minutes for idle status
self.websocket_connections: Dict[str, Set[str]] = {}
code
Assistant
async def start_cleanup_task(self):
while True:
await self.cleanup_expired_sessions()
await self.update_idle_status()
await asyncio.sleep(self.cleanup_interval)
async def update_idle_status(self):
current_time = datetime.now(timezone.utc)
for key in self.redis.scan_iter("session:*"):
session_data = self.redis.get(key)
if session_data:
session = json.loads(session_data)
last_activity = datetime.fromisoformat(session['last_activity'])
if (current_time - last_activity).total_seconds() > self.activity_timeout:
session['status'] = UserStatus.IDLE
self.redis.set(key, json.dumps(session))
async def cleanup_expired_sessions(self):
current_time = datetime.now(timezone.utc).isoformat()
for key in self.redis.scan_iter("session:*"):
session_data = self.redis.get(key)
if session_data:
session = json.loads(session_data)
if session['expires_at'] <= current_time:
self.end_session(key.decode('utf-8').split(':')[1])
def create_session(self, user_data):
user_id = user_data['user_id']
session_id = str(uuid.uuid4())
session_data = {
'user_id': user_id,
'device_name': user_data['device_name'],
'device_id': user_data['device_id'],
'expires_at': user_data['expires_at'].isoformat(),
'app_version': user_data.get('app_version'),
'location': user_data.get('location'),
'last_activity': datetime.now(timezone.utc).isoformat(),
'device_unique_name': user_data.get('device_unique_name'),
'is_ios': user_data.get('is_ios'),
'status': UserStatus.ONLINE,
'lock_timestamp': datetime.now(timezone.utc).isoformat()
}
self.redis.setex(
f"session:{session_id}",
int(user_data['expires_at'].timestamp()) - int(datetime.now(timezone.utc).timestamp()),
json.dumps(session_data)
)
self.redis.sadd(f"user_sessions:{user_id}", session_id)
return session_id
# Store the session data with expiration
self.redis.setex(f"session:{session_id}", int(user_data['expires_at'].timestamp()) - int(datetime.now(timezone.utc).timestamp()), json.dumps(session_data))
# Add this session to the user's set of active sessions
self.redis.sadd(f"user_sessions:{user_id}", session_id)
return session_id
def get_session(self, session_id):
session_data = self.redis.get(f"session:{session_id}")
if not session_data:
return None
session = json.loads(session_data)
# Check if the session has expired
current_time = datetime.now(timezone.utc).isoformat()
if current_time > session['expires_at']:
self.end_session(session_id)
return None
return session
def end_session(self, session_id):
session_data = self.redis.get(f"session:{session_id}")
if session_data:
session = json.loads(session_data)
user_id = session['user_id']
self.redis.delete(f"session:{session_id}")
self.redis.srem(f"user_sessions:{user_id}", session_id)
def update_last_activity(self, session_id):
session_data = self.get_session(session_id)
if session_data:
session_data['last_activity'] = datetime.now(timezone.utc).isoformat()
self.redis.set(f"session:{session_id}", json.dumps(session_data))
def update_session(self, session_id, user_data):
session_data = self.get_session(session_id)
if session_data:
session_data.update(user_data)
self.redis.set(f"session:{session_id}", json.dumps(session_data))
def get_sessions_by_user_and_device(self, user_id, device_id):
"""
Retrieve all active sessions for a specific user and device.
"""
# Get all session IDs associated with the user
session_ids = self.redis.smembers(f"user_sessions:{user_id}")
active_sessions = []
# Iterate over all session IDs and filter by device_id
for session_id in session_ids:
session_data = self.get_session(session_id)
if session_data:
# Check if the session belongs to the given device_id
if session_data.get('device_id') == device_id:
active_sessions.append(session_id)
return active_sessions
def update_session_status(self, session_id: str, status: UserStatus):
session_data = self.get_session(session_id)
if session_data:
session_data['status'] = status
session_data['last_activity'] = datetime.now(timezone.utc).isoformat()
self.redis.set(f"session:{session_id}", json.dumps(session_data))
def register_websocket(self, session_id: str, websocket_id: str):
if session_id not in self.websocket_connections:
self.websocket_connections[session_id] = set()
self.websocket_connections[session_id].add(websocket_id)
self.update_session_status(session_id, UserStatus.ONLINE)
def unregister_websocket(self, session_id: str, websocket_id: str):
if session_id in self.websocket_connections:
self.websocket_connections[session_id].discard(websocket_id)
if not self.websocket_connections[session_id]:
self.update_session_status(session_id, UserStatus.OFFLINE)
del self.websocket_connections[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"))
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['device_name'],
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),
lock_timestamp=session_data.get('lock_timestamp') if 'lock_timestamp' in session_data else None,
)
return session_detail
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(minutes=15):
raise HTTPException(status_code=403, detail=_("Cannot end other sessions within 24 hours of login"))
redis_session_manager.end_session(session_id)
return None
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
session_schema.py:
from pydantic import BaseModel
from typing import List, Optional
from datetime import datetime
from enum import Enum
class SessionResponse(BaseModel):
current_session: SessionSchema
other_sessions: List[SessionSchema]
To add location information to the session list and details based on the user's IP address without using external libraries, you'll need to:
Extract the User's IP Address from the Request: Capture the IP address from incoming requests.
Map the IP Address to a Location: Implement a simple IP-to-location mapping manually.
Integrate the Location into Session Management: Modify your session creation and retrieval logic to include location data.
Below is a step-by-step guide to achieve this, including code snippets to help you integrate these features into your existing FastAPI project.
1. Extract the User's IP Address from the Request
To determine the user's location, you first need to extract their IP address from the incoming request. You can achieve this by creating a FastAPI dependency that retrieves the client's IP.
python
# dependencies.py
from fastapi import Request, Depends
def get_client_ip(request: Request) -> str:
"""Extract client IP address from the request."""
# Check for the X-Forwarded-For header (useful if behind a proxy)
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
2. Implement a Basic IP-to-Location Mapping
Since you're avoiding external libraries, you can create a simple IP-to-location mapping. This example uses a predefined set of IP ranges mapped to locations. You can expand this list as needed.
python
# ip_location.py
from typing import Optional
# Define a simple IP range to location mapping
# This is a simplified example and should be expanded for real-world use
IP_LOCATION_MAPPING = [
{"range_start": "192.168.1.0", "range_end": "192.168.1.255", "location": "Local Network"},
{"range_start": "8.8.8.0", "range_end": "8.8.8.255", "location": "Google DNS"},
# Add more mappings as needed
]
def ip_to_location(ip_address: str) -> Optional[str]:
"""Map an IP address to a location based on predefined ranges."""
from ipaddress import ip_address as ip_addr, IPv4Address
try:
ip = ip_addr(ip_address)
except ValueError:
return None # Invalid IP address
for mapping in IP_LOCATION_MAPPING:
start = ip_addr(mapping["range_start"])
end = ip_addr(mapping["range_end"])
if start <= ip <= end:
return mapping["location"]
return "Unknown Location"
Note: This is a highly simplified approach. For a more accurate and extensive mapping, you'd typically use a database like GeoLite2, but since external libraries and databases are off-limits, this basic method serves as a placeholder.
3. Integrate Location into Session Management
Modify your FastAPI routes and session management to include the location information.
a. Update IntegratedAuthSessionManager to Handle Location
Ensure that the create_session method accepts and stores the location.
b. Modify Session Creation Endpoint to Include Location
Assuming you have a login endpoint where sessions are created, update it to extract the IP and determine the location. Since your provided code doesn't include the login endpoint, I'll illustrate how you might modify a hypothetical login route.
python
# user_session_router.py
from fastapi import APIRouter, HTTPException, Depends, WebSocket, WebSocketDisconnect, Request
import asyncio
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, get_client_ip
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.schemas.user_session_schema import (
SessionSchema,
SessionResponse,
)
from datetime import datetime
import uuid
from ..ip_location import ip_to_location # Import the IP-to-location mapping
router = APIRouter(tags=['User Session'])
# Hypothetical login route
@router.post("/login", response_model=SessionSchema)
async def login(
request: Request, # To access the request for IP extraction
env: Annotated[Environment, Depends(odoo_env)],
partner: Annotated[Partner, Depends(get_partner_with_session)]
):
user_data = {
'user_id': partner.id,
'device_name': "ExampleDevice", # Replace with actual device info
'device_id': "DeviceID123", # Replace with actual device ID
'expires_at': datetime.now(timezone.utc) + timedelta(hours=1),
'app_version': "1.0.0", # Replace with actual app version
'is_ios': False, # Replace with actual device OS
# 'location' will be added below
}
# Extract IP and determine location
client_ip = get_client_ip(request)
location = ip_to_location(client_ip)
user_data['location'] = location
# Create session with location
session_id = redis_session_manager.create_session(user_data)
session_data = redis_session_manager.get_session(session_id)
if not session_data:
raise HTTPException(status_code=500, detail="Failed to create session")
response = SessionSchema(
session_id=session_id,
app_version=session_data.get('app_version'),
device_name=session_data['device_name'],
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),
lock_timestamp=session_data.get('lock_timestamp') or datetime.now(timezone.utc)
)
return response
Note: The above /login endpoint is hypothetical. You should integrate the IP extraction and location mapping into your actual session creation logic wherever sessions are being created (e.g., during authentication).
c. Update Existing Session Retrieval Endpoints
Your existing session retrieval endpoints already handle the location field, so no changes are needed there as long as the location is being stored correctly in the session data.
4. Ensure Location is Passed During WebSocket Communication
If you need to handle WebSocket connections that might create or modify session data, ensure that the location is appropriately managed. However, based on your provided code, location is handled during session creation, so no additional changes are required for WebSockets unless you're creating sessions there.
5. Example Complete Flow
Here's a simplified example of the complete flow integrating the above steps:
User Logs In:
The user sends a login request.
The login endpoint extracts the user's IP address.
The IP address is mapped to a location using ip_to_location.
A session is created with the location information stored in Redis.
User Retrieves Session List:
The user requests their session list.
The get_sessions endpoint retrieves all sessions for the user, including the location for each session.
Session Details Include Location:
When retrieving a specific session's details via /session/{session_id}, the location is included in the response.
6. Security and Accuracy Considerations
Accuracy: The manual IP-to-location mapping is highly simplified and may not provide accurate location data. For production systems, consider using a comprehensive IP geolocation database or service.
Security: Ensure that IP extraction handles edge cases and potential spoofing attempts, especially if your application relies on accurate location data for security decisions.
Performance: A large IP-to-location mapping can affect performance. Optimize the lookup method or consider caching mechanisms if the mapping grows in size.
7. Final Code Snippets
dependencies.py:
python
from fastapi import Request
def get_client_ip(request: Request) -> str:
"""Extract client IP address from the request."""
x_forwarded_for = request.headers.get('X-Forwarded-For')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0].strip()
else:
ip = request.client.host
return ip
ip_location.py:
python
from typing import Optional
from ipaddress import ip_address
IP_LOCATION_MAPPING = [
{"range_start": "192.168.1.0", "range_end": "192.168.1.255", "location": "Local Network"},
{"range_start": "8.8.8.0", "range_end": "8.8.8.255", "location": "Google DNS"},
# Add more mappings as needed
]
def ip_to_location(ip_address_str: str) -> Optional[str]:
"""Map an IP address to a location based on predefined ranges."""
try:
ip = ip_address(ip_address_str)
except ValueError:
return None
for mapping in IP_LOCATION_MAPPING:
start = ip_address(mapping["range_start"])
end = ip_address(mapping["range_end"])
if start <= ip <= end:
return mapping["location"]
return "Unknown Location"
user_session_router.py:
python
from fastapi import APIRouter, HTTPException, Depends, WebSocket, WebSocketDisconnect, Request
import asyncio
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, get_client_ip
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.schemas.user_session_schema import (
SessionSchema,
SessionResponse,
)
from datetime import datetime
import uuid
from ..ip_location import ip_to_location
router = APIRouter(tags=['User Session'])
@router.post("/login", response_model=SessionSchema)
async def login(
request: Request,
env: Annotated[Environment, Depends(odoo_env)],
partner: Annotated[Partner, Depends(get_partner_with_session)]
):
user_data = {
'user_id': partner.id,
'device_name': "ExampleDevice",
'device_id': "DeviceID123",
'expires_at': datetime.now(timezone.utc) + timedelta(hours=1),
'app_version': "1.0.0",
'is_ios': False,
}
client_ip = get_client_ip(request)
location = ip_to_location(client_ip)
user_data['location'] = location
session_id = redis_session_manager.create_session(user_data)
session_data = redis_session_manager.get_session(session_id)
if not session_data:
raise HTTPException(status_code=500, detail="Failed to create session")
response = SessionSchema(
session_id=session_id,
app_version=session_data.get('app_version'),
device_name=session_data['device_name'],
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),
lock_timestamp=session_data.get('lock_timestamp') or datetime.now(timezone.utc)
)
return response
# [Other existing routes remain unchanged]
By following the above steps, you can successfully add location information to your session management system based on the user's IP address without relying on external libraries. Remember to expand and refine the IP-to-location mapping to better suit your application's needs and consider integrating more accurate geolocation data as your project evolves.