├── online_users ├── __init__.py ├── migrations │ ├── __init__.py │ └── 0001_initial.py ├── admin.py ├── middleware.py ├── models.py └── tests │ ├── test_middleware.py │ ├── __init__.py │ └── test_models.py ├── requirements.txt ├── test.db ├── MANIFEST.in ├── LICENSE ├── .gitignore ├── setup.py └── README.rst /online_users/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | Django>=1.11 -------------------------------------------------------------------------------- /online_users/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /test.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lawrencemq/django-online-users/HEAD/test.db -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE 2 | include README.rst 3 | recursive-include online_users *.py 4 | include requirements.txt -------------------------------------------------------------------------------- /online_users/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | from online_users.models import OnlineUserActivity 4 | 5 | 6 | class OnlineUserActivityAdmin(admin.ModelAdmin): 7 | list_display = ('user', 'last_activity',) 8 | search_fields = ['user__username', ] 9 | list_filter = ['last_activity'] 10 | 11 | def get_ordering(self, request): 12 | return ['last_activity'] 13 | 14 | admin.site.register(OnlineUserActivity, OnlineUserActivityAdmin) 15 | -------------------------------------------------------------------------------- /online_users/middleware.py: -------------------------------------------------------------------------------- 1 | from django.utils.deprecation import MiddlewareMixin 2 | 3 | from online_users.models import OnlineUserActivity 4 | 5 | 6 | class OnlineNowMiddleware(MiddlewareMixin): 7 | """Updates the OnlineUserActivity database whenever an authenticated user makes an HTTP request.""" 8 | 9 | @staticmethod 10 | def process_request(request): 11 | user = request.user 12 | if not user.is_authenticated: 13 | return 14 | 15 | OnlineUserActivity.update_user_activity(user) 16 | -------------------------------------------------------------------------------- /online_users/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.10.1 on 2017-01-05 19:59 3 | from __future__ import unicode_literals 4 | 5 | from django.conf import settings 6 | from django.db import migrations, models 7 | import django.db.models.deletion 8 | 9 | 10 | class Migration(migrations.Migration): 11 | 12 | initial = True 13 | 14 | dependencies = [ 15 | migrations.swappable_dependency(settings.AUTH_USER_MODEL), 16 | ] 17 | 18 | operations = [ 19 | migrations.CreateModel( 20 | name='OnlineUserActivity', 21 | fields=[ 22 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 23 | ('last_activity', models.DateTimeField()), 24 | ('user', models.OneToOneField( 25 | on_delete=django.db.models.deletion.CASCADE, 26 | to=settings.AUTH_USER_MODEL) 27 | ), 28 | ], 29 | ), 30 | ] 31 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Lawrence Weikum 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /online_users/models.py: -------------------------------------------------------------------------------- 1 | from datetime import timedelta 2 | 3 | from django.conf import settings 4 | from django.db import models 5 | from django.utils import timezone 6 | 7 | 8 | class OnlineUserActivity(models.Model): 9 | user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) 10 | last_activity = models.DateTimeField() 11 | 12 | @staticmethod 13 | def update_user_activity(user): 14 | """Updates the timestamp a user has for their last action. Uses UTC time.""" 15 | OnlineUserActivity.objects.update_or_create(user=user, defaults={'last_activity': timezone.now()}) 16 | 17 | @staticmethod 18 | def get_user_activities(time_delta=timedelta(minutes=15)): 19 | """ 20 | Gathers OnlineUserActivity objects from the database representing active users. 21 | 22 | :param time_delta: The amount of time in the past to classify a user as "active". Default is 15 minutes. 23 | :return: QuerySet of active users within the time_delta 24 | """ 25 | starting_time = timezone.now() - time_delta 26 | return OnlineUserActivity.objects.filter(last_activity__gte=starting_time).order_by('-last_activity') 27 | -------------------------------------------------------------------------------- /online_users/tests/test_middleware.py: -------------------------------------------------------------------------------- 1 | from datetime import timedelta 2 | 3 | from django.contrib.auth.models import User 4 | from django.test import TestCase 5 | 6 | from online_users.models import OnlineUserActivity 7 | 8 | 9 | class OnlineUserMiddlewareTest(TestCase): 10 | 11 | @staticmethod 12 | def get_active_user_count(): 13 | last_hour = timedelta(minutes=60) 14 | return OnlineUserActivity.get_user_activities(last_hour).count() 15 | 16 | def create_and_login_user(self): 17 | password = 'test1!' 18 | user = User.objects.create_user(username='testUser1', email='test@test.com', password=password) 19 | self.client.login(username=user.username, password=password) 20 | 21 | def url_request(self, url): 22 | response = self.client.get(url, follow=True) 23 | self.assertEqual(response.status_code, 200) 24 | return response 25 | 26 | def test_anonymous_user_not_added(self): 27 | self.url_request('') 28 | self.assertEqual(self.get_active_user_count(), 0) 29 | 30 | def test_user_added_and_updated(self): 31 | self.create_and_login_user() 32 | for i in range(3): 33 | self.url_request('') 34 | self.assertEqual(self.get_active_user_count(), 1) 35 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | instance/ 58 | .webassets-cache 59 | 60 | # Scrapy stuff: 61 | .scrapy 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | 66 | # PyBuilder 67 | target/ 68 | 69 | # IPython Notebook 70 | .ipynb_checkpoints 71 | 72 | # pyenv 73 | .python-version 74 | 75 | # celery beat schedule file 76 | celerybeat-schedule 77 | 78 | # dotenv 79 | .env 80 | 81 | # virtualenv 82 | venv/ 83 | ENV/ 84 | 85 | # Spyder project settings 86 | .spyderproject 87 | 88 | # Rope project settings 89 | .ropeproject 90 | 91 | # IntelliJ 92 | .idea/ 93 | *.iml 94 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import os 2 | from setuptools import find_packages, setup 3 | 4 | with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: 5 | README = readme.read() 6 | 7 | # allow setup.py to be run from any path 8 | os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) 9 | 10 | setup( 11 | name='django-online-users', 12 | version='0.3', 13 | packages=find_packages(), 14 | include_package_data=True, 15 | license='MIT License', 16 | description="Tracks the time of users' last actions.", 17 | long_description=README, 18 | url='https://github.com/lawrencemq/django-online-users', 19 | author='Lawrence Weikum', 20 | author_email='lawrencemq@gmail.com', 21 | test_suite='nose.collector', 22 | tests_require=['nose'], 23 | install_requires=open('requirements.txt').read(), 24 | classifiers=[ 25 | 'Environment :: Web Environment', 26 | 'Framework :: Django', 27 | 'Framework :: Django :: 1.11', 28 | 'Intended Audience :: Developers', 29 | 'License :: OSI Approved :: MIT License', 30 | 'Operating System :: OS Independent', 31 | 'Programming Language :: Python', 32 | 'Programming Language :: Python :: 2', 33 | 'Programming Language :: Python :: 2.7', 34 | 'Programming Language :: Python :: 3', 35 | 'Programming Language :: Python :: 3.4', 36 | 'Programming Language :: Python :: 3.5', 37 | 'Programming Language :: Python :: 3.6', 38 | 'Topic :: Internet :: WWW/HTTP', 39 | 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 40 | ], 41 | ) 42 | -------------------------------------------------------------------------------- /online_users/tests/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | import os 3 | import sys 4 | 5 | from django.conf import settings 6 | from django.conf.urls import url 7 | from django.core.management import call_command 8 | from django.http import HttpResponse 9 | 10 | current_dir = os.path.dirname(os.path.abspath(__file__)) 11 | sys.path.insert(0, os.path.join(current_dir, '..')) 12 | 13 | conf_kwargs = dict( 14 | ALLOWED_HOSTS=('testserver', '127.0.0.1', 'localhost', '::1'), 15 | DATABASES={ 16 | 'default': { 17 | 'ENGINE': 'django.db.backends.sqlite3', 18 | 'NAME': 'test.db', 19 | 'TEST_NAME': 'test.db' 20 | } 21 | }, 22 | SITE_ID=1, 23 | MIDDLEWARE=[ 24 | 'django.middleware.common.CommonMiddleware', 25 | 'django.contrib.sessions.middleware.SessionMiddleware', 26 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 27 | 'online_users.middleware.OnlineNowMiddleware', 28 | ], 29 | INSTALLED_APPS=( 30 | 'django.contrib.auth', 31 | 'django.contrib.contenttypes', 32 | 'django.contrib.sessions', 33 | 'django.contrib.sites', 34 | 'online_users' 35 | ), 36 | ROOT_URLCONF=( 37 | url(r'^', lambda _: HttpResponse('