Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve settings.py #442

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions BackEndApp/BackEndApp/asgi.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
"""
ASGI config for BackEndApp 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.0/howto/deployment/asgi/
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""

import os
Expand Down
66 changes: 43 additions & 23 deletions BackEndApp/BackEndApp/settings.py
Original file line number Diff line number Diff line change
@@ -1,38 +1,50 @@
"""
Django settings for BackEndApp project.

Generated by 'django-admin startproject' using Django 3.0.2.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/

https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
https://docs.djangoproject.com/en/3.2/ref/settings/
"""

import ast
import logging
import logging.config
import os
from pathlib import Path
from urllib.parse import urlparse

import dotenv
from corsheaders.defaults import default_headers

import logging
import logging.config
from .logging import LOGGING

HOST = os.getenv("HOST", "http://localhost:8000")
FRONTEND_HOST = os.getenv("FRONTEND_HOST", "http://localhost:3000")

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "q$2lre_hyydi(w7hb!*03()$y*q#rzy#ny^9hitqjb^q1_a6q="

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
BASE_DIR = Path(__file__).resolve().parent.parent

if not os.path.exists(BASE_DIR / 'logs'):
os.makedirs(BASE_DIR / 'logs')

dotenv_file = BASE_DIR / ".env"
ENV_EXISTS = os.path.isfile(dotenv_file)
if ENV_EXISTS:
import secrets
import string
dotenv.load_dotenv(dotenv_file)
PRODUCTION_SERVER = ast.literal_eval(
os.environ.get('PRODUCTION_SERVER').capitalize(), 'False')
SECRET_KEY = ''.join(secrets.choice(string.ascii_letters +
string.digits + str(secrets.randbits(7))) for i in range(10))
DEBUG = ast.literal_eval(os.environ.get('DEBUG').capitalize(), 'True')
else:
PRODUCTION_SERVER = ast.literal_eval(
os.environ.get('PRODUCTION_SERVER').capitalize(), 'True')
DEBUG = ast.literal_eval(os.environ.get('DEBUG').capitalize(), 'False')
SECRET_KEY = os.environ.get('SECRET_KEY', ''.join(secrets.choice(
string.ascii_letters + string.digits + str(secrets.randbits(7))) for i in range(10)))

ALLOWED_HOSTS = ["localhost", "127.0.0.1", urlparse(HOST).hostname]

Expand All @@ -47,9 +59,9 @@
"django.contrib.messages",
"django.contrib.staticfiles",
"corsheaders",
"authv1",
"v1",
"deployments",
"authv1.apps",
"v1.apps.V1Config",
"deployments.apps",
]

MIDDLEWARE = [
Expand Down Expand Up @@ -146,5 +158,13 @@
EMAIL_HOST_USER = os.environ.get("EMAIL_HOST_USER")
EMAIL_HOST_PASSWORD = os.environ.get("EMAIL_HOST_PASSWORD")

# Logging
logging.config.dictConfig(LOGGING)
if PRODUCTION_SERVER:
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 31536000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
SECURE_REFERRER_POLICY = "same-origin"


4 changes: 2 additions & 2 deletions BackEndApp/BackEndApp/urls.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"""BackEndApp URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
Expand All @@ -13,6 +12,7 @@
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

Expand Down
4 changes: 1 addition & 3 deletions BackEndApp/BackEndApp/wsgi.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
"""
WSGI config for BackEndApp 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.0/howto/deployment/wsgi/
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/
"""

import os
Expand Down
3 changes: 0 additions & 3 deletions BackEndApp/authv1/admin.py

This file was deleted.

1 change: 1 addition & 0 deletions BackEndApp/authv1/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@


class Authv1Config(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "authv1"
16 changes: 12 additions & 4 deletions BackEndApp/authv1/auth.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
from .connector import connect
import logging
import os
import jwt
import random
import string
from datetime import datetime, timedelta

import jwt
from dotenv import load_dotenv
import string

from .connector import connect
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)-15s | %(levelname)s - %(levelno)s | Line No: %(lineno)d | Module: %(module)s | %(message)s')
log = logging.getLogger(__name__)


load_dotenv()

Expand Down Expand Up @@ -48,7 +54,8 @@ def verify(self):

secret = os.getenv("JWT_SECRET")
decoded = jwt.decode(self.token, secret, algorithms="HS256")
decoded["expire"] = datetime.strptime(decoded.get("expire"), DATE_FORMAT)
decoded["expire"] = datetime.strptime(
decoded.get("expire"), DATE_FORMAT)

