Skip to content

Commit

Permalink
fix: refactoring & cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
ruzniaievdm committed Jul 2, 2024
1 parent 2bb4570 commit 0786bfd
Show file tree
Hide file tree
Showing 14 changed files with 465 additions and 443 deletions.
25 changes: 0 additions & 25 deletions .env

This file was deleted.

4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
**/jest*
**/dist
**/build
**/.env.production

# Envs
*.env

# Logs
logs
Expand Down
31 changes: 17 additions & 14 deletions backend/api/users/views.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
from django.contrib.auth import get_user_model
from rest_framework import status
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.authentication import BasicAuthentication, SessionAuthentication
from rest_framework.authtoken.models import Token
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.decorators import action
from rest_framework.mixins import (
ListModelMixin, RetrieveModelMixin, UpdateModelMixin
)
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin, UpdateModelMixin
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet

from .serializers import UserSerializer
from api.users.serializers import UserSerializer

User = get_user_model()

Expand All @@ -19,16 +17,19 @@ class CustomObtainAuthTokenView(ObtainAuthToken):
authentication_classes = [SessionAuthentication, BasicAuthentication]

def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data,
context={'request': request})
serializer = self.serializer_class(
data=request.data, context={"request": request}
)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
user = serializer.validated_data["user"]
token, _ = Token.objects.get_or_create(user=user)

return Response({
'token': token.key,
'username': user.username,
})
return Response(
{
"token": token.key,
"username": user.username,
}
)


class UserViewSet(RetrieveModelMixin, ListModelMixin, UpdateModelMixin, GenericViewSet):
Expand All @@ -37,5 +38,7 @@ class UserViewSet(RetrieveModelMixin, ListModelMixin, UpdateModelMixin, GenericV

@action(detail=False)
def all(self, request):
serializer = self.get_serializer(self.queryset, many=True, context={"request": request})
serializer = self.get_serializer(
self.queryset, many=True, context={"request": request}
)
return Response(status=status.HTTP_200_OK, data=serializer.data)
11 changes: 6 additions & 5 deletions backend/backend/asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@


os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.settings")
print('HERE settings', 'asgii')

application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": TokenAuthMiddleware(URLRouter(websocket_urlpatterns)),
})
application = ProtocolTypeRouter(
{
"http": get_asgi_application(),
"websocket": TokenAuthMiddleware(URLRouter(websocket_urlpatterns)),
}
)
125 changes: 58 additions & 67 deletions backend/backend/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,54 +20,59 @@
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = environ.get('DJANGO_SECRET_KEY', 'django-insecure-secret')
SECRET_KEY = environ.get("DJANGO_SECRET_KEY", "django-insecure-secret")

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = environ.get("DJANGO_DEBUG")

# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
DEFAULT_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
# third-party
'channels',
'corsheaders',
'rest_framework',
'rest_framework.authtoken',
# personal
'chat',
"channels",
"corsheaders",
"rest_framework",
"rest_framework.authtoken",
]

CUSTOM_APPS = [
"chat",
]

INSTALLED_APPS = DEFAULT_APPS + CUSTOM_APPS

MIDDLEWARE = [
# 'django_grip.GripMiddleware',
"corsheaders.middleware.CorsMiddleware",
'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',
"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",
"django.middleware.common.CommonMiddleware",
]

ROOT_URLCONF = 'backend.urls'
ROOT_URLCONF = "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',
"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",
],
},
},
Expand All @@ -81,12 +86,12 @@

DATABASES = {
"default": {
"ENGINE": environ.get('DB_ENGINE', 'django.db.backends.postgresql'),
'NAME': environ.get('DB_NAME', 'default'),
'USER': environ.get('DB_USER', 'postgres_user'),
'PASSWORD': environ.get('DB_PASSWORD', 'postgres_password'),
'HOST': environ.get('DB_HOST', 'db'),
'PORT': environ.get('DB_PORT', 5432),
"ENGINE": environ.get("DB_ENGINE", "django.db.backends.postgresql"),
"NAME": environ.get("DB_NAME", "default"),
"USER": environ.get("DB_USER", "postgres_user"),
"PASSWORD": environ.get("DB_PASSWORD", "postgres_password"),
"HOST": environ.get("DB_HOST", "db"),
"PORT": environ.get("DB_PORT", 5432),
}
}

Expand All @@ -96,26 +101,26 @@

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]


# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/

LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = "en-us"

TIME_ZONE = 'UTC'
TIME_ZONE = "UTC"

USE_I18N = True

Expand All @@ -125,48 +130,34 @@
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

STATIC_URL = 'static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
STATIC_URL = "static/"
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

# Channels
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [('redis', environ.get("REDIS_PORT"))],
"hosts": [("redis", environ.get("REDIS_PORT"))],
},
},
}

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
"DEFAULT_AUTHENTICATION_CLASSES": [
"rest_framework.authentication.BasicAuthentication",
"rest_framework.authentication.SessionAuthentication",
"rest_framework.authentication.TokenAuthentication",
]
}

# os.environ.get("DJANGO_ALLOWED_HOSTS").split(" ")
# ALLOWED_HOSTS = ['localhost']

# CORS_ALLOWED_ORIGINS = [
# "https://localhost:3000"
# ]

CORS_ALLOW_CREDENTIALS = True
# CORS_ORIGIN_ALLOW_ALL = True

CORS_ORIGIN_WHITELIST = (
'http://localhost:3000',
)

# CSRF_TRUSTED_ORIGINS = ['http://localhost:3000']
CORS_ORIGIN_WHITELIST = ("http://localhost:3000",)

FIXTURE_DIRS = ['backend/fixtures/users.json']
FIXTURE_DIRS = ["backend/fixtures/users.json"]
7 changes: 4 additions & 3 deletions backend/backend/urls.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
"""
backend URL Configuration
"""

from django.contrib import admin
from django.urls import path, include
from rest_framework import routers

from api import ConversationViewSet, UserViewSet, CustomObtainAuthTokenView

router = routers.DefaultRouter()
router.register('users', UserViewSet, basename='users')
router.register('conversations', ConversationViewSet, basename='conversations')
router.register("users", UserViewSet, basename="users")
router.register("conversations", ConversationViewSet, basename="conversations")

urlpatterns = [
path("api/", include(router.urls)),
path('admin/', admin.site.urls),
path("admin/", admin.site.urls),
path("auth-token/", CustomObtainAuthTokenView.as_view()),
]
2 changes: 1 addition & 1 deletion backend/backend/wsgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.settings")

application = get_wsgi_application()
Loading

0 comments on commit 0786bfd

Please sign in to comment.