Skip to content

Commit

Permalink
Initial phrase
Browse files Browse the repository at this point in the history
  • Loading branch information
AyemunHossain committed Feb 15, 2022
0 parents commit e0a5261
Show file tree
Hide file tree
Showing 37 changed files with 612 additions and 0 deletions.
4 changes: 4 additions & 0 deletions core/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
from __future__ import absolute_import, unicode_literals
from .celery import app as celery_app

__all__ = ('celery_app',)
Binary file added core/__pycache__/__init__.cpython-38.pyc
Binary file not shown.
Binary file added core/__pycache__/celery.cpython-38.pyc
Binary file not shown.
Binary file added core/__pycache__/settings.cpython-38.pyc
Binary file not shown.
Binary file added core/__pycache__/urls.cpython-38.pyc
Binary file not shown.
Binary file added core/__pycache__/wsgi.cpython-38.pyc
Binary file not shown.
16 changes: 16 additions & 0 deletions core/asgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
ASGI config for core 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/3.2/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')

application = get_asgi_application()
24 changes: 24 additions & 0 deletions core/celery.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from __future__ import absolute_import
import os
from celery import Celery
from django.conf import settings
from pytz import timezone


BASE_REDIS_URL = os.environ.get('REDIS_URL', 'redis://localhost:6379')


os.environ.setdefault('DJANGO_SETTINGS_MODULE','core.settings')
app = Celery('core')
app.conf.enable_utc = False
app.conf.update(timezone='Asia/Dhaka')

app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
app.conf.broker_url = BASE_REDIS_URL



@app.task(bind=True)
def debug_task(self):
print(f'Request: {self.request!r}')
214 changes: 214 additions & 0 deletions core/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
from pathlib import Path
from datetime import timedelta
from django.conf import settings


BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-r(b2&bp!i+l6mh0m-i3w)xxf#^0=yem80*#hk6w9ukbvw0jiqj'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'user.apps.UserConfig',
'rest_framework.authtoken',
'rest_framework',
'drf_yasg',
'rest_framework_swagger',
'rest_framework_simplejwt',
'rest_framework_simplejwt.token_blacklist',
]

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 = 'core.urls'
AUTH_USER_MODEL = "user.UserAccount"

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates'],
'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 = 'core.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}


# Password validation
# https://docs.djangoproject.com/en/3.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/3.2/topics/i18n/

LANGUAGE_CODE = 'en-us'
USE_I18N = True
USE_L10N = True
USE_TZ = True
TIME_ZONE = 'Asia/Dhaka'



STATIC_ROOT = BASE_DIR / 'static'
MEDIA_ROOT = BASE_DIR / 'images'

STATIC_URL = '/static/'
MEDIA_URL = '/media/'

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'




REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser',
],

'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),

'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticatedOrReadOnly',),

'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',

'PAGE_SIZE': 10,

'DEFAULT_THROTTLE_CLASSES': (
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle',
),

'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
),
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema'

# 'DEFAULT_THROTTLE_RATES': {
# 'anon': '1/minute',
# 'user': '20/minute',
# },
}


SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'ROTATE_REFRESH_TOKENS': False,
'BLACKLIST_AFTER_ROTATION': False,
'UPDATE_LAST_LOGIN': False,

'ALGORITHM': 'HS256',
'SIGNING_KEY': settings.SECRET_KEY,
'VERIFYING_KEY': None,
'AUDIENCE': None,
'ISSUER': None,
'JWK_URL': None,
'LEEWAY': 0,

'AUTH_HEADER_TYPES': ('Bearer', "JWT"),
'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule',

'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
'TOKEN_TYPE_CLAIM': 'token_type',

'JTI_CLAIM': 'jti',

'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}


SWAGGER_SETTINGS = {
'SECURITY_DEFINITIONS': {
'basic': {
'type': 'basic'
}
},
}

REDOC_SETTINGS = {
'LAZY_RENDERING': False,
}




REDIS_HOST = "127.0.0.1"
REDIS_PORT = 6379
BROKER_URL = 'redis://localhost:6379'
CELERY_RESULT_BACKEND = 'redis://localhost:6379'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'Asia/Dhaka'
11 changes: 11 additions & 0 deletions core/tasks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from celery import shared_task

from celery.utils.log import get_task_logger
from time import sleep

logger = get_task_logger(__name__)

@shared_task(name='my_first_task')
def my_first_task(duration):
sleep(duration)
return('first_task_done')
22 changes: 22 additions & 0 deletions core/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""core URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.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

urlpatterns = [
path('admin/', admin.site.urls),
path('', include('user.urls')),
]
16 changes: 16 additions & 0 deletions core/wsgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
WSGI config for core 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/3.2/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')

application = get_wsgi_application()
22 changes: 22 additions & 0 deletions manage.py
Original file line number Diff line number Diff line change
@@ -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', 'core.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()
Empty file added user/__init__.py
Empty file.
Binary file added user/__pycache__/__init__.cpython-38.pyc
Binary file not shown.
Binary file added user/__pycache__/admin.cpython-38.pyc
Binary file not shown.
Binary file added user/__pycache__/apiView.cpython-38.pyc
Binary file not shown.
Binary file added user/__pycache__/apps.cpython-38.pyc
Binary file not shown.
Binary file added user/__pycache__/choices.cpython-38.pyc
Binary file not shown.
Binary file added user/__pycache__/models.cpython-38.pyc
Binary file not shown.
Binary file added user/__pycache__/serializers.cpython-38.pyc
Binary file not shown.
Binary file added user/__pycache__/urls.cpython-38.pyc
Binary file not shown.
5 changes: 5 additions & 0 deletions user/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.contrib import admin
from .models import UserAccount as User


admin.site.register(User)
47 changes: 47 additions & 0 deletions user/apiView.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
from rest_framework import permissions, status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_simplejwt.tokens import RefreshToken
from .serializers import LoginSerializer, RegisterUserSerializer


class RegisterUser(APIView):
permission_classes = [permissions.AllowAny]
serializer_class = RegisterUserSerializer
def post(self,request,format="json"):
serializer = self.serializer_class(data=request.data)

if serializer.is_valid():
try:
newUser = serializer.save()
if newUser:
response = serializer.data
return Response(response, status=status.HTTP_201_CREATED)

except Exception as e:
return Response(status=status.HTTP_400_BAD_REQUEST)

return Response(serializer.errors or None, status=status.HTTP_400_BAD_REQUEST)


class LoginAPIView(APIView):
serializer_class = LoginSerializer
permission_classes = [permissions.AllowAny]

def post(self, request):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
return Response(serializer.data, status=status.HTTP_200_OK)


class BlacklistTokenAdding(APIView):
permission_classes = [permissions.AllowAny]

def post(self, request, format='json'):
try:
refresh_token = request.data["refresh_token"]
token = RefreshToken(refresh_token)
token.blacklist()
return Response(status=status.HTTP_200_OK)
except Exception as e:
return Response(status=status.HTTP_400_BAD_REQUEST)
Loading

0 comments on commit e0a5261

Please sign in to comment.