if (
decoded.get("username") == self.user.get("username")
Expand Down Expand Up @@ -92,6 +99,7 @@ def create(self, time_delta=5):
self.collection.insert_one(doc_otp)
return self.otp
except Exception as e:
log.exception('Exception Occured', e)
return None

def find(self):
Expand Down
11 changes: 9 additions & 2 deletions BackEndApp/authv1/connector.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import logging
import os
import ssl

import pymongo
from dotenv import load_dotenv

logging.basicConfig(level=logging.DEBUG,
format='%(asctime)-15s | %(levelname)s - %(levelno)s | Line No: %(lineno)d | Module: %(module)s | %(message)s')
log = logging.getLogger(__name__)

load_dotenv()


Expand All @@ -20,9 +26,10 @@ def connect(db_name="auth_db"):
db : object
database client connection object
"""
client = pymongo.MongoClient(os.getenv("MONGODB_URI"), ssl_cert_reqs=ssl.CERT_NONE)
client = pymongo.MongoClient(
os.getenv("MONGODB_URI"), ssl_cert_reqs=ssl.CERT_NONE)
db = client[db_name]
print("MongoDB connected")
log.info("MongoDB connected")
return db


Expand Down
15 changes: 13 additions & 2 deletions BackEndApp/authv1/models.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
import logging
import re

import bcrypt

from authv1 import connector
from authv1.auth import Token

logging.basicConfig(level=logging.DEBUG,
format='%(asctime)-15s | %(levelname)s - %(levelno)s | Line No: %(lineno)d | Module: %(module)s | %(message)s')
log = logging.getLogger(__name__)

DATE_FORMAT = "%Y/%m/%d %H/%M/%S"


Expand Down Expand Up @@ -33,7 +40,8 @@ def create(self):
if self.find():
raise ValueError("Invalid username or username already exists")

hashed_password = bcrypt.hashpw(self.password.encode("utf-8"), bcrypt.gensalt())
hashed_password = bcrypt.hashpw(
self.password.encode("utf-8"), bcrypt.gensalt())

user_document = {
"username": self.username,
Expand Down Expand Up @@ -61,6 +69,7 @@ def update(self, field_name, new_value, **kwargs):
)
return 0, None
except Exception as e:
log.exception('Could not update', e)
return 1, "Could not update."

def delete(self):
Expand Down Expand Up @@ -93,11 +102,13 @@ def create(self):
token = str(token, "utf-8")
expire = token_obj.expire.strftime(DATE_FORMAT)

session_document = {"token": token, "expire": expire, "user": self.user}
session_document = {"token": token,
"expire": expire, "user": self.user}
try:
self.collection.insert_one(session_document)
return token
except:
log.exception('Exception Occured', e)
return None

def delete(self, token):
Expand Down
6 changes: 6 additions & 0 deletions BackEndApp/authv1/store.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logging
import os
import posixpath
import shutil
Expand All @@ -6,6 +7,10 @@
sys.path.append("../")
from constants import ROOT_DIR

logging.basicConfig(level=logging.DEBUG,
format='%(asctime)-15s | %(levelname)s - %(levelno)s | Line No: %(lineno)d | Module: %(module)s | %(message)s')
log = logging.getLogger(__name__)


class Store:
def __init__(self, user):
Expand Down Expand Up @@ -44,6 +49,7 @@ def delete(self, project=None):
shutil.rmtree(_path)
return 0, None
except Exception as e:
log.exception('Exception Occured', e)
return 1, str(e)

def enlist(self):
Expand Down
3 changes: 0 additions & 3 deletions BackEndApp/authv1/tests.py

This file was deleted.

1 change: 1 addition & 0 deletions BackEndApp/authv1/urls.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from django.urls import path

from . import views

urlpatterns = [
Expand Down
20 changes: 17 additions & 3 deletions BackEndApp/authv1/views.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
import json
import logging

import bcrypt
from BackEndApp.settings import EMAIL_HOST_USER
from django.core.mail import send_mail
from django.http import JsonResponse
from rest_framework.decorators import api_view
from rest_framework.response import Response
import json

import bcrypt
import shutil
import os
import sys

from django.core.mail import send_mail
from .auth import OTP
from .emails import EmailTemplates
from .models import Session, User
Expand All @@ -19,6 +22,10 @@
sys.path.append("../")
from constants import ROOT_DIR

logging.basicConfig(level=logging.DEBUG,
format='%(asctime)-15s | %(levelname)s - %(levelno)s | Line No: %(lineno)d | Module: %(module)s | %(message)s')
log = logging.getLogger(__name__)


@api_view(["POST"])
def login(request):
Expand Down Expand Up @@ -79,6 +86,7 @@ def register(request):
status = 401
token = None
username = None
llog.exception("Some error occured!", e)
return JsonResponse(
{"message": message, "username": username, "token": token}, status=status
)
Expand Down Expand Up @@ -119,6 +127,7 @@ def logout(request):
status = 200

except Exception as e:
log.exception("Some error occured", e)
message = "Some error occurred!! Please try again."
status = 500

Expand Down Expand Up @@ -156,6 +165,7 @@ def forgot_password(request):
status = 200

except Exception as e:
log.exception("Some error occured", e)
message = "Some error occurred! Please try again."
status = 500

Expand All @@ -180,6 +190,7 @@ def verify_email(request):
status = 200

except Exception as e:
log.exception("Some error occured", e)
message = "Some error occured! Please try again."
status = 500

Expand Down Expand Up @@ -210,6 +221,7 @@ def verify_otp(request):
status = 401

except Exception as e:
log.exception("Some error occured", e)
message = "Some error occurred! Please try again."
status = 500

Expand All @@ -228,7 +240,8 @@ def update_password(request):
status = 401

new_password = request.data.get("password")
hashed_password = bcrypt.hashpw(new_password.encode("utf-8"), bcrypt.gensalt())
hashed_password = bcrypt.hashpw(
new_password.encode("utf-8"), bcrypt.gensalt())
old_password = this_user.get("password", "")

if str(old_password) == str(hashed_password):
Expand All @@ -241,6 +254,7 @@ def update_password(request):
status = 200

except Exception as e:
log.exception("Some error occured", e)
message = "Some error occurred! Please try again."
status = 500

Expand Down
3 changes: 2 additions & 1 deletion BackEndApp/deployments/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ def __init__(self, deployment_dir) -> None:
class PickleAppendFailed(DeploymentException):
def __init__(self, project_id) -> None:
self.project_id = project_id
super().__init__(f"\nPickle chunk append for Project {project_id} failed.")
super().__init__(
f"\nPickle chunk append for Project {project_id} failed.")


class PickleCopyFailed(DeploymentException):
Expand Down
Loading