Merge pull request 'dev/accesslog' (#1) from dev/accesslog into main

Reviewed-on: #1
This commit was merged in pull request #1.
This commit is contained in:
2026-01-04 12:17:25 +05:00
11 changed files with 124 additions and 2 deletions

View File

@@ -1,5 +1,6 @@
import threading import threading
from django.utils.deprecation import MiddlewareMixin from django.utils.deprecation import MiddlewareMixin
from django.contrib.auth.models import AnonymousUser
_thread_local = threading.local() _thread_local = threading.local()
@@ -14,7 +15,9 @@ def get_current_user():
"""Retrieve the user from the current request.""" """Retrieve the user from the current request."""
request = get_current_request() request = get_current_request()
if request: if request:
return getattr(request, "user", None) user = getattr(request, "user", None)
if not isinstance(user, AnonymousUser):
return user
return None return None

View File

View File

@@ -0,0 +1,21 @@
from django.contrib import admin
from .models import AccessLog
@admin.register(AccessLog)
class AccessLogAdmin(admin.ModelAdmin):
list_display = ('timestamp', 'username', 'method', 'path', 'ip_address')
list_filter = ('method', 'timestamp')
search_fields = ('username', 'path', 'ip_address')
readonly_fields = ('timestamp', 'username', 'method', 'path', 'ip_address')
ordering = ('-timestamp',)
def has_add_permission(self, request):
return False
def has_change_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False

View File

@@ -0,0 +1,5 @@
from django.apps import AppConfig
class LoggerConfig(AppConfig):
name = 'logger'

View File

@@ -0,0 +1,29 @@
from .models import AccessLog
class AccessLogMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
user = getattr(request, "user", None)
username = user.username if user and user.is_authenticated else "Anonymous"
method = request.method
path = request.get_full_path()
ip_address = self.get_client_ip(request)
AccessLog.objects.create(
username=username, method=method, path=path, ip_address=ip_address
)
return response
def get_client_ip(self, request):
x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
if x_forwarded_for:
ip = x_forwarded_for.split(",")[0]
else:
ip = request.META.get("REMOTE_ADDR")
return ip

View File

@@ -0,0 +1,37 @@
# Generated by Django 6.0 on 2026-01-03 20:40
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='AccessLog',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('username', models.CharField(max_length=150)),
('method', models.CharField(max_length=10)),
('path', models.CharField(max_length=2048)),
('timestamp', models.DateTimeField(auto_now_add=True)),
('ip_address', models.GenericIPAddressField(blank=True, null=True)),
('created_by', models.ForeignKey(blank=True, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='%(class)s_created', to=settings.AUTH_USER_MODEL)),
('updated_by', models.ForeignKey(blank=True, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='%(class)s_updated', to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name': 'Access Log',
'verbose_name_plural': 'Access Logs',
'ordering': ['-timestamp'],
},
),
]

View File

@@ -0,0 +1,19 @@
from django.db import models
from core.models import BaseModel
class AccessLog(BaseModel):
"""Model to store access logs for user requests."""
class Meta:
verbose_name = "Access Log"
verbose_name_plural = "Access Logs"
ordering = ['-timestamp']
username = models.CharField(max_length=150)
method = models.CharField(max_length=10)
path = models.CharField(max_length=2048)
timestamp = models.DateTimeField(auto_now_add=True)
ip_address = models.GenericIPAddressField(null=True, blank=True)
def __str__(self):
return f'[{self.timestamp}] {self.username} {self.method} {self.path}'

View File

@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

View File

@@ -0,0 +1,3 @@
from django.shortcuts import render
# Create your views here.

View File

@@ -27,7 +27,7 @@ SECRET_KEY = os.getenv("SECRET_KEY", "")
# SECURITY WARNING: don't run with debug turned on in production! # SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.getenv("DJANGO_DEBUG", "False") == "True" DEBUG = os.getenv("DJANGO_DEBUG", "False") == "True"
ALLOWED_HOSTS = os.getenv("ALLOWED_HOSTS", "").split(",") ALLOWED_HOSTS = os.getenv("ALLOWED_HOSTS", "").split(",") if not DEBUG else ["*"]
if not DEBUG: if not DEBUG:
USE_X_FORWARDED_HOST = True USE_X_FORWARDED_HOST = True
@@ -49,6 +49,7 @@ INSTALLED_APPS = [
# Custom apps # Custom apps
'core', 'core',
'music', 'music',
'logger',
] ]
MIDDLEWARE = [ MIDDLEWARE = [
@@ -65,6 +66,7 @@ MIDDLEWARE = [
'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',
# Custom middlewares # Custom middlewares
"core.middleware.current_request.CurrentRequestMiddleware", "core.middleware.current_request.CurrentRequestMiddleware",
"logger.middleware.AccessLogMiddleware",
] ]
ROOT_URLCONF = 'music_storage.urls' ROOT_URLCONF = 'music_storage.urls'