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

Fixing most of the logging errors + typo and fixes grave security things #438

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 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
9 changes: 0 additions & 9 deletions BackEndApp/BackEndApp/asgi.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,3 @@
"""
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/
"""

import os

from django.core.asgi import get_asgi_application
Expand Down
66 changes: 38 additions & 28 deletions BackEndApp/BackEndApp/settings.py
Original file line number Diff line number Diff line change
@@ -1,38 +1,42 @@
"""
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/

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

import ast
import logging
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
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__)

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 Down Expand Up @@ -146,5 +150,11 @@
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"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I really liked the implementation of the PRODUCTION_SERVER configurations. Thanks ✌️

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks! I have doing this for many django app, since I read their security docs

15 changes: 0 additions & 15 deletions BackEndApp/BackEndApp/urls.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,3 @@
"""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/
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

Expand Down
9 changes: 0 additions & 9 deletions BackEndApp/BackEndApp/wsgi.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,3 @@
"""
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/
"""

import os

from django.core.wsgi import get_wsgi_application
Expand Down
3 changes: 0 additions & 3 deletions BackEndApp/authv1/admin.py

This file was deleted.

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,7 +1,12 @@
import logging
import os
import posixpath
import shutil

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 @@ -40,6 +45,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: 16 additions & 4 deletions BackEndApp/authv1/views.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
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

from django.core.mail import send_mail
from .auth import OTP
from .emails import EmailTemplates
from .models import Session, User
from .store import Store

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 @@ -72,6 +77,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 All @@ -95,6 +101,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 @@ -132,6 +139,7 @@ def forgot_password(request):
status = 500

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

Expand All @@ -156,6 +164,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 @@ -186,6 +195,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 @@ -204,7 +214,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 @@ -217,6 +228,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
14 changes: 5 additions & 9 deletions BackEndApp/deployments/models.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@
import os
import git
import shutil

import git
from django.http import HttpResponse, JsonResponse

from .exceptions import (AppDownloadFailed, AppUpsertionFailed,
CloneGenerationFailed, PickleCopyFailed)
from .utils import zip_flask_app
from .exceptions import (
AppDownloadFailed,
AppUpsertionFailed,
CloneGenerationFailed,
PickleCopyFailed,
)

from django.http import JsonResponse, HttpResponse


class Deployment:
Expand Down
Loading