├── app ├── __init__.py ├── api │ ├── __init__.py │ └── urls.py ├── migrations │ └── __init__.py ├── models.py ├── apps.py └── urls.py ├── core ├── api │ ├── __init__.py │ └── pagination.py ├── __init__.py ├── middleware.py ├── asgi.py ├── wsgi.py ├── celery.py ├── urls.py └── settings.py ├── authentication ├── __init__.py ├── api │ ├── __init__.py │ ├── views │ │ ├── __init__.py │ │ └── auth_views.py │ └── urls.py ├── migrations │ ├── __init__.py │ └── 0001_initial.py ├── apps.py ├── admin.py ├── utils.py └── models.py ├── Services ├── docs ├── media │ └── scheme.png ├── run_locally_using_docker_compose.md ├── deploy_to_server_using_docker_compose.md ├── deploy_in_production_using_k8s.md └── set_env_vars.md ├── entrypoint.sh ├── entrypoint.prod.sh ├── k8s └── examples │ ├── app │ ├── configmap.yaml │ ├── .env │ ├── service.yaml │ ├── ingress.yaml │ └── deployment.yaml │ ├── postgres │ ├── pg-service.yaml │ ├── pg-storage.yaml │ └── pg-deployment.yaml │ ├── ingress-nginx │ ├── ingress-nginx-configmap.yaml │ └── ingress-nginx-service.yaml │ ├── rabbitmq │ ├── rabbitmq-service.yaml │ └── rabbitmq-deployment.yaml │ └── letsencrypt │ └── letsencrypt.yaml ├── .gitignore ├── docker-compose.override.yml ├── .dockerignore ├── gunicorn.conf.py ├── Dockerfile ├── manage.py ├── nginx ├── nginx.conf ├── dj-ms-core.conf └── app-locations.conf ├── requirements.txt ├── docker-compose.prod.yml ├── .github └── workflows │ └── build-and-push-to-docker-hub.yml ├── docker-compose.yml ├── README.md ├── deploy.sh └── LICENSE /app/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /app/api/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /core/api/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /app/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /authentication/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /authentication/api/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /authentication/api/views/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /authentication/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Services: -------------------------------------------------------------------------------- 1 | django 2 | celery 3 | celery-beat -------------------------------------------------------------------------------- /app/api/urls.py: -------------------------------------------------------------------------------- 1 | 2 | urlpatterns = [ 3 | 4 | ] 5 | -------------------------------------------------------------------------------- /app/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /core/__init__.py: -------------------------------------------------------------------------------- 1 | from .celery import app as celery_app 2 | 3 | __all__ = ['celery_app'] 4 | -------------------------------------------------------------------------------- /docs/media/scheme.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dj-ms/dj-ms-core/HEAD/docs/media/scheme.png -------------------------------------------------------------------------------- /entrypoint.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | python manage.py migrate --noinput || exit 1 4 | exec "$@" 5 | -------------------------------------------------------------------------------- /entrypoint.prod.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | python manage.py migrate --noinput || exit 1 4 | python manage.py collectstatic --noinput || exit 1 5 | exec "$@" 6 | -------------------------------------------------------------------------------- /app/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig as BaseAppConfig 2 | 3 | 4 | class AppConfig(BaseAppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'app' 7 | -------------------------------------------------------------------------------- /k8s/examples/app/configmap.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: ConfigMap 3 | metadata: 4 | name: dj-ms-core-config 5 | data: 6 | DJANGO_TIME_ZONE: 'Asia/Tashkent' 7 | DJANGO_LANGUAGE_CODE: 'en' 8 | -------------------------------------------------------------------------------- /authentication/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class AuthenticationConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'authentication' 7 | -------------------------------------------------------------------------------- /core/api/pagination.py: -------------------------------------------------------------------------------- 1 | from rest_framework.pagination import PageNumberPagination as BasePageNumberPagination 2 | 3 | 4 | class PageNumberPagination(BasePageNumberPagination): 5 | page_size_query_param = 'page_size' 6 | 7 | 8 | -------------------------------------------------------------------------------- /k8s/examples/postgres/pg-service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: postgres 5 | labels: 6 | app: postgres 7 | spec: 8 | type: ClusterIP 9 | ports: 10 | - port: 5432 11 | selector: 12 | name: postgres 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | **/venv 2 | **/.idea 3 | **/.env 4 | **/__pycache__ 5 | **/node_modules 6 | **/*.egg-info 7 | db.sqlite3 8 | static 9 | /media/ 10 | nginx/default.d/*.conf 11 | !nginx/default.d/app-locations.conf 12 | .bash_history 13 | !k8s/examples 14 | k8s 15 | -------------------------------------------------------------------------------- /k8s/examples/ingress-nginx/ingress-nginx-configmap.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: ConfigMap 3 | metadata: 4 | annotations: 5 | labels: 6 | app: ingress-nginx 7 | name: nginx-configuration 8 | namespace: ingress-nginx 9 | data: 10 | use-forwarded-headers: "true" 11 | -------------------------------------------------------------------------------- /docker-compose.override.yml: -------------------------------------------------------------------------------- 1 | services: 2 | django: 3 | ports: 4 | - "${DJANGO_WEB_PORT:-8000}:8000" 5 | volumes: 6 | - .:/home/django/ 7 | celery: 8 | volumes: 9 | - .:/home/django/ 10 | celery-beat: 11 | volumes: 12 | - .:/home/django/ 13 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | .idea 2 | .git 3 | venv 4 | /docs/ 5 | /static/ 6 | /media/ 7 | .dockerignore 8 | .gitignore 9 | db.sqlite3 10 | docker-compose.* 11 | Dockerfile 12 | runtime.txt 13 | .github 14 | README.md 15 | LICENSE 16 | nginx/default.d 17 | Services 18 | build.sh 19 | deploy.sh 20 | .bash_history 21 | k8s 22 | -------------------------------------------------------------------------------- /k8s/examples/app/.env: -------------------------------------------------------------------------------- 1 | DJANGO_SECRET_KEY=very-secret-string 2 | DJANGO_DEBUG=False 3 | DATABASE_URL=postgres://dj_ms_core:dj_ms_core@postgres.postgres:5432/dj_ms_core 4 | DJANGO_ALLOWED_HOSTS=example.com 5 | DJANGO_CSRF_TRUSTED_ORIGINS=https://example.com 6 | BROKER_URL=amqp://dj_ms_core:dj_ms_core@rabbitmq.rabbitmq:5672 7 | -------------------------------------------------------------------------------- /authentication/api/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | 3 | from authentication.api.views.auth_views import login_view, logout_view, register_view 4 | 5 | urlpatterns = [ 6 | path('login', login_view, name='login'), 7 | path('logout', logout_view, name='logout'), 8 | path('register', register_view, name='register') 9 | ] 10 | -------------------------------------------------------------------------------- /k8s/examples/rabbitmq/rabbitmq-service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: rabbitmq 5 | spec: 6 | ports: 7 | - name: ampq1 8 | port: 5671 9 | protocol: TCP 10 | targetPort: 5671 11 | - name: ampq2 12 | port: 5672 13 | protocol: TCP 14 | targetPort: 5672 15 | selector: 16 | app: rabbitmq 17 | -------------------------------------------------------------------------------- /core/middleware.py: -------------------------------------------------------------------------------- 1 | from django.http import HttpResponse 2 | 3 | 4 | class HealthCheckMiddleware: 5 | def __init__(self, get_response): 6 | self.get_response = get_response 7 | 8 | def __call__(self, request): 9 | if request.path == '/health': 10 | return HttpResponse('ok') 11 | return self.get_response(request) 12 | -------------------------------------------------------------------------------- /gunicorn.conf.py: -------------------------------------------------------------------------------- 1 | # Gunicorn configuration file 2 | # https://docs.gunicorn.org/en/stable/configure.html#configuration-file 3 | # https://docs.gunicorn.org/en/stable/settings.html 4 | import multiprocessing 5 | 6 | log_file = '-' 7 | 8 | workers = multiprocessing.cpu_count() + 1 9 | 10 | bind = '0.0.0.0:8000' 11 | 12 | timeout = 600 13 | 14 | preload = True 15 | -------------------------------------------------------------------------------- /app/urls.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import redirect 2 | from django.urls import path 3 | 4 | from core.urls import URL_PREFIX 5 | 6 | urlpatterns = [ 7 | 8 | ] 9 | 10 | # This redirects to the API root if there is no other root URL 11 | if not any(url == '' for url in urlpatterns): 12 | urlpatterns += [ 13 | path('', lambda req: redirect('/api/' + URL_PREFIX)), 14 | ] 15 | -------------------------------------------------------------------------------- /k8s/examples/app/service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: dj-ms-core 5 | labels: 6 | app.kubernetes.io/name: dj-ms-core 7 | app.kubernetes.io/component: web 8 | spec: 9 | type: ClusterIP 10 | ports: 11 | - port: 8000 12 | targetPort: http 13 | protocol: TCP 14 | name: http 15 | selector: 16 | app.kubernetes.io/name: dj-ms-core 17 | app.kubernetes.io/component: web 18 | -------------------------------------------------------------------------------- /core/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for dj_ms_core project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.1/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /core/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for dj_ms_core project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.1/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /k8s/examples/postgres/pg-storage.yaml: -------------------------------------------------------------------------------- 1 | kind: PersistentVolume 2 | apiVersion: v1 3 | metadata: 4 | name: postgres-pv 5 | labels: 6 | type: local 7 | spec: 8 | storageClassName: manual 9 | capacity: 10 | storage: 512M 11 | accessModes: 12 | - ReadWriteOnce 13 | hostPath: 14 | path: "/data" 15 | --- 16 | apiVersion: v1 17 | kind: PersistentVolumeClaim 18 | metadata: 19 | name: postgres-pv-claim 20 | labels: 21 | app: postgres 22 | spec: 23 | storageClassName: manual 24 | accessModes: 25 | - ReadWriteOnce 26 | resources: 27 | requests: 28 | storage: 512M 29 | -------------------------------------------------------------------------------- /core/celery.py: -------------------------------------------------------------------------------- 1 | import os 2 | from celery import Celery 3 | 4 | # set the default Django settings module for the 'celery' program. 5 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') 6 | 7 | app = Celery('core') 8 | 9 | # Using a string here means the worker doesn't have to serialize 10 | # the configuration object to child processes. 11 | # - namespace='CELERY' means all celery-related configuration keys 12 | # should have a `CELERY_` prefix. 13 | app.config_from_object('django.conf:settings', namespace='CELERY') 14 | 15 | # Load task modules from all registered Django app configs. 16 | app.autodiscover_tasks() 17 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.10-alpine as python-deps 2 | 3 | COPY requirements.txt / 4 | 5 | RUN apk add --no-cache py3-virtualenv py3-pip git && \ 6 | python3 -m venv /.venv && \ 7 | source /.venv/bin/activate && \ 8 | pip install -r /requirements.txt --no-cache-dir 9 | 10 | 11 | FROM python:3.10-alpine as runtime 12 | 13 | RUN apk add --no-cache curl 14 | 15 | ENV PATH="/.venv/bin:$PATH" 16 | 17 | ENV PYTHONUNBUFFERED 1 18 | 19 | WORKDIR /home/django 20 | 21 | COPY --from=python-deps /.venv /.venv 22 | 23 | ARG CACHE_DATE=not_a_date 24 | RUN echo $CACHE_DATE 25 | 26 | ADD . . 27 | 28 | ENTRYPOINT ["/home/django/entrypoint.sh"] 29 | 30 | CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] 31 | 32 | EXPOSE 8000 33 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /nginx/nginx.conf: -------------------------------------------------------------------------------- 1 | upstream django { 2 | server django:8000; 3 | } 4 | 5 | server { 6 | listen 8000; 7 | server_name localhost; 8 | 9 | location / { 10 | proxy_pass "http://django"; 11 | proxy_http_version 1.1; 12 | proxy_set_header Upgrade $http_upgrade; 13 | proxy_set_header Connection "upgrade"; 14 | proxy_set_header Host $host; 15 | proxy_set_header X-Real-IP $remote_addr; 16 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 17 | } 18 | 19 | location /static/ { 20 | alias /usr/share/nginx/static/; 21 | access_log off; 22 | } 23 | 24 | location /media/ { 25 | alias /usr/share/nginx/media/; 26 | access_log off; 27 | } 28 | } -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # Python 2 | python-dotenv 3 | setuptools>=65.5.1 4 | certifi>=2022.12.07 5 | 6 | # Django 7 | Django~=4.1 8 | djangorestframework 9 | django-filter 10 | django-cors-headers 11 | django-cleanup 12 | # django-auditlog 13 | # temporary fix for django-auditlog. will change to original source when Jazzband merges my PR 14 | git+https://github.com/HarleyK1ng/django-auditlog.git@master#egg=django-auditlog 15 | 16 | # Miscroservices 17 | dj-ms-auth-router==1.4.0 18 | 19 | # Databases 20 | psycopg2-binary 21 | dj-database-url 22 | 23 | # Deployment 24 | gunicorn 25 | whitenoise 26 | 27 | # Async Celery tasks 28 | celery 29 | django-celery-beat 30 | django-celery-results 31 | 32 | # Message broker 33 | pika 34 | 35 | # Sentry 36 | sentry-sdk 37 | -------------------------------------------------------------------------------- /k8s/examples/app/ingress.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: networking.k8s.io/v1 2 | kind: Ingress 3 | metadata: 4 | name: dj-ms-core 5 | labels: 6 | app.kubernetes.io/name: dj-ms-core 7 | app.kubernetes.io/component: web 8 | annotations: 9 | kubernetes.io/ingress.class: nginx 10 | spec: 11 | rules: 12 | - host: core.k8s.dj-ms.dev 13 | http: 14 | paths: 15 | - path: / 16 | backend: 17 | service: 18 | name: dj-ms-core 19 | port: 20 | number: 8000 21 | - path: /api/ 22 | backend: 23 | service: 24 | name: dj-ms-core 25 | port: 26 | number: 8000 27 | pathType: ImplementationSpecific 28 | -------------------------------------------------------------------------------- /k8s/examples/letsencrypt/letsencrypt.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: cert-manager.io/v1 2 | kind: ClusterIssuer 3 | metadata: 4 | name: letsencrypt-staging 5 | spec: 6 | acme: 7 | server: https://acme-staging-v02.api.letsencrypt.org/directory 8 | email: admin@cluster.local 9 | privateKeySecretRef: 10 | name: letsencrypt-staging 11 | solvers: 12 | - http01: 13 | ingress: 14 | class: nginx 15 | --- 16 | apiVersion: cert-manager.io/v1 17 | kind: ClusterIssuer 18 | metadata: 19 | name: letsencrypt-production 20 | spec: 21 | acme: 22 | server: https://acme-v02.api.letsencrypt.org/directory 23 | email: admin@cluster.local 24 | privateKeySecretRef: 25 | name: letsencrypt-production 26 | solvers: 27 | - http01: 28 | ingress: 29 | class: nginx 30 | -------------------------------------------------------------------------------- /docker-compose.prod.yml: -------------------------------------------------------------------------------- 1 | services: 2 | django: 3 | command: /home/django/entrypoint.prod.sh gunicorn core.wsgi 4 | environment: 5 | - DJANGO_DEBUG=False 6 | - DJANGO_SECRET_KEY=${DJANGO_SECRET_KEY:?DJANGO_SECRET_KEY} 7 | volumes: 8 | - static:/home/django/static/ 9 | - media:/home/django/media/ 10 | celery: 11 | volumes: 12 | - static:/home/django/static/ 13 | - media:/home/django/media/ 14 | celery-beat: 15 | volumes: 16 | - static:/home/django/static/ 17 | - media:/home/django/media/ 18 | nginx: 19 | image: nginx:alpine-slim 20 | volumes: 21 | - ./nginx/nginx.conf:/etc/nginx/conf.d/nginx.conf 22 | - static:/usr/share/nginx/static/ 23 | - media:/usr/share/nginx/media/ 24 | ports: 25 | - "${DJANGO_WEB_PORT:-8000}:8000" 26 | depends_on: 27 | django: 28 | condition: service_healthy 29 | 30 | 31 | volumes: 32 | static: 33 | media: 34 | -------------------------------------------------------------------------------- /k8s/examples/postgres/pg-deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | name: postgres 5 | spec: 6 | replicas: 1 7 | selector: 8 | matchLabels: 9 | name: postgres 10 | template: 11 | metadata: 12 | labels: 13 | name: postgres 14 | spec: 15 | containers: 16 | - name: postgres 17 | image: postgres:12.2 18 | ports: 19 | - containerPort: 5432 20 | env: 21 | - name: POSTGRES_USER 22 | value: "postgres" 23 | - name: POSTGRES_PASSWORD 24 | value: "postgres" 25 | - name: POSTGRES_DB 26 | value: "postgres" 27 | volumeMounts: 28 | - mountPath: /var/lib/postgresql/data 29 | name: postgres-volume-mount 30 | volumes: 31 | - name: postgres-volume-mount 32 | persistentVolumeClaim: 33 | claimName: postgres-pv-claim 34 | -------------------------------------------------------------------------------- /authentication/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | from authentication.models import User 4 | 5 | 6 | @admin.register(User) 7 | class UserAdmin(admin.ModelAdmin): 8 | list_display = ('id', 'username', 'email', 'first_name', 'last_name', 'is_active', 'is_staff', 'is_superuser') 9 | list_filter = ('is_active', 'is_staff', 'is_superuser') 10 | search_fields = ('username', 'email', 'first_name', 'last_name') 11 | ordering = ('id',) 12 | readonly_fields = ('id', 'date_joined', 'last_login') 13 | 14 | fieldsets = ( 15 | (None, { 16 | 'fields': ('id', 'username', 'email', 'first_name', 'last_name', 'is_active', 'is_staff', 'is_superuser') 17 | }), 18 | ('Permissions', { 19 | 'fields': ('groups', 'user_permissions') 20 | }), 21 | ('Important dates', { 22 | 'fields': ('last_login', 'date_joined') 23 | }), 24 | ) 25 | add_fieldsets = ( 26 | (None, { 27 | 'classes': ('wide',), 28 | 'fields': ('username', 'email', 'password1', 'password2', 'first_name', 'last_name', 'is_active', 'is_staff', 'is_superuser') 29 | }), 30 | ) 31 | 32 | def has_add_permission(self, request): 33 | return False 34 | 35 | def has_delete_permission(self, request, obj=None): 36 | return False 37 | 38 | -------------------------------------------------------------------------------- /k8s/examples/ingress-nginx/ingress-nginx-service.yaml: -------------------------------------------------------------------------------- 1 | # Source: ingress-nginx/templates/controller-service-webhook.yaml 2 | apiVersion: v1 3 | kind: Service 4 | metadata: 5 | labels: 6 | app.kubernetes.io/name: ingress-nginx 7 | app.kubernetes.io/instance: ingress-nginx 8 | app.kubernetes.io/component: controller 9 | name: ingress-nginx-controller-admission 10 | namespace: ingress-nginx 11 | spec: 12 | type: ClusterIP 13 | ports: 14 | - name: https-webhook 15 | port: 443 16 | targetPort: webhook 17 | selector: 18 | app.kubernetes.io/name: ingress-nginx 19 | app.kubernetes.io/part-of: ingress-nginx 20 | --- 21 | # Source: ingress-nginx/templates/controller-service.yaml 22 | apiVersion: v1 23 | kind: Service 24 | metadata: 25 | labels: 26 | app.kubernetes.io/name: ingress-nginx 27 | app.kubernetes.io/instance: ingress-nginx 28 | app.kubernetes.io/component: controller 29 | name: ingress-nginx-controller 30 | namespace: ingress-nginx 31 | spec: 32 | type: LoadBalancer 33 | externalTrafficPolicy: Cluster 34 | ports: 35 | - name: http 36 | port: 80 37 | protocol: TCP 38 | targetPort: http 39 | - name: https 40 | port: 443 41 | protocol: TCP 42 | targetPort: https 43 | selector: 44 | app.kubernetes.io/name: ingress-nginx 45 | app.kubernetes.io/part-of: ingress-nginx 46 | -------------------------------------------------------------------------------- /k8s/examples/rabbitmq/rabbitmq-deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | labels: 5 | app: rabbitmq 6 | name: rabbitmq 7 | spec: 8 | minReadySeconds: 5 9 | progressDeadlineSeconds: 600 10 | replicas: 1 11 | revisionHistoryLimit: 10 12 | selector: 13 | matchLabels: 14 | app: rabbitmq 15 | strategy: 16 | rollingUpdate: 17 | maxSurge: 1 18 | maxUnavailable: 1 19 | type: RollingUpdate 20 | template: 21 | metadata: 22 | labels: 23 | app: rabbitmq 24 | spec: 25 | containers: 26 | - env: 27 | - name: RABBITMQ_DEFAULT_USER 28 | value: rabbitmq 29 | - name: RABBITMQ_DEFAULT_PASS 30 | value: rabbitmq 31 | image: rabbitmq 32 | imagePullPolicy: Always 33 | name: rabbitmq 34 | ports: 35 | - containerPort: 5671 36 | protocol: TCP 37 | - containerPort: 5672 38 | protocol: TCP 39 | - containerPort: 4369 40 | protocol: TCP 41 | - containerPort: 15672 42 | protocol: TCP 43 | resources: 44 | requests: 45 | cpu: 100m 46 | terminationMessagePath: /dev/termination-log 47 | terminationMessagePolicy: File 48 | dnsPolicy: ClusterFirst 49 | restartPolicy: Always 50 | schedulerName: default-scheduler 51 | securityContext: {} 52 | terminationGracePeriodSeconds: 3 53 | -------------------------------------------------------------------------------- /core/urls.py: -------------------------------------------------------------------------------- 1 | """dj_ms_core URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/4.1/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.shortcuts import redirect 18 | from django.urls import path, include 19 | 20 | from core.settings import APP_LABEL 21 | 22 | URL_PREFIX = APP_LABEL + '/' if APP_LABEL else '' 23 | 24 | 25 | urlpatterns = [ 26 | path(URL_PREFIX + 'admin/', admin.site.urls), 27 | path('api/auth/', include('authentication.api.urls'), name='authentication'), 28 | ] 29 | 30 | 31 | def get_redirect_url(): 32 | if URL_PREFIX: 33 | return redirect(f'{URL_PREFIX}') 34 | return redirect(URL_PREFIX + 'admin/') 35 | 36 | 37 | urlpatterns += [ 38 | path('', lambda req: get_redirect_url()), 39 | ] 40 | 41 | urlpatterns += [ 42 | path('api/' + URL_PREFIX, include('app.api.urls'), name='api'), 43 | path(URL_PREFIX, include('app.urls')), 44 | ] 45 | -------------------------------------------------------------------------------- /nginx/dj-ms-core.conf: -------------------------------------------------------------------------------- 1 | location /api/dj-ms-core/ { 2 | proxy_pass "http://127.0.0.1:/api/dj-ms-core/"; 3 | proxy_http_version 1.1; 4 | proxy_set_header Upgrade $http_upgrade; 5 | proxy_set_header Connection "upgrade"; 6 | proxy_set_header Host $host; 7 | proxy_set_header X-Real-IP $remote_addr; 8 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 9 | } 10 | 11 | location /static/dj-ms-core/ { 12 | proxy_pass "http://127.0.0.1:/static/dj-ms-core/"; 13 | proxy_http_version 1.1; 14 | proxy_set_header Upgrade $http_upgrade; 15 | proxy_set_header Connection "upgrade"; 16 | proxy_set_header Host $host; 17 | proxy_set_header X-Real-IP $remote_addr; 18 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 19 | } 20 | 21 | location /media/dj-ms-core/ { 22 | proxy_pass "http://127.0.0.1:/media/dj-ms-core/"; 23 | proxy_http_version 1.1; 24 | proxy_set_header Upgrade $http_upgrade; 25 | proxy_set_header Connection "upgrade"; 26 | proxy_set_header Host $host; 27 | proxy_set_header X-Real-IP $remote_addr; 28 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 29 | } 30 | 31 | location /dj-ms-core/ { 32 | proxy_pass "http://127.0.0.1:/dj-ms-core/"; 33 | proxy_http_version 1.1; 34 | proxy_set_header Upgrade $http_upgrade; 35 | proxy_set_header Connection "upgrade"; 36 | proxy_set_header Host $host; 37 | proxy_set_header X-Real-IP $remote_addr; 38 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 39 | } 40 | -------------------------------------------------------------------------------- /.github/workflows/build-and-push-to-docker-hub.yml: -------------------------------------------------------------------------------- 1 | # This workflow uses actions that are not certified by GitHub. 2 | # They are provided by a third-party and are governed by 3 | # separate terms of service, privacy policy, and support 4 | # documentation. 5 | 6 | # GitHub recommends pinning actions to a commit SHA. 7 | # To get a newer version, you will need to update the SHA. 8 | # You can also reference a tag or branch, but the action may change without warning. 9 | 10 | name: Publish Docker image 11 | 12 | on: 13 | release: 14 | types: [published] 15 | 16 | jobs: 17 | push_to_registry: 18 | name: Push Docker image to Docker Hub 19 | runs-on: ubuntu-latest 20 | steps: 21 | - name: Check out the repo 22 | uses: actions/checkout@v3 23 | 24 | - name: Log in to Docker Hub 25 | uses: docker/login-action@f054a8b539a109f9f41c372932f1ae047eff08c9 26 | with: 27 | username: ${{ secrets.DOCKER_USERNAME }} 28 | password: ${{ secrets.DOCKER_PASSWORD }} 29 | 30 | - name: Extract metadata (tags, labels) for Docker 31 | id: meta 32 | uses: docker/metadata-action@98669ae865ea3cffbcbaa878cf57c20bbf1c6c38 33 | with: 34 | images: harleyking/dj-ms-core 35 | 36 | - name: Build and push Docker image 37 | uses: docker/build-push-action@ad44023a93711e3deb337508980b4b5e9bcdc5dc 38 | with: 39 | context: . 40 | push: true 41 | tags: ${{ steps.meta.outputs.tags }} 42 | labels: ${{ steps.meta.outputs.labels }} 43 | -------------------------------------------------------------------------------- /docs/run_locally_using_docker_compose.md: -------------------------------------------------------------------------------- 1 | # Run locally using docker compose 2 | 3 | 4 | --- 5 | ## Prerequisites 6 | 7 | Create the `.env` file and set the environment variables according to the instructions. 8 | [Set environment variables](set_env_vars.md). 9 | ```shell 10 | nano .env 11 | ``` 12 | 13 | 14 | --- 15 | ## Run project 16 | > Note: when running locally, you don't need to build project while unless you change `requirements.txt`. 17 | > It's because local code is mounted into container so your changes are reflected immediately. 18 | 19 | Build 20 | ```shell 21 | docker compose build 22 | ``` 23 | 24 | 25 | --- 26 | ### Run 27 | 28 | Core service: 29 | ```shell 30 | docker compose -f docker-compose.yml -f docker-compose.core.yml -f docker-compose.override.yml up -d 31 | ``` 32 | 33 |
34 | 35 | Any microservice: 36 | ```shell 37 | docker compose up -d 38 | ``` 39 | 40 |
41 | 42 | Enter container 43 | ```shell 44 | docker compose exec django sh 45 | ``` 46 | 47 |
48 | 49 | Create superuser 50 | ```shell 51 | python manage.py createsuperuser 52 | ``` 53 | 54 |
55 | 56 | View logs 57 | ```shell 58 | docker compose logs -f 59 | ``` 60 | 61 | > Note: you can use `docker compose logs -f django` to view only django logs. 62 | 63 | Stop project 64 | ```shell 65 | docker compose down 66 | ``` 67 | 68 | 69 | --- 70 | ## Access project 71 | Now you can access admin panel at `http://localhost:8000/admin/`. 72 | 73 | If you have set `DJANGO_URL_PREFIX` in `.env` file, 74 | then you should access admin panel at `http://localhost:8000//admin/`. 75 | -------------------------------------------------------------------------------- /nginx/app-locations.conf: -------------------------------------------------------------------------------- 1 | location /api/DJ_MS_APP_LABEL/ { 2 | proxy_pass "http://127.0.0.1:DJANGO_WEB_PORT/api/DJ_MS_APP_LABEL/"; 3 | proxy_http_version 1.1; 4 | proxy_set_header Upgrade $http_upgrade; 5 | proxy_set_header Connection "upgrade"; 6 | proxy_set_header Host $host; 7 | proxy_set_header X-Real-IP $remote_addr; 8 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 9 | } 10 | 11 | location /static/DJ_MS_APP_LABEL/ { 12 | proxy_pass "http://127.0.0.1:DJANGO_WEB_PORT/static/DJ_MS_APP_LABEL/"; 13 | proxy_http_version 1.1; 14 | proxy_set_header Upgrade $http_upgrade; 15 | proxy_set_header Connection "upgrade"; 16 | proxy_set_header Host $host; 17 | proxy_set_header X-Real-IP $remote_addr; 18 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 19 | } 20 | 21 | location /media/DJ_MS_APP_LABEL/ { 22 | proxy_pass "http://127.0.0.1:DJANGO_WEB_PORT/media/DJ_MS_APP_LABEL/"; 23 | proxy_http_version 1.1; 24 | proxy_set_header Upgrade $http_upgrade; 25 | proxy_set_header Connection "upgrade"; 26 | proxy_set_header Host $host; 27 | proxy_set_header X-Real-IP $remote_addr; 28 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 29 | } 30 | 31 | location /DJ_MS_APP_LABEL/ { 32 | proxy_pass "http://127.0.0.1:DJANGO_WEB_PORT/DJ_MS_APP_LABEL/"; 33 | proxy_http_version 1.1; 34 | proxy_set_header Upgrade $http_upgrade; 35 | proxy_set_header Connection "upgrade"; 36 | proxy_set_header Host $host; 37 | proxy_set_header X-Real-IP $remote_addr; 38 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 39 | } 40 | -------------------------------------------------------------------------------- /authentication/utils.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import uuid 3 | 4 | from django.conf import settings 5 | from django.utils import timezone 6 | from rest_framework.authentication import TokenAuthentication 7 | from rest_framework.exceptions import AuthenticationFailed 8 | 9 | from authentication.models import Token 10 | 11 | 12 | TOKEN_TTL = settings.REST_AUTH_TOKEN_TTL 13 | 14 | 15 | def generate_token(user): 16 | user_id = user.pk 17 | Token.objects.filter(user_id=user_id, active=True).update(active=False) 18 | key = uuid.uuid4() 19 | token = Token.objects.create(key=key, user_id=user_id, active=True) 20 | return token.key 21 | 22 | 23 | class ExpiringTokenAuthentication(TokenAuthentication): 24 | model = Token 25 | keyword = 'Bearer' 26 | 27 | def authenticate_credentials(self, key, request=None): 28 | try: 29 | token = self.model.objects.get(key=key) 30 | except self.model.DoesNotExist: 31 | raise AuthenticationFailed({"error": "Invalid or Inactive Token", "is_authenticated": False}) 32 | else: 33 | if not token.user.is_active: 34 | raise AuthenticationFailed({"error": "Invalid user", "is_authenticated": False}) 35 | if not token.active: 36 | raise AuthenticationFailed({"error": "Inactive Token", "is_authenticated": False}) 37 | now = timezone.now() 38 | diff = now - datetime.timedelta(seconds=TOKEN_TTL) 39 | if token.last_use < diff: 40 | token.active = False 41 | token.save() 42 | raise AuthenticationFailed({"error": "Token has expired", "token_status": False}) 43 | token.last_use = now 44 | token.save() 45 | return token.user, token 46 | -------------------------------------------------------------------------------- /k8s/examples/app/deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | name: dj-ms-core 5 | labels: 6 | app.kubernetes.io/name: dj-ms-core 7 | app.kubernetes.io/component: web 8 | spec: 9 | replicas: 1 10 | selector: 11 | matchLabels: 12 | app.kubernetes.io/name: dj-ms-core 13 | app.kubernetes.io/component: web 14 | template: 15 | metadata: 16 | labels: 17 | app.kubernetes.io/name: dj-ms-core 18 | app.kubernetes.io/component: web 19 | spec: 20 | containers: 21 | - name: web 22 | image: harleyking/dj-ms-core:latest 23 | command: ["/home/django/entrypoint.prod.sh", "gunicorn", "core.wsgi"] 24 | imagePullPolicy: Always 25 | ports: 26 | - containerPort: 8000 27 | name: http 28 | envFrom: 29 | - configMapRef: 30 | name: dj-ms-core-config 31 | - secretRef: 32 | name: dj-ms-core-secret 33 | - name: celery 34 | image: harleyking/dj-ms-core:latest 35 | command: ["celery", "-A", "core", "worker", "-l", "info", "--concurrency", "1", "-P", "solo", "-E"] 36 | imagePullPolicy: Always 37 | envFrom: 38 | - configMapRef: 39 | name: dj-ms-core-config 40 | - secretRef: 41 | name: dj-ms-core-secret 42 | - name: celery-beat 43 | image: harleyking/dj-ms-core:latest 44 | command: ["celery", "-A", "core", "beat", "-l", "info", 45 | "--scheduler", "django_celery_beat.schedulers.DatabaseScheduler"] 46 | imagePullPolicy: Always 47 | envFrom: 48 | - configMapRef: 49 | name: dj-ms-core-config 50 | - secretRef: 51 | name: dj-ms-core-secret 52 | -------------------------------------------------------------------------------- /authentication/models.py: -------------------------------------------------------------------------------- 1 | from auditlog.registry import auditlog 2 | from django.contrib.auth.base_user import BaseUserManager, AbstractBaseUser 3 | from django.contrib.auth.models import PermissionsMixin 4 | from django.db import models 5 | from rest_framework.authtoken.models import Token as AuthToken 6 | from django.utils.translation import gettext_lazy as _ 7 | 8 | 9 | class MyUserManager(BaseUserManager): 10 | def create_user(self, username, first_name=None, last_name=None, password=None): 11 | user = self.model( 12 | username=username, 13 | first_name=first_name, 14 | last_name=last_name) 15 | user.set_password(password) 16 | user.save(using=self._db) 17 | return user 18 | 19 | def create_superuser(self, username, password, first_name=None, last_name=None): 20 | user = self.create_user(password=password, 21 | username=username, 22 | first_name=first_name, 23 | last_name=last_name) 24 | user.is_superuser = True 25 | user.is_staff = True 26 | user.save(using=self._db) 27 | return user 28 | 29 | 30 | class User(AbstractBaseUser, PermissionsMixin): 31 | username = models.CharField(max_length=24, null=False, blank=False, unique=True) 32 | email = models.EmailField(unique=True, default=None, null=True) 33 | first_name = models.CharField(max_length=32, null=True, default=None) 34 | last_name = models.CharField(max_length=32, null=True, default=None) 35 | date_of_birth = models.DateField(null=True, default=None) 36 | date_joined = models.DateField(null=True, default=None) 37 | is_active = models.BooleanField(default=True) 38 | is_staff = models.BooleanField(default=False) 39 | 40 | objects = MyUserManager() 41 | 42 | USERNAME_FIELD = 'username' 43 | REQUIRED_FIELDS = [] 44 | 45 | def has_module_perms(self, app_label): 46 | """Does the user have permissions to view the app `app_label`?""" 47 | # Simplest possible answer: Yes, always 48 | return True 49 | 50 | class Meta: 51 | verbose_name = _('user') 52 | verbose_name_plural = _('users') 53 | db_table = 'auth_user' 54 | 55 | 56 | class Token(AuthToken): 57 | key = models.CharField(_('Key'), max_length=40, primary_key=True) 58 | user_id = models.PositiveBigIntegerField(_('User'), db_index=True) 59 | created = models.DateTimeField(_('Created'), auto_now_add=True) 60 | last_use = models.DateTimeField(_('Last use'), auto_now=True) 61 | active = models.BooleanField(default=False) 62 | 63 | class Meta: 64 | verbose_name = _('Token') 65 | verbose_name_plural = _('Tokens') 66 | 67 | def __str__(self): 68 | return self.key 69 | 70 | @property 71 | def user(self): 72 | try: 73 | return User.objects.get(id=self.user_id) 74 | except User.DoesNotExist: 75 | self.delete() 76 | return None 77 | 78 | 79 | auditlog.register(User) 80 | -------------------------------------------------------------------------------- /authentication/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 4.1.6 on 2023-02-03 20:32 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | initial = True 9 | 10 | dependencies = [ 11 | ('auth', '0012_alter_user_first_name_max_length'), 12 | ] 13 | 14 | operations = [ 15 | migrations.CreateModel( 16 | name='Token', 17 | fields=[ 18 | ('key', models.CharField(max_length=40, primary_key=True, serialize=False, verbose_name='Key')), 19 | ('user_id', models.PositiveBigIntegerField(db_index=True, verbose_name='User')), 20 | ('created', models.DateTimeField(auto_now_add=True, verbose_name='Created')), 21 | ('last_use', models.DateTimeField(auto_now=True, verbose_name='Last use')), 22 | ('active', models.BooleanField(default=False)), 23 | ], 24 | options={ 25 | 'verbose_name': 'Token', 26 | 'verbose_name_plural': 'Tokens', 27 | }, 28 | ), 29 | migrations.CreateModel( 30 | name='User', 31 | fields=[ 32 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 33 | ('password', models.CharField(max_length=128, verbose_name='password')), 34 | ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), 35 | ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), 36 | ('username', models.CharField(max_length=24, unique=True)), 37 | ('email', models.EmailField(default=None, max_length=254, null=True, unique=True)), 38 | ('first_name', models.CharField(default=None, max_length=32, null=True)), 39 | ('last_name', models.CharField(default=None, max_length=32, null=True)), 40 | ('date_of_birth', models.DateField(default=None, null=True)), 41 | ('date_joined', models.DateField(default=None, null=True)), 42 | ('is_active', models.BooleanField(default=True)), 43 | ('is_staff', models.BooleanField(default=False)), 44 | ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.group', verbose_name='groups')), 45 | ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.permission', verbose_name='user permissions')), 46 | ], 47 | options={ 48 | 'verbose_name': 'user', 49 | 'verbose_name_plural': 'users', 50 | 'db_table': 'auth_user', 51 | }, 52 | ), 53 | ] 54 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | 3 | services: 4 | postgres: 5 | image: postgres:14.6-bullseye 6 | restart: always 7 | ports: 8 | - "${POSTGRES_PORT:-5432}:5432" 9 | environment: 10 | - POSTGRES_USER=${POSTGRES_USER:-postgres} 11 | - POSTGRES_PASSWORD=${POSTGRES_PASSWORD:-postgres} 12 | - POSTGRES_DB=${POSTGRES_DB:-postgres} 13 | volumes: 14 | - postgres_data:/var/lib/postgresql/data/ 15 | healthcheck: 16 | test: [ "CMD", "pg_isready", "-q", "-d", "postgres", "-U", "postgres" ] 17 | interval: 3s 18 | timeout: 3s 19 | retries: 10 20 | rabbitmq: 21 | image: rabbitmq:3-management-alpine 22 | restart: always 23 | healthcheck: 24 | test: [ "CMD", "rabbitmqctl", "status" ] 25 | interval: 3s 26 | timeout: 3s 27 | retries: 10 28 | ports: 29 | - "${RABBITMQ_PORT:-5672}:5672" 30 | - "${RABBITMQ_MANAGEMENT_PORT:-15672}:15672" 31 | environment: 32 | - RABBITMQ_DEFAULT_USER=${RABBITMQ_DEFAULT_USER:-rabbitmq} 33 | - RABBITMQ_DEFAULT_PASS=${RABBITMQ_DEFAULT_PASS:-rabbitmq} 34 | volumes: 35 | - rabbitmq_data:/var/lib/rabbitmq/ 36 | - rabbitmq_log:/var/log/rabbitmq 37 | django: 38 | image: ${DOCKER_BASE_IMAGE:-harleyking/dj-ms-core:latest} 39 | build: 40 | context: . 41 | healthcheck: 42 | test: curl -f http://localhost:8000/health || exit 1 43 | interval: 3s 44 | timeout: 3s 45 | retries: 10 46 | depends_on: 47 | postgres: 48 | condition: service_healthy 49 | rabbitmq: 50 | condition: service_healthy 51 | environment: 52 | - BROKER_URL=amqp://${RABBITMQ_DEFAULT_USER:-rabbitmq}:${RABBITMQ_DEFAULT_PASS:-rabbitmq}@rabbitmq:5672 53 | - DATABASE_URL=postgres://${POSTGRES_USER:-postgres}:${POSTGRES_PASSWORD:-postgres}@postgres/${POSTGRES_DB:-postgres} 54 | env_file: 55 | - .env 56 | celery: 57 | image: ${DOCKER_BASE_IMAGE:-harleyking/dj-ms-core:latest} 58 | command: celery -A core worker -l info --concurrency 1 -P solo -E 59 | depends_on: 60 | django: 61 | condition: service_healthy 62 | postgres: 63 | condition: service_healthy 64 | rabbitmq: 65 | condition: service_healthy 66 | environment: 67 | - BROKER_URL=amqp://${RABBITMQ_DEFAULT_USER:-rabbitmq}:${RABBITMQ_DEFAULT_PASS:-rabbitmq}@rabbitmq:5672 68 | - DATABASE_URL=postgres://${POSTGRES_USER:-postgres}:${POSTGRES_PASSWORD:-postgres}@postgres/${POSTGRES_DB:-postgres} 69 | env_file: 70 | - .env 71 | celery-beat: 72 | image: ${DOCKER_BASE_IMAGE:-harleyking/dj-ms-core:latest} 73 | command: celery -A core beat -l info --scheduler django_celery_beat.schedulers.DatabaseScheduler 74 | depends_on: 75 | django: 76 | condition: service_healthy 77 | postgres: 78 | condition: service_healthy 79 | rabbitmq: 80 | condition: service_healthy 81 | environment: 82 | - BROKER_URL=amqp://${RABBITMQ_DEFAULT_USER:-rabbitmq}:${RABBITMQ_DEFAULT_PASS:-rabbitmq}@rabbitmq:5672 83 | - DATABASE_URL=postgres://${POSTGRES_USER:-postgres}:${POSTGRES_PASSWORD:-postgres}@postgres/${POSTGRES_DB:-postgres} 84 | env_file: 85 | - .env 86 | 87 | 88 | volumes: 89 | postgres_data: 90 | rabbitmq_data: 91 | rabbitmq_log: 92 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Django microservice core 2 | 3 | 4 | ![GitHub release (latest by date)](https://img.shields.io/github/v/release/dj-ms/dj-ms-core?display_name=release&style=for-the-badge) 5 | ![GitHub commit activity](https://img.shields.io/github/commit-activity/m/dj-ms/dj-ms-core?style=for-the-badge) 6 | ![GitHub issues](https://img.shields.io/github/issues/dj-ms/dj-ms-core?style=for-the-badge) 7 | ![GitHub closed issues](https://img.shields.io/github/issues-closed-raw/dj-ms/dj-ms-core?style=for-the-badge) 8 | ![GitHub repo size](https://img.shields.io/github/repo-size/dj-ms/dj-ms-core?style=for-the-badge) 9 | ![Docker Image Size (latest by date)](https://img.shields.io/docker/image-size/harleyking/dj-ms-core?style=for-the-badge) 10 | 11 | 12 | --- 13 | ## Purpose 14 |

15 | This project helps to develop microservices with Django Framework. 16 | 17 | No more tens of apps in one project. 18 | Separate your apps into microservices and connect them under one domain. 19 | Every Django app can be developed and deployed separately, even by different teams. 20 | But all of them will be under one domain and will have unified authentication. 21 | 22 |

23 | 24 | 25 | --- 26 | > #### Note: First of all this is simple Django project with some customizations. If you are newbie in Django, you can use this project as a template for your own projects. I'm not very cool in programming, but I have some experience in Python and Django and want to share it with you. 27 | 28 | 29 | --- 30 | > #### Not ready for production. Will be ready with version 1.0.0 31 | 32 | 33 | --- 34 | ## How it works 35 |

36 | How it works 37 |

38 | 39 | 40 | --- 41 | ## What's inside 42 | - [x] Unified authentication in all microservices 43 | - [x] Production deployment with Docker Compose or Kubernetes 44 | - [x] Celery, Celery Beat, RabbitMQ, Postgres and Nginx included in Docker Compose 45 | - [x] Expiring Bearer Token authentication 46 | - [x] Custom user model 47 | - [x] Custom db router for auth models 48 | - [x] Object changes logging to one DB with [django-auditlog](https://github.com/jazzband/django-auditlog) 49 | - [x] Static and media files served by Nginx 50 | - [ ] Message brokers integration (there is RabbitMQ in docker compose, but at this time it's only used by Celery) 51 | - [ ] Automated CI/CD either with GitHub Actions, GitLab CI or Bitbucket Pipelines 52 | - [ ] Active directory authentication 53 | - [ ] Automatic discovery of microservices 54 | 55 | 56 | --- 57 | ## Requirements 58 | 59 | - Docker and Docker Compose - [Download](https://docs.docker.com/get-docker/) 60 | > Of course, you can just run project without docker right on your machine. But docker is recommended way. 61 | 62 | - Python 3.10 - [Download](https://www.python.org/downloads/) 63 | > You will need Python only if you want to run this project locally without docker. 64 | 65 | 66 | --- 67 | ## Installation 68 | 69 | ### [Run locally using docker compose](docs/run_locally_using_docker_compose.md) 70 | 71 | ### [Deploy to server using docker compose](docs/deploy_to_server_using_docker_compose.md) 72 | 73 | ### [Deploy to production using Kubernetes](docs/deploy_in_production_using_k8s.md) 74 | 75 | 76 | --- 77 | ## Examples 78 | 79 | You can find example microservice apps under [forks](https://github.com/dj-ms/dj-ms-core/network/members) section. 80 | 81 | Also, there is special example repos: 82 | - [dj-ms-example-app](https://github.com/dj-ms/dj-ms-example-app) 83 | - [dj-ms-telegram-bot](https://github.com/dj-ms/dj-ms-telegram-bot) 84 | 85 | 86 | --- 87 | ## Contributing 88 | I will be very happy if you will contribute to this project. You can help with code, documentation, ideas, etc. 89 | Just create an issue or pull request. I will be glad to discuss it with you. 90 | Also, you can contact me via email: astafeev0308@gmail.com. 91 | -------------------------------------------------------------------------------- /authentication/api/views/auth_views.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import logging 3 | 4 | from django.contrib.auth import authenticate, password_validation, login, logout 5 | from django.core.exceptions import ValidationError 6 | from django.http import HttpResponse 7 | from django.utils import timezone 8 | from django.views.decorators.csrf import csrf_exempt 9 | from rest_framework import status 10 | from rest_framework.decorators import api_view, permission_classes 11 | from rest_framework.permissions import AllowAny 12 | from rest_framework.response import Response 13 | from authentication.models import User, Token 14 | from django.utils.translation import gettext_lazy as _ 15 | from django.conf import settings 16 | 17 | 18 | TOKEN_TTL = settings.REST_AUTH_TOKEN_TTL 19 | 20 | 21 | @csrf_exempt 22 | @api_view(['POST']) 23 | @permission_classes([AllowAny]) 24 | def login_view(request): 25 | username = request.data.get('username') 26 | password = request.data.get('password') 27 | if None in (username, password): 28 | return Response(status=status.HTTP_400_BAD_REQUEST) 29 | user_exists = User.objects.filter(username=username).exists() 30 | if not user_exists: 31 | return Response(status=status.HTTP_404_NOT_FOUND) 32 | user = authenticate(request, username=username, password=password) 33 | if user is None: 34 | return Response(status=status.HTTP_403_FORBIDDEN) 35 | now = timezone.now() 36 | diff = now - datetime.timedelta(seconds=TOKEN_TTL) 37 | token, created = Token.objects.get_or_create(user_id=user.pk, last_use__gt=diff, active=True) 38 | login(request, user) 39 | return Response({'token': token.key, 40 | 'user': { 41 | 'id': user.pk, 42 | 'username': user.username, 43 | 'email': user.email, 44 | 'first_name': user.first_name, 45 | 'last_name': user.last_name, 46 | }}) 47 | 48 | 49 | @csrf_exempt 50 | @api_view(['POST']) 51 | def logout_view(request): 52 | if request.user.is_anonymous: 53 | return Response(status=status.HTTP_401_UNAUTHORIZED) 54 | user = request.user 55 | Token.objects.filter(user_id=user.pk).update(active=False) 56 | logout(request) 57 | return Response(status=status.HTTP_200_OK) 58 | 59 | 60 | @csrf_exempt 61 | @api_view(['POST']) 62 | @permission_classes([AllowAny]) 63 | def register_view(request): 64 | username = request.POST.get('username') 65 | email = request.POST.get('email') 66 | password1 = request.POST.get('password1') 67 | password2 = request.POST.get('password2') 68 | first_name = request.POST.get('first_name') 69 | if None in [username, password1, password2]: 70 | return Response(status=status.HTTP_400_BAD_REQUEST) 71 | if password1 != password2: 72 | return HttpResponse(_('Passwords does not match'), status=status.HTTP_400_BAD_REQUEST) 73 | try: 74 | password_validation.validate_password(password1) 75 | except ValidationError as error: 76 | logging.error(error) 77 | return HttpResponse(status=status.HTTP_403_FORBIDDEN) 78 | if email: 79 | email_exists = User.objects.filter(email=email).exists() 80 | if email_exists: 81 | return HttpResponse(_('User with that email is already registered'), status=status.HTTP_403_FORBIDDEN) 82 | username_exists = User.objects.filter(username=username).exists() 83 | if username_exists: 84 | return HttpResponse(_('User with that username is already registered'), status=status.HTTP_403_FORBIDDEN) 85 | last_name = request.POST.get('last_name') 86 | new_user = User( 87 | username=username, 88 | email=email, 89 | first_name=first_name, 90 | last_name=last_name, 91 | is_active=True 92 | ) 93 | new_user.set_password(password1) 94 | new_user.save() 95 | return Response(status=status.HTTP_201_CREATED) 96 | 97 | -------------------------------------------------------------------------------- /deploy.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | 4 | help() { 5 | echo "Usage: deploy.sh [OPTIONS]" 6 | echo 7 | echo "Options:" 8 | echo "-d, --down Don't build or deploy, just down the stack" 9 | echo "-n, --no-build Don't build, just deploy" 10 | echo "-rn Recreate nginx conf file" 11 | echo "-rno Only recreate nginx conf file and exit" 12 | echo "-h, --help Print this Help." 13 | echo 14 | } 15 | 16 | 17 | # Short replacement for long docker compose command 18 | compose () { 19 | # shellcheck disable=SC2086 20 | local args=$*; docker compose -f docker-compose.yml -f docker-compose.prod.yml $args 21 | } 22 | 23 | sed_alt () { 24 | local SED=sed args=$* 25 | if [[ $(uname) == "Darwin" ]] ; then 26 | SED=gsed 27 | type $SED >/dev/null 2>&1 || { echo >&2 "$SED it's not installed. Try: brew install gnu-sed"; exit 1; } 28 | fi 29 | # shellcheck disable=SC2086 30 | $SED ${args} 31 | } 32 | 33 | build=true rno=false rn=false 34 | while [[ $# -gt 0 ]]; do 35 | case $1 in 36 | -d|--down) 37 | compose down; 38 | exit;; 39 | -n|--no-build) 40 | build=false; 41 | shift;; 42 | -rno) 43 | rno=true; 44 | shift;; 45 | -rn) 46 | rn=true; 47 | shift;; 48 | -h|--help) 49 | help 50 | exit 0;; 51 | *) 52 | echo "Unknown option: $1" 53 | exit 2;; 54 | esac 55 | done 56 | 57 | DJ_MS_APP_LABEL=$(grep DJ_MS_APP_LABEL .env | xargs | awk -F "=" '{print $2}') 58 | if [[ -z "${DJ_MS_APP_LABEL}" ]]; then 59 | DJ_MS_APP_LABEL="dj-ms-core" 60 | fi 61 | 62 | create_nginx_conf () { 63 | cp nginx/app-locations.conf nginx/"${DJ_MS_APP_LABEL}".conf 64 | DJANGO_WEB_PORT=$(grep DJANGO_WEB_PORT .env | xargs | awk -F "=" '{print $2}') 65 | if [[ $DJ_MS_APP_LABEL == 'core' ]]; then 66 | sed_alt -i "s|DJ_MS_APP_LABEL/||g" nginx/"${DJ_MS_APP_LABEL}".conf 67 | sed_alt -i "s|DJANGO_WEB_PORT|$DJANGO_WEB_PORT|g" nginx/"${DJ_MS_APP_LABEL}".conf 68 | else 69 | sed_alt -i "s/DJ_MS_APP_LABEL/$DJ_MS_APP_LABEL/g" nginx/"${DJ_MS_APP_LABEL}".conf 70 | sed_alt -i "s/DJANGO_WEB_PORT/$DJANGO_WEB_PORT/g" nginx/"${DJ_MS_APP_LABEL}".conf 71 | fi 72 | 73 | echo " 74 | Created nginx/${DJ_MS_APP_LABEL}.conf. 75 | Copy it to /etc/nginx/ manually and reload Nginx: 76 | 77 | > cp nginx/${DJ_MS_APP_LABEL}.conf /etc/nginx/sites-available/${DJ_MS_APP_LABEL}.conf 78 | > ln -s /etc/nginx/sites-available/${DJ_MS_APP_LABEL}.conf /etc/nginx/sites-enabled/${DJ_MS_APP_LABEL}.conf 79 | > nginx -s reload 80 | 81 | Tip: If you want to recreate the file, delete it and run this script again with -rno option: 82 | 83 | > rm nginx/${DJ_MS_APP_LABEL}.conf 84 | > ./deploy.sh -rno 85 | " 86 | } 87 | 88 | if $rno; then 89 | create_nginx_conf; exit 0 90 | fi 91 | 92 | if $build; then 93 | DOCKER_BASE_IMAGE=$(grep DOCKER_BASE_IMAGE .env | xargs | awk -F "=" '{print $2}') 94 | if [[ -z "${DOCKER_BASE_IMAGE}" ]]; then 95 | DOCKER_BASE_IMAGE="harleyking/dj-ms-core:latest" 96 | fi 97 | . build.sh -t "$DOCKER_BASE_IMAGE" || exit 126 98 | fi 99 | 100 | service_scale () { 101 | local count=$1 scales=""; for i in "${!services[@]}"; do scales+="--scale ${services[i]}=$count "; done 102 | echo "$scales" 103 | } 104 | 105 | get_services () { 106 | local name; services=() 107 | while IFS= read -r service || [[ -n "$service" ]]; do if [[ "${service}" == "#"* ]]; then continue; fi 108 | name=$(echo "$service" | awk '{print $1}'); services+=("$name") 109 | done < Services 110 | } 111 | 112 | rollback () { 113 | local last service_name 114 | last=$(compose ps | tail -n +2 | awk '{print $1}' | awk -F- '{print $NF}' | sort -nr | head -n 1) 115 | service_name=$(grep COMPOSE_PROJECT_NAME .env | xargs | awk -F= '{print $2}') 116 | compose ps | tail -n +2 | awk '{print $1}' | grep "${service_name}-.*-${last}" | xargs docker rm -f 117 | } 118 | 119 | 120 | if [ -z "$(docker compose ps -q)" ]; then 121 | compose up -d || (error_code=$?; compose down; exit $error_code) 122 | else 123 | get_services 124 | # shellcheck disable=SC2046 125 | compose up -d --no-recreate $(echo $(service_scale 2)) || (code=$?; rollback; exit $code) 126 | # shellcheck disable=SC2046 127 | compose up -d --no-recreate $(echo $(service_scale 1)) || (code=$?; rollback; exit $code) 128 | compose exec -it nginx nginx -s reload 129 | fi 130 | 131 | if [[ ! -f nginx/${DJ_MS_APP_LABEL}.conf || $rn ]]; then 132 | create_nginx_conf 133 | fi 134 | 135 | -------------------------------------------------------------------------------- /docs/deploy_to_server_using_docker_compose.md: -------------------------------------------------------------------------------- 1 | # Deploy to server 2 | 3 | 4 | --- 5 | ## Prerequisites 6 | I assume, you have docker with compose plugin installed on your server. 7 | Please, refer to the [official documentation](https://docs.docker.com/engine/install/) to install it. 8 | 9 |
10 | 11 | Clone the repository to your server: 12 | ```shell 13 | git clone https://github.com/dj-ms/dj-ms-core.git 14 | ``` 15 | 16 |
17 | 18 | Go to the project directory: 19 | ```shell 20 | cd dj-ms-core 21 | ``` 22 | 23 |
24 | 25 | Create the `.env` file and set the environment variables according to the instructions. 26 | [Set environment variables](set_env_vars.md). 27 | ```shell 28 | nano .env 29 | ``` 30 | 31 | 32 | --- 33 | ## Run project 34 | Build the docker image: 35 | ```shell 36 | docker compose build 37 | ``` 38 | 39 | --- 40 | ### Run: 41 | 42 | Core service: 43 | ```shell 44 | docker compose -f docker-compose.yml -f docker-compose.core.yml -f docker-compose.prod.yml up -d 45 | ``` 46 | 47 |
48 | 49 | Any microservice: 50 | ```shell 51 | docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d 52 | ``` 53 | 54 | > As you can see, we use two docker compose files: `docker-compose.yml` and `docker-compose.prod.yml`. 55 | And that's all the difference between running locally and running in production. 56 | So you can use all the commands you used to run locally. Just add `-f docker-compose.yml -f docker-compose.prod.yml` to them. 57 | 58 | 59 | > On master node you might need to open ports for DB and RabbitMQ. 60 | > Search solution in the internet, because it depends on your cloud provider, OS, etc. 61 | > To open ports in VPS on Ubuntu, you can use the following commands: 62 | > ```shell 63 | > sudo ufw allow 5432/tcp 64 | > sudo ufw allow 5672/tcp 65 | > sudo ufw allow 15672/tcp 66 | > sudo iptables -I INPUT -p tcp -m tcp --dport 5432 -j ACCEPT 67 | > sudo iptables -I INPUT -p tcp -m tcp --dport 5672 -j ACCEPT 68 | > sudo iptables -I INPUT -p tcp -m tcp --dport 15672 -j ACCEPT 69 | > ``` 70 | > And then save the rules: 71 | > ```shell 72 | > sudo iptables-save > /etc/iptables/rules.v4 73 | > ``` 74 | > This is not a final solution, but it works for me. 75 | 76 | ## Set up Nginx 77 | 78 | ### Install Nginx 79 | 80 | Ubuntu: 81 | ```shell 82 | sudo apt install nginx -y 83 | ``` 84 | 85 |
86 | 87 | CentOS: 88 | ```shell 89 | sudo yum install nginx -y 90 | ``` 91 | 92 | ### Configure Nginx 93 | 94 | Create a new file in the `/etc/nginx/sites-available` directory: 95 | ```shell 96 | sudo nano /etc/nginx/sites-available/ 97 | ``` 98 | 99 |
100 | 101 | Paste the following content to the file: 102 | ```nginx 103 | server { 104 | listen 80; 105 | server_name www.; 106 | 107 | location / { 108 | proxy_pass http://localhost:; 109 | proxy_http_version 1.1; 110 | proxy_set_header Upgrade $http_upgrade; 111 | proxy_set_header Connection "upgrade"; 112 | proxy_set_header Host $host; 113 | proxy_set_header X-Real-IP $remote_addr; 114 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 115 | } 116 | } 117 | ``` 118 | 119 |
120 | 121 | Create a symbolic link to the `/etc/nginx/sites-enabled` directory: 122 | ```shell 123 | sudo ln -s /etc/nginx/sites-available/ /etc/nginx/sites-enabled/ 124 | ``` 125 | 126 |
127 | 128 | Remove the default configuration file: 129 | ```shell 130 | sudo rm /etc/nginx/sites-enabled/default 131 | ``` 132 | 133 |
134 | 135 | Restart Nginx: 136 | ```shell 137 | sudo systemctl restart nginx # or "nginx -s reload" to reload the configuration without restarting the service 138 | ``` 139 | 140 | ### Check Nginx configuration 141 | 142 | Open the following URL in your browser: 143 | ```shell 144 | http://your-server-ip-address//admin/ # Skip if you didn't set it. 145 | ``` 146 | 147 | If you see the Django admin page, then everything is fine. 148 | 149 | 150 | ## Configure HTTPS 151 | 152 | First, get some domain name from any service, for example, from [namecheap](https://www.namecheap.com) or [freenom](https://www.freenom.com). 153 | Create A-record for your domain name and point it to your server IP address. 154 | 155 |
156 | 157 | Check, that your domain name is accessible from the internet: 158 | ```shell 159 | curl -I http:// 160 | ``` 161 | 162 |
163 | 164 | > Sometimes you need to wait some time, until your domain name will be accessible from the internet. Maybe 5 minutes or more. 165 | 166 | ### Install certbot 167 | 168 | Ubuntu: 169 | ```shell 170 | sudo apt install python3-certbot-nginx -y 171 | ``` 172 | 173 |
174 | 175 | CentOS: 176 | ```shell 177 | sudo yum install python3-certbot-nginx -y 178 | ``` 179 | 180 | ### Get SSL certificate 181 | 182 | ```shell 183 | sudo certbot --nginx -d -d www. 184 | ``` 185 | 186 | You will be asked to enter your email address and agree with the terms of service. 187 | After that, you will be asked to choose the redirect method. Choose the second option. 188 | 189 | ### Check SSL certificate 190 | 191 | Open the following URL in your browser: 192 | ```shell 193 | https:////admin/ # Skip if you didn't set it. 194 | ``` 195 | 196 | If you see the Django admin page, then everything is fine. 197 | 198 | ### Configure automatic renewal of SSL certificate 199 | 200 | ```shell 201 | sudo crontab -e 202 | ``` 203 | 204 |
205 | 206 | Add the following line to the end of the file: 207 | ```shell 208 | 0 0 * * * /usr/bin/certbot renew --quiet 209 | ``` 210 | 211 | Save the file and exit. 212 | 213 | ### Check automatic renewal of SSL certificate 214 | 215 | ```shell 216 | sudo certbot renew --dry-run 217 | ``` 218 | 219 | If you see the following message, then everything is fine: 220 | ```shell 221 | Congratulations, all renewals succeeded. The following certs have been renewed: 222 | /etc/letsencrypt/live//fullchain.pem (success) 223 | ``` 224 | 225 | -------------------------------------------------------------------------------- /docs/deploy_in_production_using_k8s.md: -------------------------------------------------------------------------------- 1 | # Deploy to production using Kubernetes 2 | 3 | > **Note:** This is just an example. 4 | > Please, review all the files in the `k8s` directory before applying them to your cluster. 5 | 6 | 7 | --- 8 | ## Prerequisites 9 | 10 | > I assume that you have a Kubernetes cluster and `kubectl` installed. 11 | > Other things I will try to describe here. 12 | 13 | Copy example files 14 | 15 | ```shell 16 | cp -r k8s/examples/app k8s/app 17 | ``` 18 | 19 | Create a namespace 20 | 21 | ```shell 22 | kubectl create namespace dj-ms-core 23 | ``` 24 | 25 | 26 | --- 27 | ### PostgreSQL 28 | 29 | If you don't have a PostgreSQL database, you can install it using the following commands: 30 | 31 | ```shell 32 | kubectl create namespace postgres 33 | kubectl apply -f k8s/examples/postgres -n postgres 34 | ``` 35 | 36 | You will need to create a database and a user for your application. 37 | 38 | Get pod name: 39 | 40 | ```shell 41 | kubectl get pods -n postgres 42 | ``` 43 | 44 | You should see something like this: 45 | 46 | ```shell 47 | NAME READY STATUS RESTARTS AGE 48 | postgres-bbb44c799-g7v9j 1/1 Running 0 2m 49 | ``` 50 | 51 | Then you can connect to the database: 52 | 53 | ```shell 54 | kubectl exec -it -n postgres -- psql -U postgres 55 | ``` 56 | 57 | Create a database: 58 | 59 | ```sql 60 | CREATE DATABASE dj_ms_core; 61 | ``` 62 | 63 | Create a user: 64 | 65 | ```sql 66 | CREATE USER dj_ms_core WITH ENCRYPTED PASSWORD 'dj_ms_core'; 67 | ``` 68 | 69 | Grant permissions and exit: 70 | 71 | ```sql 72 | GRANT ALL PRIVILEGES ON DATABASE dj_ms_core TO dj_ms_core; 73 | exit; 74 | ``` 75 | 76 | 77 | --- 78 | ### RabbitMQ 79 | 80 | If you don't have a RabbitMQ cluster, you can install it using the following commands: 81 | 82 | Install RabbitMQ cluster connector: 83 | 84 | ```shell 85 | kubectl apply -f "https://github.com/rabbitmq/cluster-operator/releases/latest/download/cluster-operator.yml" -n rabbitmq 86 | ``` 87 | 88 | Install RabbitMQ cluster: 89 | 90 | ```shell 91 | kubectl create namespace rabbitmq 92 | kubectl apply -f k8s/examples/rabbitmq -n rabbitmq 93 | ``` 94 | 95 | You will need to create a user for your application. 96 | 97 | Get pod name: 98 | 99 | ```shell 100 | kubectl get pods -n rabbitmq 101 | ``` 102 | 103 | You should see something like this: 104 | 105 | ```shell 106 | NAME READY STATUS RESTARTS AGE 107 | rabbitmq-7c78d7f66b-n84jr 1/1 Running 0 2m 108 | ``` 109 | 110 | Create a user: 111 | 112 | ```shell 113 | kubectl exec -it -n rabbitmq -- rabbitmqctl add_user dj_ms_core dj_ms_core 114 | ``` 115 | 116 | Grant permissions: 117 | 118 | ```shell 119 | kubectl exec -it -n rabbitmq -- rabbitmqctl set_user_tags dj_ms_core administrator 120 | kubectl exec -it -n rabbitmq -- rabbitmqctl set_permissions -p / dj_ms_core ".*" ".*" ".*" 121 | ``` 122 | 123 | 124 | --- 125 | ### Ingress 126 | 127 | If you don't have an Ingress controller, you can install ingres-nginx using the following commands: 128 | 129 | ```shell 130 | kubectl apply -f k8s/examples/ingress-nginx 131 | ``` 132 | 133 | 134 | --- 135 | ### TLS 136 | 137 | > **NOTE:** If you have a TLS certificate for your domain, you should add it first. 138 | > Otherwise, you can use the self-signed certificates by `Cert Manager`. 139 | 140 | To add a TLS certificate, you should create a secret with the following files: 141 | - `tls.crt` - certificate 142 | - `tls.key` - private key 143 | 144 | Then you can create a secret and deploy the application: 145 | 146 | ```shell 147 | kubectl delete secret dj-ms-core-tls-secret -n dj-ms-core 148 | kubectl create secret tls dj-ms-core-tls-secret --cert=k8s/app/tls.crt --key=k8s/app/tls.key -n dj-ms-core 149 | ``` 150 | 151 | Then you should add the following lines to the `Ingress` resource under the `spec` section: 152 | 153 | ```yaml 154 | ... 155 | tls: 156 | - hosts: 157 | - app.dj-ms.dev 158 | secretName: dj-ms-core-tls-secret 159 | ... 160 | ``` 161 | 162 | 163 | --- 164 | ### Cert Manager 165 | 166 | If you don't have a Cert Manager, you can install it using the following commands: 167 | 168 | ```shell 169 | kubectl create namespace cert-manager 170 | kubectl apply -f k8s/examples/cert-manager -n cert-manager 171 | ``` 172 | 173 | To enable automatic TLS certificate generation, add the following **annotation** to the `Ingress` resource: 174 | 175 | ```yaml 176 | ... 177 | ... 178 | cert-manager.io/cluster-issuer: letsencrypt-production 179 | ... 180 | ``` 181 | 182 | Then add following lines to the `Ingress` resource under the `spec` section: 183 | 184 | ```yaml 185 | ... 186 | tls: 187 | - hosts: 188 | - app.dj-ms.dev 189 | secretName: dj-ms-core-tls-secret 190 | ... 191 | ``` 192 | 193 | 194 | --- 195 | ## Deploy 196 | 197 | First of all, you should review all the files in the `k8s/app` directory. 198 | Change the values as you need. 199 | 200 | After that, you should create an `.env` file in the `k8s/app` directory. 201 | It should contain the following variables: 202 | - `DJANGO_DEBUG` - normally `False` for production 203 | - `DJANGO_SECRET_KEY` - some random string. You can generate one with `openssl rand -base64 32` 204 | - `DATABASE_URL` - Postgres connection string, e.g. `postgres://dj_ms_core:dj_ms_core@postgres.postgres:5432/dj_ms_core` 205 | - `DJANGO_ALLOWED_HOSTS` - your domain name. For example, `app.dj-ms.dev` 206 | - `DJANGO_CSRF_TRUSTED_ORIGINS` - usually the same as `DJANGO_ALLOWED_HOSTS` but with `https://` prefix. For example, `https://app.dj-ms.dev` 207 | - `BROKER_URL` - RabbitMQ connection string, e.g. `amqp://dj_ms_core:dj_ms_core@rabbitmq.rabbitmq:5672` 208 | 209 | Then you can create a secret and deploy the application: 210 | 211 | ```shell 212 | kubectl delete secret dj-ms-core-secret -n dj-ms-core 213 | kubectl create secret generic dj-ms-core-secret --from-env-file=k8s/app/.env -n dj-ms-core 214 | kubectl apply -f k8s/app -n dj-ms-core 215 | ``` 216 | 217 | 218 | --- 219 | ## Access your application 220 | 221 | After successful deployment, you should be able to access your application at `https://app.example.com/admin`. 222 | But if it's first time you deploy your application, you should create a superuser. 223 | 224 | ```shell 225 | kubectl get pods -n dj-ms-core 226 | ``` 227 | 228 | ```shell 229 | kubectl exec -it -n dj-ms-core -- python manage.py createsuperuser 230 | ``` 231 | 232 | Then you can access your application at `https://app.example.com/admin` and log in with the credentials you have just created. 233 | -------------------------------------------------------------------------------- /docs/set_env_vars.md: -------------------------------------------------------------------------------- 1 | # Set environment variables 2 | 3 | 4 | > Note: you don't need to set all of these variables. 5 | > Docker compose files already have default values for most of them. 6 | > But in production you have to set at least `DJANGO_SECRET_KEY`. 7 | --- 8 | Also, when running / deploying microservices, there is some requirements: 9 | 10 | > - use exact the same `DJANGO_SECRET_KEY` for all microservices; 11 | > - all services except `core` needs to have `AUTH_DB_URL` set to `core` service's `DATABASE_URL`; 12 | > - all services except `core` needs to have `BROKER_URL` set to `core` service's `BROKER_URL`. 13 | 14 | Other requirements will be explained below. 15 | 16 | 17 | --- 18 | ## General 19 | 20 | ### Core service 21 | To get started with core service on local machine, you don't need to set any environment variables. 22 | To deploy it to the server in production mode, `DJANGO_SECRET_KEY`, 23 | `DJANGO_ALLOWED_HOSTS` and `DJANGO_CSRF_TRUSTED_ORIGINS` will be enough: 24 | 25 | ```dotenv 26 | DJANGO_SECRET_KEY= 27 | ``` 28 | 29 | ### Fork app / microservice 30 | To run second / third / etc. microservice somewhere, including server in production mode, 31 | you need to set at least the following variables: 32 | 33 | ```dotenv 34 | # The same secret key as in core service 35 | DJANGO_SECRET_KEY= 36 | 37 | # Any free port, for example 5433 38 | POSTGRES_PORT= 39 | 40 | # Any free port, for example 5051 41 | PGADMIN_PORT= 42 | 43 | # Some unique label, for example "products" 44 | DJ_MS_APP_LABEL= 45 | 46 | # Core service's database url 47 | AUTH_DB_URL=postgres://postgres:postgres@host.docker.internal:5432/postgres 48 | 49 | # Core service's broker url 50 | BROKER_URL=amqp://rabbitmq:rabbitmq@host.docker.internal:5672 51 | 52 | # Any free port, for example 8001 53 | DJANGO_WEB_PORT= 54 | ``` 55 | 56 | 57 | --- 58 | ## Django 59 | 60 | ```dotenv 61 | DJANGO_DEBUG= 62 | ``` 63 | 64 | In production, `DJANGO_DEBUG` is set to `False` in the `docker-compose.prod.yml` file. 65 | In other cases default value will be `True` if not set. 66 | You don't need to set it here unless you want to change it to `False` in _development environment_. 67 | 68 |
69 | 70 | ```dotenv 71 | DJANGO_SECRET_KEY= 72 | ``` 73 | 74 | Use 1 strict secret key for all microservices. 75 | You can generate one using one of these commands: 76 | - `openssl rand -base64 40` 77 | - `openssl rand -hex 40` 78 | - `python -c 'import uuid; print(uuid.uuid4().hex)'` 79 | 80 |
81 | 82 | 83 | ```dotenv 84 | DJANGO_ALLOWED_HOSTS="," 85 | DJANGO_CSRF_TRUSTED_ORIGINS="," 86 | ``` 87 | 88 | For example, you're deploying the project to the server with the hostname `example.com`. 89 | Then you should set these variables to `example.com` and `https://example.com` respectively. 90 | 91 | 92 | ```dotenv 93 | DJANGO_TIME_ZONE= 94 | ``` 95 | 96 | Default timezone is `UTC`. You can change it to your local timezone. For example: `Europe/Warsaw` 97 | 98 |
99 | 100 | ```dotenv 101 | DJANGO_LANGUAGE_CODE= 102 | ``` 103 | 104 | Default language is English (`en-us`). You can change it to your local language. For example: `ru` 105 | 106 |
107 | 108 | ```dotenv 109 | DJANGO_REST_AUTH_TOKEN_TTL= 110 | ``` 111 | 112 | This project has expiring token implementation. You can set the token expiration time in seconds. 113 | Default value is `86400` seconds (24 hours). 114 | 115 | 116 | --- 117 | ## Database 118 | 119 | > By default, the project uses postgres database, built in the `docker-compose.yml` file. 120 | > So you don't need to set this setting unless you want to use another database. 121 | > Default value is `postgres://postgres:postgres@postgres:5432/postgres` 122 | 123 | ```dotenv 124 | DATABASE_URL=postgres://postgres:postgres@postgres:5432/postgres 125 | ``` 126 | 127 | ### Postgres 128 | 129 | ```dotenv 130 | POSTGRES_PORT= 131 | ``` 132 | 133 | Which port should be exposed for **postgres** that built in the `docker-compose.yml` file? 134 | Default value is `5432`. 135 | 136 |
137 | 138 | ```dotenv 139 | POSTGRES_USER= 140 | ``` 141 | 142 | Default **postgres** username is `postgres`. 143 | 144 |
145 | 146 | ```dotenv 147 | POSTGRES_PASSWORD= 148 | ``` 149 | 150 | Default **postgres** password is `postgres`. 151 | 152 |
153 | 154 | ```dotenv 155 | POSTGRES_DB= 156 | ``` 157 | 158 | Default **postgres** database is `postgres`. 159 | 160 | 161 | --- 162 | ## Microservices 163 | 164 | ```dotenv 165 | DOCKER_BASE_IMAGE= 166 | ``` 167 | 168 | Which base image should be used for building the service? 169 | By default, `harleyking/dj-ms-core:latest` image is used. 170 | This setting must be exactly the same in every microservice. 171 | 172 |
173 | 174 | ```dotenv 175 | DJ_MS_APP_LABEL= 176 | ``` 177 | 178 | In main microservice this setting should be skipped. 179 | In every other microservice you should set a unique label for the app. 180 | It will be used for building appropriate docker image and as a url prefix. 181 | For example: label `products` will result in the following docker image: `dj-ms-products:latest`. 182 | And the url for the service will be: `http://localhost:8000/products/` 183 | 184 |
185 | 186 | ```dotenv 187 | AUTH_DB_URL= 188 | ``` 189 | 190 | This is the most interesting part of the project! In core microservice this setting must be skipped. 191 | But! In other microservices you should set this setting to the core microservice database url. 192 | This allows you to use the same authentication database in all microservices. 193 | 194 |
195 | 196 | ```dotenv 197 | BROKER_URL= 198 | ``` 199 | 200 | Same as `AUTH_DB_URL`, but for **RabbitMQ** message broker. 201 | Skip this setting in the core microservice. 202 | In other microservices set it to the core microservice broker url. 203 | 204 |
205 | 206 | ```dotenv 207 | DJANGO_WEB_PORT= 208 | ``` 209 | 210 | Which http port should be exposed for entire service? 211 | By default, `8000` port is used. 212 | But if you're running multiple services on the same machine, you have to change it to another port. 213 | 214 | 215 | --- 216 | ## RabbitMQ 217 | 218 | ```dotenv 219 | RABBITMQ_PORT= 220 | ``` 221 | 222 | Which port should be exposed for **RabbitMQ** that built in the `docker-compose.yml` file? 223 | Default value is `5672`. 224 | 225 |
226 | 227 | ```dotenv 228 | RABBITMQ_MANAGEMENT_PORT= 229 | ``` 230 | 231 | Which port should be exposed for **RabbitMQ** management that built in the `docker-compose.yml` file? 232 | Default value is `15672`. 233 | 234 |
235 | 236 | ```dotenv 237 | RABBITMQ_DEFAULT_USER= 238 | ``` 239 | 240 | Default username is `rabbitmq`. 241 | 242 |
243 | 244 | ```dotenv 245 | RABBITMQ_DEFAULT_PASS= 246 | ``` 247 | 248 | Default password is `rabbitmq`. 249 | 250 | 251 | --- 252 | ### Sentry 253 | 254 | ```dotenv 255 | SENTRY_DSN= 256 | ``` 257 | 258 | Your **Sentry** `DSN`. You can get it from your **Sentry** project settings. 259 | 260 |
261 | 262 | ```dotenv 263 | SENTRY_ENVIRONMENT= 264 | ``` 265 | 266 | Default value is `development`. 267 | 268 | -------------------------------------------------------------------------------- /core/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for dj_ms_core project. 3 | 4 | Generated by 'django-admin startproject' using Django 4.1.6. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.1/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/4.1/ref/settings/ 11 | """ 12 | import os 13 | from pathlib import Path 14 | 15 | import dj_database_url 16 | import dotenv 17 | 18 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 19 | BASE_DIR = Path(__file__).resolve().parent.parent 20 | 21 | 22 | # Load env variables from *.env* file 23 | dotenv_file = os.path.join(BASE_DIR, ".env") 24 | if os.path.isfile(dotenv_file): 25 | dotenv.load_dotenv(dotenv_file) 26 | 27 | 28 | # Quick-start development settings - unsuitable for production 29 | # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ 30 | 31 | # SECURITY WARNING: keep the secret key used in production secret! 32 | SECRET_KEY = os.getenv('DJANGO_SECRET_KEY', 'django-insecure-9uq@=l5ykga+r$2=+nk+abwy)ej-y2n%!-u^fe^0=ybj)*+)d!') 33 | 34 | # SECURITY WARNING: don't run with debug turned on in production! 35 | DEBUG = False if os.getenv('DJANGO_DEBUG') == 'False' else True 36 | 37 | # Use different app label for each microservice. For example, 'product' for product microservice 38 | APP_LABEL = os.getenv('DJ_MS_APP_LABEL', '') 39 | 40 | ALLOWED_HOSTS = [ 41 | '127.0.0.1', 42 | 'localhost' 43 | ] 44 | 45 | extra_allowed_hosts = os.getenv('DJANGO_ALLOWED_HOSTS', None) 46 | 47 | if extra_allowed_hosts: 48 | assert isinstance(extra_allowed_hosts.split(','), list) 49 | ALLOWED_HOSTS.extend(extra_allowed_hosts.split(',')) 50 | 51 | CORS_ORIGIN_ALLOW_ALL = False 52 | 53 | CORS_ALLOWED_ORIGINS = ( 54 | 'http://127.0.0.1:8000', 55 | 'http://localhost:8000', 56 | ) 57 | 58 | CSRF_TRUSTED_ORIGINS = [ 59 | 'http://localhost:8000', 60 | 'http://127.0.0.1:8000', 61 | ] 62 | 63 | extra_csrf_trusted_origins = os.getenv('DJANGO_CSRF_TRUSTED_ORIGINS', None) 64 | 65 | if extra_csrf_trusted_origins: 66 | assert isinstance(extra_csrf_trusted_origins.split(','), list) 67 | CSRF_TRUSTED_ORIGINS.extend(extra_csrf_trusted_origins.split(',')) 68 | 69 | # Application definition 70 | 71 | INSTALLED_APPS = [ 72 | 'django.contrib.admin', 73 | 'django.contrib.auth', 74 | 'django.contrib.contenttypes', 75 | 'django.contrib.sessions', 76 | 'django.contrib.messages', 77 | 'django.contrib.staticfiles', 78 | 79 | # third party apps 80 | 'whitenoise.runserver_nostatic', 81 | 'corsheaders', 82 | 'rest_framework', 83 | 'django_celery_beat', 84 | 'django_celery_results', 85 | 'auditlog', 86 | 87 | # microservice apps 88 | 'authentication', 89 | 'ms_auth_router', 90 | 'app', 91 | 92 | # django_cleanup cleanup files after deleting model instance with FileField or ImageField fields 93 | 'django_cleanup.apps.CleanupConfig' 94 | ] 95 | 96 | MIDDLEWARE = [ 97 | 'core.middleware.HealthCheckMiddleware', 98 | 'django.middleware.security.SecurityMiddleware', 99 | 'whitenoise.middleware.WhiteNoiseMiddleware', 100 | 'django.contrib.sessions.middleware.SessionMiddleware', 101 | 'corsheaders.middleware.CorsMiddleware', 102 | 'django.middleware.common.CommonMiddleware', 103 | 'django.middleware.csrf.CsrfViewMiddleware', 104 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 105 | 'django.contrib.messages.middleware.MessageMiddleware', 106 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 107 | 'auditlog.middleware.AuditlogMiddleware', 108 | ] 109 | 110 | ROOT_URLCONF = 'core.urls' 111 | 112 | TEMPLATES = [ 113 | { 114 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 115 | 'DIRS': [], 116 | 'APP_DIRS': True, 117 | 'OPTIONS': { 118 | 'context_processors': [ 119 | 'django.template.context_processors.debug', 120 | 'django.template.context_processors.request', 121 | 'django.contrib.auth.context_processors.auth', 122 | 'django.contrib.messages.context_processors.messages', 123 | ], 124 | }, 125 | }, 126 | ] 127 | 128 | WSGI_APPLICATION = 'core.wsgi.application' 129 | 130 | 131 | # Database 132 | # https://docs.djangoproject.com/en/4.1/ref/settings/#databases 133 | 134 | DATABASE_ROUTERS = [ 135 | 'ms_auth_router.routers.DefaultRouter', 136 | ] 137 | 138 | ROUTE_APP_LABELS = ('authentication', ) 139 | 140 | AUTH_DB = 'default' 141 | 142 | DATABASES = { 143 | 'default': dj_database_url.config(default='sqlite:///db.sqlite3', conn_max_age=600) 144 | } 145 | 146 | if auth_db := os.getenv('AUTH_DB_URL'): 147 | AUTH_DB = 'auth_db' 148 | DATABASES['auth_db'] = dj_database_url.parse(auth_db) 149 | 150 | AUTH_USER_MODEL = 'authentication.User' 151 | 152 | # -----> Rest Framework 153 | REST_AUTH_TOKEN_MODEL = 'authentication.Token' 154 | 155 | REST_AUTH_TOKEN_TTL = os.getenv('DJANGO_REST_AUTH_TOKEN_TTL', 60 * 60 * 24) 156 | 157 | REST_AUTH_TOKEN_CREATOR = 'authentication.utils.create_token' 158 | 159 | REST_FRAMEWORK = { 160 | 'DEFAULT_AUTHENTICATION_CLASSES': [ 161 | 'rest_framework.authentication.SessionAuthentication', 162 | 'authentication.utils.ExpiringTokenAuthentication' 163 | ], 164 | 'DEFAULT_FILTER_BACKENDS': [ 165 | 'rest_framework.filters.SearchFilter', 166 | 'rest_framework.filters.OrderingFilter', 167 | 'django_filters.rest_framework.DjangoFilterBackend' 168 | ], 169 | 'DATETIME_FORMAT': "%Y-%m-%d %H:%M:%S", 170 | 'DEFAULT_PERMISSION_CLASSES': [ 171 | 'rest_framework.permissions.IsAuthenticated', 172 | ], 173 | 'DEFAULT_PAGINATION_CLASS': 'core.api.pagination.PageNumberPagination', 174 | 'PAGE_SIZE': 10 175 | } 176 | 177 | 178 | # Password validation 179 | # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators 180 | 181 | AUTH_PASSWORD_VALIDATORS = [ 182 | { 183 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 184 | }, 185 | { 186 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 187 | }, 188 | { 189 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 190 | }, 191 | { 192 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 193 | }, 194 | ] 195 | 196 | 197 | # Internationalization 198 | # https://docs.djangoproject.com/en/4.1/topics/i18n/ 199 | 200 | LANGUAGE_CODE = os.getenv('DJANGO_LANGUAGE_CODE', 'en-us') 201 | 202 | TIME_ZONE = os.getenv('DJANGO_TIME_ZONE', 'UTC') 203 | 204 | USE_I18N = True 205 | 206 | USE_TZ = True 207 | 208 | 209 | # Static files (CSS, JavaScript, Images) 210 | # https://docs.djangoproject.com/en/4.1/howto/static-files/ 211 | 212 | STATIC_URL = 'static/' 213 | 214 | STATIC_ROOT = BASE_DIR / 'static' 215 | 216 | STATICFILES_DIRS = [ 217 | BASE_DIR / 'assets' 218 | ] 219 | 220 | MEDIA_URL = 'media/' 221 | 222 | MEDIA_ROOT = BASE_DIR / 'media' 223 | 224 | 225 | # Default primary key field type 226 | # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field 227 | 228 | DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' 229 | 230 | 231 | # -----> RABBITMQ 232 | BROKER_URL = os.getenv('BROKER_URL', 'amqp://guest:guest@localhost:5672') 233 | 234 | 235 | # -----> CELERY 236 | CELERY_BROKER_URL = BROKER_URL 237 | CELERY_RESULT_BACKEND = 'django-db' 238 | CELERY_CACHE_BACKEND = 'django-cache' 239 | CELERY_ACCEPT_CONTENT = ['application/json'] 240 | CELERY_TASK_SERIALIZER = 'json' 241 | CELERY_RESULT_SERIALIZER = 'json' 242 | CELERY_TIMEZONE = TIME_ZONE 243 | CELERY_TASK_DEFAULT_QUEUE = 'default' 244 | 245 | 246 | # -----> SENTRY 247 | if SENTRY_DSN := os.getenv('SENTRY_DSN', None): 248 | 249 | SENTRY_ENVIRONMENT = os.getenv('SENTRY_ENVIRONMENT', 'development') 250 | environment = f'{APP_LABEL}-{SENTRY_ENVIRONMENT}' if APP_LABEL else SENTRY_ENVIRONMENT 251 | 252 | import sentry_sdk 253 | from sentry_sdk.integrations.celery import CeleryIntegration 254 | from sentry_sdk.integrations.django import DjangoIntegration 255 | 256 | sentry_sdk.init( 257 | dsn=SENTRY_DSN, 258 | integrations=[ 259 | DjangoIntegration(), CeleryIntegration() 260 | ], 261 | 262 | debug=DEBUG, 263 | 264 | # Set traces_sample_rate to 1.0 to capture 100% 265 | # of transactions for performance monitoring. 266 | # We recommend adjusting this value in production. 267 | traces_sample_rate=1.0, 268 | 269 | # If you wish to associate users to errors (assuming you are using 270 | # django.contrib.auth) you may enable sending PII data. 271 | send_default_pii=True, 272 | 273 | environment=environment 274 | ) 275 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------