nova-api/api/db/logs.py

89 lines
2.3 KiB
Python
Raw Normal View History

import os
2023-08-03 03:50:04 +02:00
import time
2023-10-08 00:28:13 +02:00
import asyncio
from dotenv import load_dotenv
from motor.motor_asyncio import AsyncIOMotorClient
2023-10-08 00:28:13 +02:00
try:
from helpers import network
except ImportError:
pass
2023-08-04 03:30:56 +02:00
load_dotenv()
2023-08-12 18:20:18 +02:00
## MONGODB Setup
2023-08-19 16:25:45 +02:00
conn = AsyncIOMotorClient(os.environ['MONGO_URI'])
2023-08-12 18:20:18 +02:00
async def _get_collection(collection_name: str):
2023-08-16 15:06:16 +02:00
return conn[os.getenv('MONGO_NAME', 'nova-test')][collection_name]
2023-08-04 03:30:56 +02:00
async def log_api_request(user: dict, incoming_request, target_url: str):
2023-10-08 00:28:13 +02:00
"""Logs the API Request into the database."""
2023-10-12 00:03:15 +02:00
2023-08-12 18:20:18 +02:00
db = await _get_collection('logs')
payload = {}
try:
payload = await incoming_request.json()
except Exception as exc:
if 'JSONDecodeError' in str(exc):
pass
2023-08-04 03:30:56 +02:00
model = payload.get('model')
2023-08-04 17:29:49 +02:00
ip_address = await network.get_ip(incoming_request)
new_log_item = {
2023-08-03 03:50:04 +02:00
'timestamp': time.time(),
2023-08-04 03:30:56 +02:00
'method': incoming_request.method,
'path': incoming_request.url.path,
2023-08-06 21:42:07 +02:00
'user_id': str(user['_id']),
'security': {
2023-08-04 17:29:49 +02:00
'ip': ip_address,
},
'details': {
'model': model,
'target_url': target_url
}
}
2023-08-06 21:42:07 +02:00
inserted = await db.insert_one(new_log_item)
log_item = await db.find_one({'_id': inserted.inserted_id})
return log_item
async def by_id(log_id: str):
2023-08-12 18:20:18 +02:00
db = await _get_collection('logs')
2023-08-06 21:42:07 +02:00
return await db.find_one({'_id': log_id})
async def by_user_id(user_id: str):
2023-08-12 18:20:18 +02:00
db = await _get_collection('logs')
2023-08-06 21:42:07 +02:00
return await db.find({'user_id': user_id})
async def delete_by_id(log_id: str):
2023-08-12 18:20:18 +02:00
db = await _get_collection('logs')
2023-08-06 21:42:07 +02:00
return await db.delete_one({'_id': log_id})
async def delete_by_user_id(user_id: str):
2023-08-12 18:20:18 +02:00
db = await _get_collection('logs')
2023-08-06 21:42:07 +02:00
return await db.delete_many({'user_id': user_id})
2023-10-08 00:28:13 +02:00
async def get_logs_time_range(start: int, end: int):
db = await _get_collection('logs')
entries = []
async for entry in db.find({'timestamp': {'$gte': start, '$lte': end}}):
entries.append(entry)
return entries
async def main():
# how many requests in last 24 hours?
last_24_hours = time.time() - 86400
logs = await get_logs_time_range(last_24_hours, time.time())
print(f'Number of logs in last 24 hours: {len(logs)}')
if __name__ == '__main__':
2023-10-08 00:28:13 +02:00
asyncio.run(main())