diff --git a/.coverage b/.coverage new file mode 100644 index 0000000..fb898ca Binary files /dev/null and b/.coverage differ diff --git a/.flake8 b/.flake8 new file mode 100644 index 0000000..6296348 --- /dev/null +++ b/.flake8 @@ -0,0 +1,15 @@ +[flake8] +extend-ignore = E203 +include = + user/*.py, + group/*.py +exclude = + .git, + __pycache__, + docs/source/conf.py, + old, + build, + dist, + user/migrations/*, + group/migrations/* +max-complexity = 10 \ No newline at end of file diff --git a/.github/workflows/run_test.yml b/.github/workflows/run_test.yml new file mode 100644 index 0000000..fb942fd --- /dev/null +++ b/.github/workflows/run_test.yml @@ -0,0 +1,54 @@ +name: Lint, Test, and Generate Coverage report + +on: + pull_request: + branches: + - develop + - main + +jobs: + build: + runs-on: ubuntu-latest + strategy: + matrix: + version: ["3.9"] + services: + postgres: + image: postgres + env: + POSTGRES_PASSWORD: ${{ secrets.POSTGRES_PASSWORD }} + options: >- + --health-cmd pg_isready + --health-interval 10s + --health-timeout 5s + --health-retries 5 + ports: + - 5432:5432 + + steps: + - uses: actions/checkout@v3 + - name: Set up Python ${{ matrix.version }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.version }} + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install -r requirements.txt + - name: Lint with pylint and flake8 + run: | + pylint --ignore=migrations group + pylint --ignore=migrations user + flake8 group + flake8 user + - name: Test with pytest + env: + SECRET_KEY: ${{ secrets.SECRET_KEY }} + DB_NAME: ${{ secrets.DB_NAME }} + DB_USER: ${{ secrets.DB_USER }} + DB_PASSWORD: ${{ secrets.DB_PASSWORD }} + DB_HOST: ${{ secrets.DB_HOST }} + DB_PORT: ${{ secrets.DB_PORT }} + run: coverage run -m pytest -v -s + - name: Generate coverage report + run: coverage report -m diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..293a1a2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +__pycache__/ +.env +env/ \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..6ab5314 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,11 @@ +FROM python:3.9 + +WORKDIR /postit + +COPY requirements.txt . + +RUN pip install -r requirements.txt + +EXPOSE 8000 + +CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] diff --git a/Pipfile b/Pipfile new file mode 100644 index 0000000..8a20dc9 --- /dev/null +++ b/Pipfile @@ -0,0 +1,12 @@ +[[source]] +url = "https://pypi.org/simple" +verify_ssl = true +name = "pypi" + +[packages] +django = "*" + +[dev-packages] + +[requires] +python_version = "3.7" diff --git a/Pipfile.lock b/Pipfile.lock new file mode 100644 index 0000000..a7d5466 --- /dev/null +++ b/Pipfile.lock @@ -0,0 +1,54 @@ +{ + "_meta": { + "hash": { + "sha256": "627ef89f247ecee27e9ef0dabe116108d09c47abf171c900a8817befa64f9dd2" + }, + "pipfile-spec": 6, + "requires": { + "python_version": "3.7" + }, + "sources": [ + { + "name": "pypi", + "url": "https://pypi.org/simple", + "verify_ssl": true + } + ] + }, + "default": { + "asgiref": { + "hashes": [ + "sha256:89b2ef2247e3b562a16eef663bc0e2e703ec6468e2fa8a5cd61cd449786d4f6e", + "sha256:9e0ce3aa93a819ba5b45120216b23878cf6e8525eb3848653452b4192b92afed" + ], + "markers": "python_version >= '3.7'", + "version": "==3.7.2" + }, + "django": { + "hashes": [ + "sha256:08f41f468b63335aea0d904c5729e0250300f6a1907bf293a65499496cdbc68f", + "sha256:a64d2487cdb00ad7461434320ccc38e60af9c404773a2f95ab0093b4453a3215" + ], + "index": "pypi", + "markers": "python_version >= '3.8'", + "version": "==4.2.6" + }, + "sqlparse": { + "hashes": [ + "sha256:5430a4fe2ac7d0f93e66f1efc6e1338a41884b7ddf2a350cedd20ccc4d9d28f3", + "sha256:d446183e84b8349fa3061f0fe7f06ca94ba65b426946ffebe6e3e8295332420c" + ], + "markers": "python_version >= '3.5'", + "version": "==0.4.4" + }, + "typing-extensions": { + "hashes": [ + "sha256:8f92fc8806f9a6b641eaa5318da32b44d401efaac0f6678c9bc448ba3605faa0", + "sha256:df8e4339e9cb77357558cbdbceca33c303714cf861d1eef15e1070055ae8b7ef" + ], + "markers": "python_version < '3.11'", + "version": "==4.8.0" + } + }, + "develop": {} +} diff --git a/README.md b/README.md index 9ac3357..7064397 100644 --- a/README.md +++ b/README.md @@ -1 +1,55 @@ # post-it-backend + +PostIt ​is a simple application that allows friends and colleagues to create groups for notifications. This way one person can post notifications to everyone by sending a message once. The application allows people to create accounts, create groups add registered users to the groups, and then send messages to these groups whenever they want. + +# Project Setup + +1. After cloning the repo, set up a virtual environment + `python3 -m venv .venv` + +2. Activate the virtual environment + `. .venv/bin/activate` + +3. Install the dependencies in requirements.txt + `pip install -r requirements.txt` + +4. Configure PostgresSQL + i) Open the PostgresSQL command line interface + `psql postgres` + + ii) From your terminal, create a database + `CREATE DATABASE postit;` + + iii) Create a user, feel free to replace the username and password + `CREATE USER admin WITH PASSWORD 'password';` + + iv) Modify the connection parameters for the created user + `ALTER ROLE admin SET client_encoding TO 'utf8';` + `ALTER ROLE admin SET default_transaction_isolation TO 'read committed';` + `ALTER ROLE admin SET timezone TO 'UTC';` + + v) Grant the user access rights to the database + `GRANT ALL PRIVILEGES ON DATABASE postit TO admin;` + + vi) Exit the postgres command line + `\q` + +5. Create a .env file at the root of the project and set the database configurations there + `SECRET_KEY=your_secret_key` + `DB_NAME=postit` + `DB_USER=admin` + `DB_PASSWORD=your_password` + `DB_HOST=localhost` + `DB_PORT=5432` + +6. Make migrations + `python manage.py makemigrations` + +7. Migrate to create tables + `python manage.py migrate` + +8. Create a superuser + `python manage.py createsuperuser` + +9. Start the server + `python manage.py runserver` diff --git a/api/__init__.py b/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/api/admin.py b/api/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/api/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/api/apps.py b/api/apps.py new file mode 100644 index 0000000..66656fd --- /dev/null +++ b/api/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class ApiConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'api' diff --git a/api/migrations/__init__.py b/api/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/api/models.py b/api/models.py new file mode 100644 index 0000000..71a8362 --- /dev/null +++ b/api/models.py @@ -0,0 +1,3 @@ +from django.db import models + +# Create your models here. diff --git a/api/tests.py b/api/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/api/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/api/urls.py b/api/urls.py new file mode 100644 index 0000000..3e4aaf1 --- /dev/null +++ b/api/urls.py @@ -0,0 +1,6 @@ +from django.urls import path, include + +urlpatterns = [ + path('users/', include('user.urls')), + path('groups/', include('group.urls')), +] \ No newline at end of file diff --git a/api/views.py b/api/views.py new file mode 100644 index 0000000..91ea44a --- /dev/null +++ b/api/views.py @@ -0,0 +1,3 @@ +from django.shortcuts import render + +# Create your views here. diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml new file mode 100644 index 0000000..b3535b7 --- /dev/null +++ b/docker-compose.dev.yml @@ -0,0 +1,26 @@ +services: + db: + image: postgres + environment: + - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} + env_file: + - .env + web: + build: . + command: python manage.py runserver 0.0.0.0:8000 + volumes: + - .:/postit + ports: + - "8000:8000" + depends_on: + - db + environment: + - SECRET_KEY=${SECRET_KEY} + - DB_NAME=${DB_NAME} + - DB_USER=${DB_USER} + - DB_PASSWORD=${DB_PASSWORD} + - DB_HOST=${DB_HOST} + - DB_PORT=${DB_PORT} + env_file: + - .env + tty: true diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..0276063 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,22 @@ +services: + db: + image: postgres + environment: + - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} + web: + build: . + command: python manage.py runserver 0.0.0.0:8000 + volumes: + - .:/postit + ports: + - "8000:8000" + depends_on: + - db + environment: + - SECRET_KEY=${SECRET_KEY} + - DB_NAME=${DB_NAME} + - DB_USER=${DB_USER} + - DB_PASSWORD=${DB_PASSWORD} + - DB_HOST=${DB_HOST} + - DB_PORT=${DB_PORT} + tty: true diff --git a/group/__init__.py b/group/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/group/admin.py b/group/admin.py new file mode 100644 index 0000000..5227c5b --- /dev/null +++ b/group/admin.py @@ -0,0 +1,6 @@ +"""Register the Group model to see it in Django admin""" +from django.contrib import admin +from .models import Group, Message + +admin.site.register(Group) +admin.site.register(Message) diff --git a/group/apps.py b/group/apps.py new file mode 100644 index 0000000..8b5d385 --- /dev/null +++ b/group/apps.py @@ -0,0 +1,8 @@ +"""Apps module""" +from django.apps import AppConfig + + +class GroupConfig(AppConfig): + """App class configuration""" + default_auto_field = 'django.db.models.BigAutoField' + name = 'group' diff --git a/group/migrations/0001_initial.py b/group/migrations/0001_initial.py new file mode 100644 index 0000000..a84afd8 --- /dev/null +++ b/group/migrations/0001_initial.py @@ -0,0 +1,26 @@ +# Generated by Django 4.2.6 on 2023-10-30 08:26 + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='Group', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=255, unique=True)), + ('creator', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='groups_created', to=settings.AUTH_USER_MODEL)), + ('members', models.ManyToManyField(related_name='groups_joined', to=settings.AUTH_USER_MODEL)), + ], + ), + ] diff --git a/group/migrations/0002_message.py b/group/migrations/0002_message.py new file mode 100644 index 0000000..d484adf --- /dev/null +++ b/group/migrations/0002_message.py @@ -0,0 +1,26 @@ +# Generated by Django 4.2.6 on 2023-11-02 09:41 + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('group', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='Message', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('post', models.TextField()), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='messages', to='group.group')), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='messages_authored', to=settings.AUTH_USER_MODEL)), + ], + ), + ] diff --git a/group/migrations/__init__.py b/group/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/group/models.py b/group/models.py new file mode 100644 index 0000000..bc056ac --- /dev/null +++ b/group/models.py @@ -0,0 +1,27 @@ +"""Models module""" +from django.db import models +from django.contrib.auth.models import User + + +class Group(models.Model): + """Group class model""" + name = models.CharField(max_length=255, unique=True) + members = models.ManyToManyField(User, related_name='groups_joined') + creator = models.ForeignKey(User, on_delete=models.CASCADE, + related_name='groups_created') + + def __str__(self) -> str: + return str(self.name) + + +class Message(models.Model): + """A model to define the structure of messages""" + post = models.TextField() + group = models.ForeignKey(Group, on_delete=models.CASCADE, + related_name='messages') + user = models.ForeignKey(User, on_delete=models.CASCADE, + related_name='messages_authored') + created_at = models.DateTimeField(auto_now_add=True) + + def __str__(self): + return f'{self.user.username}: {self.post}' diff --git a/group/serializers.py b/group/serializers.py new file mode 100644 index 0000000..a999a1b --- /dev/null +++ b/group/serializers.py @@ -0,0 +1,37 @@ +"""Serializer module""" +from rest_framework import serializers +from django.contrib.auth.models import User +from user.serializers import UserSerializer +from .models import Group, Message + + +class GroupSerializer(serializers.ModelSerializer): + """Group serializer class""" + + class Meta: + """Serializer Meta class""" + model = Group + fields = ['id', 'name', 'members', 'creator'] + + def to_representation(self, instance): + representation = super().to_representation(instance) + representation['members'] = UserSerializer( + instance.members, many=True).data + return representation + + def update(self, instance, validated_data): + new_members = validated_data.get("members") + + member_objects = User.objects.filter( + id__in=[member.id for member in new_members]) + instance.members.add(*member_objects) + instance.save() + return instance + + +class MessageSerializer(serializers.ModelSerializer): + """Message serializer class""" + class Meta: + """Message serializer Meta class""" + model = Message + fields = ['id', 'post', 'group', 'user', 'created_at'] diff --git a/group/tests.py b/group/tests.py new file mode 100644 index 0000000..a39b155 --- /dev/null +++ b/group/tests.py @@ -0,0 +1 @@ +# Create your tests here. diff --git a/group/urls.py b/group/urls.py new file mode 100644 index 0000000..807b02d --- /dev/null +++ b/group/urls.py @@ -0,0 +1,17 @@ +"""urls module""" +from django.urls import path +from .views import\ + GroupApiView, \ + GroupDetailApiView, \ + MessageAPIView, \ + MessageDetailAPIView + +urlpatterns = [ + path('', GroupApiView.as_view(), name='group'), + path('/', GroupApiView.as_view()), + path('detail//', GroupDetailApiView.as_view(), name='group'), + path('users//', GroupDetailApiView.as_view(), name='group'), + path('messages', MessageAPIView.as_view()), + path('/messages//', + MessageDetailAPIView.as_view()), +] diff --git a/group/views.py b/group/views.py new file mode 100644 index 0000000..6899d08 --- /dev/null +++ b/group/views.py @@ -0,0 +1,211 @@ +"""views module""" +from rest_framework.views import APIView +from rest_framework import permissions +from rest_framework.exceptions import PermissionDenied +from rest_framework.response import Response +from rest_framework import status +from rest_framework.generics import ListAPIView +from rest_framework.pagination import PageNumberPagination + +from django.contrib.auth.models import User +from django.http import Http404 + + +from .models import Group, Message +from .serializers import GroupSerializer, MessageSerializer + + +class GroupApiView(ListAPIView): + """Define methods for performing actions on groups""" + permission_classes = [permissions.IsAuthenticated] + queryset = Group.objects.all() + serializer_class = GroupSerializer + pagination_class = PageNumberPagination + + def get_object(self, request=None, group_id=None): + """Check for user permission and group existence""" + try: + if request and group_id is not None: + group = Group.objects.get(id=group_id) + if request.user != group.creator: + raise PermissionDenied("Access Denied") + return group + except Group.DoesNotExist as exc: + raise Http404 from exc + + def get(self, request, *args, **kwargs): + """Retrieve a list of all the groups""" + queryset = self.get_queryset().order_by('id') + page = self.paginate_queryset(queryset) + if page is not None: + serializer = self.serializer_class(page, many=True) + return self.get_paginated_response(serializer.data) + serializer = self.serializer_class(queryset, many=True) + return Response(serializer.data, status=status.HTTP_200_OK) + + def post(self, request): + """Create a group""" + data = request.data.copy() + user_id = request.user.id + data['creator'] = user_id + data['members'] = [user_id] + serializer = GroupSerializer(data=data) + if serializer.is_valid(): + serializer.save() + return Response(serializer.data, status=status.HTTP_201_CREATED) + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + + def patch(self, request): + """Update members list""" + data = request.data + group_id = data.get("group_id") + members_ids = data.get("members") + + data.pop('creator', None) + data.pop('name', None) + try: + group = self.get_object(request, group_id) + errors = [] + for member in members_ids: + try: + user = User.objects.get(id=member) + group.members.add(user) + except User.DoesNotExist: + errors.append(f"User with ID {member} is not found") + serializer = GroupSerializer(group, data=data, partial=True) + if serializer.is_valid(): + serializer.save() + return Response(serializer.data, status=status.HTTP_200_OK) + if errors: + return Response({"error": errors}, + status=status.HTTP_400_BAD_REQUEST) + return Response(serializer.errors, + status=status.HTTP_400_BAD_REQUEST) + except PermissionDenied: + return Response({"error": "Only group creator can add members"}, + status=status.HTTP_403_FORBIDDEN) + except Http404: + return Response({"error": "Group not found"}, + status=status.HTTP_404_NOT_FOUND) + + def delete(self, request, group_id): + """Delete a group""" + try: + group = self.get_object(request, group_id) + group.delete() + return Response({"message": "Group deleted successfully"}, + status=status.HTTP_204_NO_CONTENT) + except PermissionDenied: + return Response({"error": "Only the group creator can delete"}, + status=status.HTTP_403_FORBIDDEN) + except Http404: + return Response({"error": "Group not found"}, + status=status.HTTP_404_NOT_FOUND) + + +class GroupDetailApiView(APIView): + """ + Define methods for performing detail and more specific actions on groups + """ + permission_classes = [permissions.IsAuthenticated] + + def get(self, request, group_id): + """Retrieve a single group""" + try: + group = Group.objects.get(id=group_id) + serializer = GroupSerializer(group) + return Response(serializer.data, status=status.HTTP_200_OK) + except Group.DoesNotExist: + return Response({"error": "Group not found"}, + status=status.HTTP_404_NOT_FOUND) + + def delete(self, request, user_id): + """Delete/Remove a user from a specific group""" + group_id = request.data.get("group_id") + try: + group = Group.objects.get(id=group_id) + if request.user != group.creator: + return Response({ + "error": + "Only group creator can remove members"}) + user = User.objects.get(id=user_id) + if user.id == group.creator.id: + return Response( + {"error": "Cannot remove creator from the group"}, + status=status.HTTP_403_FORBIDDEN) + if user.id not in group.members.all().values_list('id', + flat=True): + return Response( + {"error": f"User with ID {user_id} not in this group"}) + group.members.remove(user) + return Response({"message": + f"User with ID {user_id} successfully removed"}, + status=status.HTTP_204_NO_CONTENT) + except User.DoesNotExist: + return Response({"error": f"User with ID {user_id} not found"}, + status=status.HTTP_404_NOT_FOUND) + except Group.DoesNotExist: + return Response({"error": "Group not found"}, + status=status.HTTP_404_NOT_FOUND) + + +class MessageAPIView(APIView): + """Define methods for messaging within the group""" + permission_classes = [permissions.IsAuthenticated] + + def post(self, request, *args, **kwargs): + """Post message to a group""" + data = request.data + group_id = data.get("group_id") + post = data.get("post") + try: + group = Group.objects.select_related("creator").get(id=group_id) + user = request.user + except Group.DoesNotExist: + return Response({"error": "Group not found"}, + status=status.HTTP_404_NOT_FOUND) + except User.DoesNotExist: + return Response({"error": "User not found"}, + status=status.HTTP_404_NOT_FOUND) + if user.id in group.members.all().values_list("id", flat=True): + data = { + "post": post, + "group": group.id, + "user": user.id, + } + + serializer = MessageSerializer(data=data) + if serializer.is_valid(): + serializer.save() + return Response(serializer.data, status=status.HTTP_200_OK) + return Response(serializer.errors, + status=status.HTTP_400_BAD_REQUEST) + return Response({"error": "User is not a member of this group"}, + status=status.HTTP_403_FORBIDDEN) + + +class MessageDetailAPIView(APIView): + """Define methods for messaging within the group""" + permission_classes = [permissions.IsAuthenticated] + + def get(self, request, *args, **kwargs): + """Retrieve all messages in a group""" + group_id = kwargs.get("group_id") + user_id = kwargs.get("user_id") + try: + group = Group.objects.select_related("creator").get(id=group_id) + user = User.objects.select_related("auth_token").get(id=user_id) + except Group.DoesNotExist: + return Response({"error": "Group not found"}, + status=status.HTTP_404_NOT_FOUND) + except User.DoesNotExist: + return Response({"error": "User not found"}, + status=status.HTTP_404_NOT_FOUND) + + if user.id in group.members.all().values_list("id", flat=True): + messages = Message.objects.filter(group=group) + + serializer = MessageSerializer(messages, many=True) + return Response(serializer.data, status=status.HTTP_200_OK) + return Response({"error": "User is not a member of this group"}, + status=status.HTTP_403_FORBIDDEN) diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..94360fe --- /dev/null +++ b/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + """Run administrative tasks.""" + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'post_it_backend.settings') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == '__main__': + main() diff --git a/post_it_backend/__init__.py b/post_it_backend/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/post_it_backend/asgi.py b/post_it_backend/asgi.py new file mode 100644 index 0000000..29fce65 --- /dev/null +++ b/post_it_backend/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for post_it_backend project. + +It exposes the ASGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'post_it_backend.settings') + +application = get_asgi_application() diff --git a/post_it_backend/settings.py b/post_it_backend/settings.py new file mode 100644 index 0000000..c7c7f01 --- /dev/null +++ b/post_it_backend/settings.py @@ -0,0 +1,152 @@ +""" +Django settings for post_it_backend project. + +Generated by 'django-admin startproject' using Django 4.2.6. + +For more information on this file, see +https://docs.djangoproject.com/en/4.2/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/4.2/ref/settings/ +""" + +import environ +import os + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + +env = environ.Env() + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = env('SECRET_KEY') + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = ['localhost', '127.0.0.1',] + + +# Application definition + +INSTALLED_APPS = [ + # My apps + 'user', + 'api', + 'group', + + # Django apps + 'rest_framework.authtoken', + 'rest_framework', + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + 'drf_yasg', +] + +REST_FRAMEWORK = { + 'DEFAULT_PERMISSION_CLASSES': [ + 'rest_framework.permissions.AllowAny' + ], + 'DEFAULT_AUTHENTICATION_CLASSES': [ + 'rest_framework.authentication.TokenAuthentication', + ], + 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', + 'PAGE_SIZE': 10 +} + +MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', +] + +ROOT_URLCONF = 'post_it_backend.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'post_it_backend.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/4.2/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.postgresql', + 'NAME': env('DB_NAME'), + 'USER': env('DB_USER'), + 'PASSWORD': env('DB_PASSWORD'), + 'HOST': env('DB_HOST'), + 'PORT': env('DB_PORT'), + 'TEST': { + 'NAME': 'test_postgres' + } + } +} + + +# Password validation +# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/4.2/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/4.2/howto/static-files/ + +STATIC_URL = 'static/' + +# Default primary key field type +# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' diff --git a/post_it_backend/urls.py b/post_it_backend/urls.py new file mode 100644 index 0000000..64c0b71 --- /dev/null +++ b/post_it_backend/urls.py @@ -0,0 +1,45 @@ +""" +URL configuration for post_it_backend project. + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/4.2/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.urls import include, path + 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) +""" +from django.contrib import admin +from django.urls import path, include +from drf_yasg.views import get_schema_view +from drf_yasg import openapi +from rest_framework import permissions + + +schema_view = get_schema_view( + openapi.Info( + title='POST IT APIs', + default_version='v1', + description='API documentation', + terms_of_service='', + contact=openapi.Contact(email=''), + license=openapi.License(name='BSD Licence'), + ), + public=True, + permission_classes=(permissions.AllowAny,), +) + +urlpatterns = [ + path('admin/', admin.site.urls), + path('api/', include('api.urls')), + + #DRF URLs + path('documentation/', schema_view.without_ui(cache_timeout=0), name='schema-json'), + path('documentation/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), + path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc') +] diff --git a/post_it_backend/wsgi.py b/post_it_backend/wsgi.py new file mode 100644 index 0000000..b0d9ada --- /dev/null +++ b/post_it_backend/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for post_it_backend project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'post_it_backend.settings') + +application = get_wsgi_application() diff --git a/pylintrc b/pylintrc new file mode 100644 index 0000000..6777ccb --- /dev/null +++ b/pylintrc @@ -0,0 +1,638 @@ +[MAIN] + +# Analyse import fallback blocks. This can be used to support both Python 2 and +# 3 compatible code, which means that the block might have code that exists +# only in one or another interpreter, leading to false positives when analysed. +analyse-fallback-blocks=no + +# Clear in-memory caches upon conclusion of linting. Useful if running pylint +# in a server-like mode. +clear-cache-post-run=no + +# Load and enable all available extensions. Use --list-extensions to see a list +# all available extensions. +#enable-all-extensions= + +# In error mode, messages with a category besides ERROR or FATAL are +# suppressed, and no reports are done by default. Error mode is compatible with +# disabling specific errors. +#errors-only= + +# Always return a 0 (non-error) status code, even if lint errors are found. +# This is primarily useful in continuous integration scripts. +#exit-zero= + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. +extension-pkg-allow-list= + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. (This is an alternative name to extension-pkg-allow-list +# for backward compatibility.) +extension-pkg-whitelist= + +# Return non-zero exit code if any of these messages/categories are detected, +# even if score is above --fail-under value. Syntax same as enable. Messages +# specified are enabled, while categories only check already-enabled messages. +fail-on= + +# Specify a score threshold under which the program will exit with error. +fail-under=10 + +# Interpret the stdin as a python script, whose filename needs to be passed as +# the module_or_package argument. +#from-stdin= + +# Files or directories to be skipped. They should be base names, not paths. +ignore=CVS + +# Add files or directories matching the regular expressions patterns to the +# ignore-list. The regex matches against paths and can be in Posix or Windows +# format. Because '\\' represents the directory delimiter on Windows systems, +# it can't be used as an escape character. +ignore-paths= + +# Files or directories matching the regular expression patterns are skipped. +# The regex matches against base names, not paths. The default value ignores +# Emacs file locks +ignore-patterns=^\.# + +# List of module names for which member attributes should not be checked +# (useful for modules/projects where namespaces are manipulated during runtime +# and thus existing member attributes cannot be deduced by static analysis). It +# supports qualified module names, as well as Unix pattern matching. +ignored-modules= + +# Python code to execute, usually for sys.path manipulation such as +# pygtk.require(). +#init-hook= + +# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the +# number of processors available to use, and will cap the count on Windows to +# avoid hangs. +jobs=1 + +# Control the amount of potential inferred values when inferring a single +# object. This can help the performance when dealing with large functions or +# complex, nested conditions. +limit-inference-results=100 + +# List of plugins (as comma separated values of python module names) to load, +# usually to register additional checkers. +load-plugins= + +# Pickle collected data for later comparisons. +persistent=yes + +# Minimum Python version to use for version dependent checks. Will default to +# the version used to run pylint. +py-version=3.10 + +# Discover python modules and packages in the file system subtree. +recursive=no + +# Add paths to the list of the source roots. Supports globbing patterns. The +# source root is an absolute path or a path relative to the current working +# directory used to determine a package namespace for modules located under the +# source root. +source-roots= + +# When enabled, pylint would attempt to guess common misconfiguration and emit +# user-friendly hints instead of false-positive error messages. +suggestion-mode=yes + +# Allow loading of arbitrary C extensions. Extensions are imported into the +# active Python interpreter and may run arbitrary code. +unsafe-load-any-extension=no + +# In verbose mode, extra non-checker-related info will be displayed. +#verbose= + + +[BASIC] + +# Naming style matching correct argument names. +argument-naming-style=snake_case + +# Regular expression matching correct argument names. Overrides argument- +# naming-style. If left empty, argument names will be checked with the set +# naming style. +#argument-rgx= + +# Naming style matching correct attribute names. +attr-naming-style=snake_case + +# Regular expression matching correct attribute names. Overrides attr-naming- +# style. If left empty, attribute names will be checked with the set naming +# style. +#attr-rgx= + +# Bad variable names which should always be refused, separated by a comma. +bad-names=foo, + bar, + baz, + toto, + tutu, + tata + +# Bad variable names regexes, separated by a comma. If names match any regex, +# they will always be refused +bad-names-rgxs= + +# Naming style matching correct class attribute names. +class-attribute-naming-style=any + +# Regular expression matching correct class attribute names. Overrides class- +# attribute-naming-style. If left empty, class attribute names will be checked +# with the set naming style. +#class-attribute-rgx= + +# Naming style matching correct class constant names. +class-const-naming-style=UPPER_CASE + +# Regular expression matching correct class constant names. Overrides class- +# const-naming-style. If left empty, class constant names will be checked with +# the set naming style. +#class-const-rgx= + +# Naming style matching correct class names. +class-naming-style=PascalCase + +# Regular expression matching correct class names. Overrides class-naming- +# style. If left empty, class names will be checked with the set naming style. +#class-rgx= + +# Naming style matching correct constant names. +const-naming-style=UPPER_CASE + +# Regular expression matching correct constant names. Overrides const-naming- +# style. If left empty, constant names will be checked with the set naming +# style. +#const-rgx= + +# Minimum line length for functions/classes that require docstrings, shorter +# ones are exempt. +docstring-min-length=-1 + +# Naming style matching correct function names. +function-naming-style=snake_case + +# Regular expression matching correct function names. Overrides function- +# naming-style. If left empty, function names will be checked with the set +# naming style. +#function-rgx= + +# Good variable names which should always be accepted, separated by a comma. +good-names=i, + j, + k, + ex, + Run, + _ + +# Good variable names regexes, separated by a comma. If names match any regex, +# they will always be accepted +good-names-rgxs= + +# Include a hint for the correct naming format with invalid-name. +include-naming-hint=no + +# Naming style matching correct inline iteration names. +inlinevar-naming-style=any + +# Regular expression matching correct inline iteration names. Overrides +# inlinevar-naming-style. If left empty, inline iteration names will be checked +# with the set naming style. +#inlinevar-rgx= + +# Naming style matching correct method names. +method-naming-style=snake_case + +# Regular expression matching correct method names. Overrides method-naming- +# style. If left empty, method names will be checked with the set naming style. +#method-rgx= + +# Naming style matching correct module names. +module-naming-style=snake_case + +# Regular expression matching correct module names. Overrides module-naming- +# style. If left empty, module names will be checked with the set naming style. +#module-rgx= + +# Colon-delimited sets of names that determine each other's naming style when +# the name regexes allow several styles. +name-group= + +# Regular expression which should only match function or class names that do +# not require a docstring. +no-docstring-rgx=^_ + +# List of decorators that produce properties, such as abc.abstractproperty. Add +# to this list to register other decorators that produce valid properties. +# These decorators are taken in consideration only for invalid-name. +property-classes=abc.abstractproperty + +# Regular expression matching correct type alias names. If left empty, type +# alias names will be checked with the set naming style. +#typealias-rgx= + +# Regular expression matching correct type variable names. If left empty, type +# variable names will be checked with the set naming style. +#typevar-rgx= + +# Naming style matching correct variable names. +variable-naming-style=snake_case + +# Regular expression matching correct variable names. Overrides variable- +# naming-style. If left empty, variable names will be checked with the set +# naming style. +#variable-rgx= + + +[CLASSES] + +# Warn about protected attribute access inside special methods +check-protected-access-in-special-methods=no + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__, + __new__, + setUp, + asyncSetUp, + __post_init__ + +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected=_asdict,_fields,_replace,_source,_make,os._exit + +# List of valid names for the first argument in a class method. +valid-classmethod-first-arg=cls + +# List of valid names for the first argument in a metaclass class method. +valid-metaclass-classmethod-first-arg=mcs + + +[DESIGN] + +# List of regular expressions of class ancestor names to ignore when counting +# public methods (see R0903) +exclude-too-few-public-methods= + +# List of qualified class names to ignore when counting class parents (see +# R0901) +ignored-parents= + +# Maximum number of arguments for function / method. +max-args=5 + +# Maximum number of attributes for a class (see R0902). +max-attributes=7 + +# Maximum number of boolean expressions in an if statement (see R0916). +max-bool-expr=5 + +# Maximum number of branch for function / method body. +max-branches=12 + +# Maximum number of locals for function / method body. +max-locals=15 + +# Maximum number of parents for a class (see R0901). +max-parents=7 + +# Maximum number of public methods for a class (see R0904). +max-public-methods=20 + +# Maximum number of return / yield for function / method body. +max-returns=6 + +# Maximum number of statements in function / method body. +max-statements=50 + +# Minimum number of public methods for a class (see R0903). +min-public-methods=2 + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when caught. +overgeneral-exceptions=builtins.BaseException,builtins.Exception + + +[FORMAT] + +# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. +expected-line-ending-format= + +# Regexp for a line that is allowed to be longer than the limit. +ignore-long-lines=^\s*(# )??$ + +# Number of spaces of indent required inside a hanging or continued line. +indent-after-paren=4 + +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string=' ' + +# Maximum number of characters on a single line. +max-line-length=100 + +# Maximum number of lines in a module. +max-module-lines=1000 + +# Allow the body of a class to be on the same line as the declaration if body +# contains single statement. +single-line-class-stmt=no + +# Allow the body of an if to be on the same line as the test if there is no +# else. +single-line-if-stmt=no + + +[IMPORTS] + +# List of modules that can be imported at any level, not just the top level +# one. +allow-any-import-level= + +# Allow explicit reexports by alias from a package __init__. +allow-reexport-from-package=no + +# Allow wildcard imports from modules that define __all__. +allow-wildcard-with-all=no + +# Deprecated modules which should not be used, separated by a comma. +deprecated-modules= + +# Output a graph (.gv or any supported image format) of external dependencies +# to the given file (report RP0402 must not be disabled). +ext-import-graph= + +# Output a graph (.gv or any supported image format) of all (i.e. internal and +# external) dependencies to the given file (report RP0402 must not be +# disabled). +import-graph= + +# Output a graph (.gv or any supported image format) of internal dependencies +# to the given file (report RP0402 must not be disabled). +int-import-graph= + +# Force import order to recognize a module as part of the standard +# compatibility libraries. +known-standard-library= + +# Force import order to recognize a module as part of a third party library. +known-third-party=enchant + +# Couples of modules and preferred modules, separated by a comma. +preferred-modules= + + +[LOGGING] + +# The type of string formatting that logging methods do. `old` means using % +# formatting, `new` is for `{}` formatting. +logging-format-style=old + +# Logging modules to check that the string format arguments are in logging +# function parameter format. +logging-modules=logging + + +[MESSAGES CONTROL] + +# Only show warnings with the listed confidence levels. Leave empty to show +# all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE, +# UNDEFINED. +confidence=HIGH, + CONTROL_FLOW, + INFERENCE, + INFERENCE_FAILURE, + UNDEFINED + +# Disable the message, report, category or checker with the given id(s). You +# can either give multiple identifiers separated by comma (,) or put this +# option multiple times (only on the command line, not in the configuration +# file where it should appear only once). You can also use "--disable=all" to +# disable everything first and then re-enable specific checks. For example, if +# you want to run only the similarities checker, you can use "--disable=all +# --enable=similarities". If you want to run only the classes checker, but have +# no Warning level messages displayed, use "--disable=all --enable=classes +# --disable=W". +disable=unused-argument, + too-many-return-statements, + no-member, + too-few-public-methods, + raw-checker-failed, + bad-inline-option, + locally-disabled, + file-ignored, + suppressed-message, + useless-suppression, + deprecated-pragma, + use-symbolic-message-instead, + use-implicit-booleaness-not-comparison-to-string, + use-implicit-booleaness-not-comparison-to-zero + +# Enable the message, report, category or checker with the given id(s). You can +# either give multiple identifier separated by comma (,) or put this option +# multiple time (only on the command line, not in the configuration file where +# it should appear only once). See also the "--disable" option for examples. +enable= + + +[METHOD_ARGS] + +# List of qualified names (i.e., library.method) which require a timeout +# parameter e.g. 'requests.api.get,requests.api.post' +timeout-methods=requests.api.delete,requests.api.get,requests.api.head,requests.api.options,requests.api.patch,requests.api.post,requests.api.put,requests.api.request + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME, + XXX, + TODO + +# Regular expression of note tags to take in consideration. +notes-rgx= + + +[REFACTORING] + +# Maximum number of nested blocks for function / method body +max-nested-blocks=5 + +# Complete name of functions that never returns. When checking for +# inconsistent-return-statements if a never returning function is called then +# it will be considered as an explicit return statement and no message will be +# printed. +never-returning-functions=sys.exit,argparse.parse_error + + +[REPORTS] + +# Python expression which should return a score less than or equal to 10. You +# have access to the variables 'fatal', 'error', 'warning', 'refactor', +# 'convention', and 'info' which contain the number of messages in each +# category, as well as 'statement' which is the total number of statements +# analyzed. This score is used by the global evaluation report (RP0004). +evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)) + +# Template used to display messages. This is a python new-style format string +# used to format the message information. See doc for all details. +msg-template= + +# Set the output format. Available formats are: text, parseable, colorized, +# json2 (improved json format), json (old json format) and msvs (visual +# studio). You can also give a reporter class, e.g. +# mypackage.mymodule.MyReporterClass. +#output-format= + +# Tells whether to display a full report or only the messages. +reports=no + +# Activate the evaluation score. +score=yes + + +[SIMILARITIES] + +# Comments are removed from the similarity computation +ignore-comments=yes + +# Docstrings are removed from the similarity computation +ignore-docstrings=yes + +# Imports are removed from the similarity computation +ignore-imports=yes + +# Signatures are removed from the similarity computation +ignore-signatures=yes + +# Minimum lines number of a similarity. +min-similarity-lines=4 + + +[SPELLING] + +# Limits count of emitted suggestions for spelling mistakes. +max-spelling-suggestions=4 + +# Spelling dictionary name. No available dictionaries : You need to install +# both the python package and the system dependency for enchant to work. +spelling-dict= + +# List of comma separated words that should be considered directives if they +# appear at the beginning of a comment and should not be checked. +spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy: + +# List of comma separated words that should not be checked. +spelling-ignore-words= + +# A path to a file that contains the private dictionary; one word per line. +spelling-private-dict-file= + +# Tells whether to store unknown words to the private dictionary (see the +# --spelling-private-dict-file option) instead of raising a message. +spelling-store-unknown-words=no + + +[STRING] + +# This flag controls whether inconsistent-quotes generates a warning when the +# character used as a quote delimiter is used inconsistently within a module. +check-quote-consistency=no + +# This flag controls whether the implicit-str-concat should generate a warning +# on implicit string concatenation in sequences defined over several lines. +check-str-concat-over-line-jumps=no + + +[TYPECHECK] + +# List of decorators that produce context managers, such as +# contextlib.contextmanager. Add to this list to register other decorators that +# produce valid context managers. +contextmanager-decorators=contextlib.contextmanager + +# List of members which are set dynamically and missed by pylint inference +# system, and so shouldn't trigger E1101 when accessed. Python regular +# expressions are accepted. +generated-members= + +# Tells whether to warn about missing members when the owner of the attribute +# is inferred to be None. +ignore-none=yes + +# This flag controls whether pylint should warn about no-member and similar +# checks whenever an opaque object is returned when inferring. The inference +# can return multiple potential results while evaluating a Python object, but +# some branches might not be evaluated, which results in partial inference. In +# that case, it might be useful to still emit no-member and other checks for +# the rest of the inferred objects. +ignore-on-opaque-inference=yes + +# List of symbolic message names to ignore for Mixin members. +ignored-checks-for-mixins=no-member, + not-async-context-manager, + not-context-manager, + attribute-defined-outside-init + +# List of class names for which member attributes should not be checked (useful +# for classes with dynamically set attributes). This supports the use of +# qualified names. +ignored-classes=optparse.Values,thread._local,_thread._local,argparse.Namespace + +# Show a hint with possible names when a member name was not found. The aspect +# of finding the hint is based on edit distance. +missing-member-hint=yes + +# The minimum edit distance a name should have in order to be considered a +# similar match for a missing member name. +missing-member-hint-distance=1 + +# The total number of similar names that should be taken in consideration when +# showing a hint for a missing member. +missing-member-max-choices=1 + +# Regex pattern to define which classes are considered mixins. +mixin-class-rgx=.*[Mm]ixin + +# List of decorators that change the signature of a decorated function. +signature-mutators= + + +[VARIABLES] + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid defining new builtins when possible. +additional-builtins= + +# Tells whether unused global variables should be treated as a violation. +allow-global-unused-variables=yes + +# List of names allowed to shadow builtins +allowed-redefined-builtins= + +# List of strings which can identify a callback function by name. A callback +# name must start or end with one of those strings. +callbacks=cb_, + _cb + +# A regular expression matching the name of dummy variables (i.e. expected to +# not be used). +dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ + +# Argument names that match this expression will be ignored. +ignored-argument-names=_.*|^ignored_|^unused_ + +# Tells whether we should check for unused import in __init__ files. +init-import=no + +# List of qualified module names which can have objects that can redefine +# builtins. +redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..5aec779 --- /dev/null +++ b/pytest.ini @@ -0,0 +1,3 @@ +[pytest] +DJANGO_SETTINGS_MODULE = post_it_backend.settings +python_files = tests.py test_*.py *_tests.py \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..4dde776 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,10 @@ +Django==4.2.6 +django-environ==0.11.2 +djangorestframework==3.14.0 +flake8==6.1.0 +psycopg2==2.9.9 +pylint==3.0.2 +pylint-django==2.5.5 +pytest-django==4.8.0 +coverage==7.4.3 +drf-yasg==1.21.7 \ No newline at end of file diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..04ec501 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,75 @@ +"""Reusable test functions""" +import pytest +from rest_framework.test import APIClient +from django.contrib.auth.models import User +from django.urls import reverse +from group.models import Group + + +@pytest.fixture(name="api_client") +def fixture_api_client(): + """ + APIClient fixture + """ + return APIClient() + + +@pytest.fixture(name="create_user") +def fixture_create_user(db): + """ + Create a user object + :param db + :return None + """ + def make_user(username, password, email): + return User.objects.create_user(username=username, + password=password, email=email) + return make_user + + +@pytest.fixture +def authenticate_user_with_token(db, api_client, create_user): + """ + Authenticate user with token after signin + :params db, api_client, create_user + """ + def authenticate_user(username, password, email): + """ + Authenticate user + """ + if not User.objects.filter(username=username).exists(): + create_user(username, password, email) + url = reverse('signin') + data = { + "username": username, + "password": password + } + + response = api_client.post(url, data=data, format="json") + print(response.data) + return response.data["token"] + return authenticate_user + + +@pytest.fixture(name="group_creator") +def fixture_group_creator(db, create_user): + """Create a user who is a group creator to test group delete""" + + return create_user(username='test_creator', + password='123', email='testcreator@gmail.com') + + +@pytest.fixture(name="another_user") +def fixture_another_user(db, create_user): + """Create a user object who isn't a group creator to test group delete""" + + return create_user(username='not_creator', + password='123', email='notcreator@gmail.com') + + +@pytest.fixture +def test_group(db, group_creator): + """Create a test group""" + group = Group.objects.create(name="Test group", creator=group_creator) + group.members.set([group_creator]) + return group diff --git a/tests/test_groups_api.py b/tests/test_groups_api.py new file mode 100644 index 0000000..6c14f5e --- /dev/null +++ b/tests/test_groups_api.py @@ -0,0 +1,292 @@ +"""Test cases for groups APIs""" +import pytest +from django.urls import reverse +from django.contrib.auth.models import User +from rest_framework import status +from group.models import Group + + +@pytest.mark.django_db +def test_group_create(api_client, authenticate_user_with_token): + """ + Test create group api endpoint + :param client + :return None + """ + + token = authenticate_user_with_token("testuser", "123", + "testuser@gmail.com") + + url = reverse("group") + data = { + "name": "test group" + } + api_client.credentials(HTTP_AUTHORIZATION='Token ' + token) + response = api_client.post(url, data=data, format="json") + + api_client.credentials() + + assert response.status_code == status.HTTP_201_CREATED + + +@pytest.mark.django_db +def test_group_list(api_client, authenticate_user_with_token, group_creator): + """Test GET method for retrieving groups""" + token = authenticate_user_with_token("testuser", "123", + "testuser@gmail.com") + + Group.objects.create(name="group 1", creator=group_creator) + Group.objects.create(name="group 2", creator=group_creator) + + url = reverse("group") + api_client.credentials(HTTP_AUTHORIZATION='Token ' + token) + response = api_client.get(url) + + api_client.credentials() + + assert response.status_code == status.HTTP_200_OK + expected_size = Group.objects.count() + assert response.json().get('count') == expected_size + + +@pytest.mark.django_db +def test_group_delete_success(api_client, authenticate_user_with_token, + test_group): + """Test successful group deletion""" + token = authenticate_user_with_token("test_creator", "123", + "testcreator@gmail.com") + + url = reverse("group") + api_client.credentials(HTTP_AUTHORIZATION='Token ' + token) + response = api_client.delete(f"{url}{test_group.id}/") + + api_client.credentials() + + assert response.status_code == status.HTTP_204_NO_CONTENT + + +@pytest.mark.django_db +def test_group_delete_permission_denied(api_client, + authenticate_user_with_token, + test_group): + """Test for permission denied if user is not a group creator""" + token = authenticate_user_with_token("not_creator", "123", + "notcreator@gmail.com") + + url = reverse("group") + api_client.credentials(HTTP_AUTHORIZATION='Token ' + token) + response = api_client.delete(f"{url}{test_group.id}/") + + api_client.credentials() + + assert response.status_code == status.HTTP_403_FORBIDDEN + + +@pytest.mark.django_db +def test_group_delete_group_not_found(api_client, + authenticate_user_with_token): + """Test deletion if group is not existent""" + token = authenticate_user_with_token("testuser", "123", + "testuser@gmail.com") + + url = reverse("group") + non_existent_group_id = 0 + api_client.credentials(HTTP_AUTHORIZATION='Token ' + token) + response = api_client.delete(f"{url}{non_existent_group_id}/") + + api_client.credentials() + + assert response.status_code == status.HTTP_404_NOT_FOUND + + +@pytest.mark.django_db +def test_group_add_members_successful(api_client, + authenticate_user_with_token, + group_creator): + """ + Test successful addition of new members to a group by the group creator + """ + token = authenticate_user_with_token("test_creator", "123", + "testcreator@gmail.com") + group = Group.objects.create(name="group 1", creator=group_creator) + user_1 = User.objects.create_user("user_1", "123", "user_1@gmail.com") + user_2 = User.objects.create_user("user_2", "123", "user_2@gmail.com") + + url = reverse("group") + data = { + "members": [user_1.id, user_2.id], + "group_id": group.id + } + api_client.credentials(HTTP_AUTHORIZATION='Token ' + token) + response = api_client.patch(url, data=data, format="json") + + api_client.credentials() + + assert response.status_code == status.HTTP_200_OK + + +@pytest.mark.django_db +def test_group_add_members_permission_denied(api_client, + authenticate_user_with_token, + group_creator): + """ + Test permission denied when adding new members to a group + """ + token = authenticate_user_with_token("not_creator", "123", + "notcreator@gmail.com") + group = Group.objects.create(name="group 1", creator=group_creator) + user_1 = User.objects.create_user("user_1", "123", "user_1@gmail.com") + user_2 = User.objects.create_user("user_2", "123", "user_2@gmail.com") + + url = reverse("group") + data = { + "members": [user_1.id, user_2.id], + "group_id": group.id + } + api_client.credentials(HTTP_AUTHORIZATION='Token ' + token) + response = api_client.patch(url, data=data, format="json") + + api_client.credentials() + + assert response.status_code == status.HTTP_403_FORBIDDEN + + +@pytest.mark.django_db +def test_group_add_members_bad_request(api_client, + authenticate_user_with_token, + group_creator): + """ + Test for non existent user when adding new members to a group + """ + token = authenticate_user_with_token("test_creator", "123", + "testcreator@gmail.com") + group = Group.objects.create(name="group 1", creator=group_creator) + non_existent_user_id = 0 + + url = reverse("group") + data = { + "members": [non_existent_user_id], + "group_id": group.id + } + api_client.credentials(HTTP_AUTHORIZATION='Token ' + token) + response = api_client.patch(url, data=data, format="json") + + api_client.credentials() + + assert response.status_code == status.HTTP_400_BAD_REQUEST + + +@pytest.mark.django_db +def test_group_add_members_group_not_found(api_client, + authenticate_user_with_token, + group_creator): + """ + Test group not found when adding new members to a group + """ + token = authenticate_user_with_token("test_creator", "123", + "testcreator@gmail.com") + user_1 = User.objects.create_user("user_1", "123", "user_1@gmail.com") + + non_existent_group_id = 0 + + url = reverse("group") + data = { + "members": [user_1.id], + "group_id": non_existent_group_id + } + api_client.credentials(HTTP_AUTHORIZATION='Token ' + token) + response = api_client.patch(url, data=data, format="json") + + api_client.credentials() + + assert response.status_code == status.HTTP_404_NOT_FOUND + + +@pytest.mark.django_db +def test_group_retrieve_single_group(api_client, + authenticate_user_with_token, + group_creator): + """Test GET method for retrieving a single group""" + token = authenticate_user_with_token("test_creator", "123", + "testcreator@gmail.com") + + group = Group.objects.create(name="group 1", creator=group_creator) + + url = reverse("group", kwargs={"group_id": group.id}) + api_client.credentials(HTTP_AUTHORIZATION='Token ' + token) + response = api_client.get(url) + + api_client.credentials() + + assert response.status_code == status.HTTP_200_OK + + +@pytest.mark.django_db +def test_group_successful_delete_user(api_client, + authenticate_user_with_token, + group_creator): + """Test successful removal of a user(s) from group""" + token = authenticate_user_with_token("test_creator", "123", + "testcreator@gmail.com") + + group = Group.objects.create(name="group 1", creator=group_creator) + user = User.objects.create_user("user_to_delete", "123", + "usertodelete@gmail.com") + group.members.set([user]) + + url = reverse("group", kwargs={"user_id": user.id}) + data = {"group_id": group.id} + + api_client.credentials(HTTP_AUTHORIZATION='Token ' + token) + response = api_client.delete(url, data=data, format="json") + + api_client.credentials() + + assert response.status_code == status.HTTP_204_NO_CONTENT + + +@pytest.mark.django_db +def test_group_only_creator_delete_user(api_client, + authenticate_user_with_token, + group_creator): + """Test that only group creator can remove a user(s) from group""" + token = authenticate_user_with_token("testuser", "123", + "testuser@gmail.com") + + group = Group.objects.create(name="group 1", creator=group_creator) + user = User.objects.create_user("user_to_delete", "123", + "usertodelete@gmail.com") + group.members.set([user]) + + url = reverse("group", kwargs={"user_id": user.id}) + data = {"group_id": group.id} + + api_client.credentials(HTTP_AUTHORIZATION='Token ' + token) + response = api_client.delete(url, data=data, format="json") + error = response.json().get("error") + assert error == "Only group creator can remove members" + + api_client.credentials() + + +@pytest.mark.django_db +def test_group_cannot_remove_creator_from_group(api_client, + authenticate_user_with_token, + group_creator): + """Test that group creator cannot be removed from group""" + token = authenticate_user_with_token("test_creator", "123", + "testcreator@gmail.com") + + group = Group.objects.create(name="group 1", creator=group_creator) + group.members.set([group_creator]) + + url = reverse("group", kwargs={"user_id": group_creator.id}) + data = {"group_id": group.id} + + api_client.credentials(HTTP_AUTHORIZATION='Token ' + token) + response = api_client.delete(url, data=data, format="json") + error = response.json().get("error") + assert error == "Cannot remove creator from the group" + assert response.status_code == status.HTTP_403_FORBIDDEN + + api_client.credentials() diff --git a/tests/test_users_api.py b/tests/test_users_api.py new file mode 100644 index 0000000..4c4367b --- /dev/null +++ b/tests/test_users_api.py @@ -0,0 +1,44 @@ +"""Test cases for users APIs""" +import pytest +from django.urls import reverse +from django.contrib.auth.models import User +from rest_framework import status + + +@pytest.mark.django_db +def test_user_signup_api(api_client): + """ + Test the user signup API + :param client + :return None + """ + + url = reverse('signup') + data = { + "username": "testuser", + "password": "123", + "email": "testuser@gmail.com" + } + response = api_client.post(url, data=data, format="json") + assert response.status_code == status.HTTP_201_CREATED + + user = User.objects.get(username="testuser") + assert user.username == "testuser" + + +@pytest.mark.django_db +def test_user_signin_api(api_client, create_user): + """ + Test the user signin API + :param client, create_user + :return None + """ + create_user("testuser", "123", "testuser@gmail.com") + url = reverse('signin') + data = { + "username": "testuser", + "password": "123" + } + + response = api_client.post(url, data=data, format="json") + assert response.status_code == status.HTTP_200_OK diff --git a/user/__init__.py b/user/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/user/apps.py b/user/apps.py new file mode 100644 index 0000000..93b93cf --- /dev/null +++ b/user/apps.py @@ -0,0 +1,8 @@ +"""App module""" +from django.apps import AppConfig + + +class UserConfig(AppConfig): + """app class configuration""" + default_auto_field = 'django.db.models.BigAutoField' + name = 'user' diff --git a/user/models.py b/user/models.py new file mode 100644 index 0000000..6b20219 --- /dev/null +++ b/user/models.py @@ -0,0 +1 @@ +# Create your models here. diff --git a/user/serializers.py b/user/serializers.py new file mode 100644 index 0000000..d6f65c6 --- /dev/null +++ b/user/serializers.py @@ -0,0 +1,20 @@ +"""user serializer module""" +from rest_framework import serializers +from django.contrib.auth.models import User +from django.contrib.auth.hashers import make_password + + +class UserSerializer(serializers.ModelSerializer): + """user serializer class""" + class Meta: + """user serializer meta class""" + model = User + fields = ['id', 'username', 'password', 'email'] + extra_kwargs = {'password': {'write_only': True}} + + def create(self, validated_data): + password = validated_data.pop('password') + user = User(**validated_data) + user.password = make_password(password) + user.save() + return user diff --git a/user/urls.py b/user/urls.py new file mode 100644 index 0000000..4e41412 --- /dev/null +++ b/user/urls.py @@ -0,0 +1,9 @@ +"""user urls module""" +from django.urls import path +from .views import UserSignupAPIView, UserSigninAPIView + + +urlpatterns = [ + path('signup/', UserSignupAPIView.as_view(), name='signup'), + path('signin/', UserSigninAPIView.as_view(), name='signin'), +] diff --git a/user/views.py b/user/views.py new file mode 100644 index 0000000..6ae6ee7 --- /dev/null +++ b/user/views.py @@ -0,0 +1,35 @@ +"""user views module""" +from rest_framework.views import APIView +from rest_framework.response import Response +from rest_framework import status +from rest_framework.authtoken.models import Token +from django.contrib.auth import authenticate +from .serializers import UserSerializer + + +class UserSignupAPIView(APIView): + """Define method(s) for signing up""" + def post(self, request): + """a function for signing up a user""" + serializer = UserSerializer(data=request.data) + if serializer.is_valid(): + serializer.save() + return Response(serializer.data, status=status.HTTP_201_CREATED) + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + + +class UserSigninAPIView(APIView): + """Define method(s) for signing in a user""" + def post(self, request): + """a function for signing in a user""" + username = request.data.get('username') + password = request.data.get('password') + user = authenticate(username=username, password=password) + if not user: + return Response({ + 'error': 'username or password is incorrect'}, + status=status.HTTP_401_UNAUTHORIZED) + token, _ = Token.objects.get_or_create(user=user) + return Response({ + 'token': token.key}, + status=status.HTTP_200_OK)