2

The website is live and its hosted on remote server(aws ec2) but when I try to register to the website its giving error.

Error while registering to the Website

Error.png

I have gone through previous SO post but they didn't help me to fix:

settings.py

"""
Django settings for sufintek project.

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

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

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

from datetime import datetime
from pathlib import Path
import os
import sys
import json

import pathlib

WEBSITE_DIR = None
CONFIG_FILE_PATH = None
DEBUG = True
BASE_DIR = Path(__file__).resolve().parent.parent

if sys.platform == "win32":
    WEBSITE_DIR = os.path.join(str(Path.home().parent.parent), 'Sufintek')
    CONFIG_FILE_PATH = os.path.join(WEBSITE_DIR, "pconfig", "sufintek.json")
else:
    WEBSITE_DIR = os.path.join('/var', 'Sufintek')
    CONFIG_FILE_PATH = os.path.join(WEBSITE_DIR, "pconfig", "sufintek.json")

assert WEBSITE_DIR
assert CONFIG_FILE_PATH

with open(CONFIG_FILE_PATH, "r") as jfile:
    PRO_SETTINGS = json.load(jfile)

print("PRO_SETTINGS")
print(PRO_SETTINGS)

# Build paths inside the project like this: BASE_DIR / 'subdir'.


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = PRO_SETTINGS["secret_key"]

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

if not os.path.exists(os.path.join(WEBSITE_DIR, 'logs')):
    os.makedirs(os.path.join(WEBSITE_DIR, 'logs'))

LOG_FILE = os.path.join(str(datetime.strftime(datetime.now(), "%d-%m-%Y.log")))


LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'loggers': {
        'Sufintek': {
            'handlers': ['file'],
            'level': 'DEBUG'
        }
    },
    'handlers': {
        'file': {
            'level': 'INFO',
            'class': 'logging.FileHandler',
            'filename': os.path.join(WEBSITE_DIR, 'logs', LOG_FILE),
            'formatter': 'verbose',
        }},
    'formatters': {
        'verbose': {
            'format': '{levelname} {asctime} {module} {message}',
            'style': '{',
        }
    }
}

# Find a solution for testing and production
IP_ADDRESS = "3.110.170.248"

ALLOWED_HOSTS = [IP_ADDRESS, f"{IP_ADDRESS}:8000"]
CSRF_TRUSTED_ORIGINS = [f"http://{IP_ADDRESS}:8000", f"http://{IP_ADDRESS}", "http://localhost", "http://localhost:8000"]

print("CSRF Trusted Origins")
print(CSRF_TRUSTED_ORIGINS)

# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "users",
    "django.contrib.sites",
    "allauth",
    "allauth.account",
    "allauth.socialaccount",
    "allauth.socialaccount.providers.google",
]

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",
]
AUTH_USER_MODEL = 'users.User'

ROOT_URLCONF = "sufintek.urls"

# print(f"Base dir : {BASE_DIR}")
# print(os.path.join(BASE_DIR, 'templates'))

# Added templates to TEMPLATES

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [
            os.path.join(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 = "sufintek.wsgi.application"


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


DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": PRO_SETTINGS["database"],
        "USER": PRO_SETTINGS["user"],
        "PASSWORD": PRO_SETTINGS["pass"],
        "HOST": "localhost"
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.1/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.1/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.1/howto/static-files/

STATIC_URL = "/static/"

STATIC_ROOT = os.path.join(BASE_DIR, "static_root")

# this is where static files goes
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'templates', 'static')
]

MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "templates",
                          "static", "assets", "usersImage")

# for static_path in STATICFILES_DIRS:
#     print(f"STATICFILES DIR {static_path}")

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

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

SECURE_REFERRER_POLICY = "no-referrer-when-downgrade"

CSRF_COOKIE_SECURE = False
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_SAMESITE = 'None'
SESSION_COOKIE_SAMESITE = 'None'

# SMTP CONFIGURATION

EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = PRO_SETTINGS["email_address"]
EMAIL_HOST_PASSWORD = PRO_SETTINGS["email_pass"]

LOGIN_URL = 'login'

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'allauth.account.auth_backends.AuthenticationBackend'
]

SOCIALACCOUNT_LOGIN_ON_GET = True

SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'SCOPE': [
            'profile',
            'email',
        ],
        'AUTH_PARAMS': {
            'access_type': 'online',
        },
        'OAUTH_PKCE_ENABLED': True,
    }
}
SITE_ID = 1
SOCIALACCOUNT_LOGIN_ON_GET = True
LOGIN_REDIRECT_URL = '/'
LOGIN_REDIRECT_URL = 'glogin_success'
LOGOUT_REDIRECT_URL = '/'

# ACCOUNT_USER_MODEL_USERNAME_FIELD = None

ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_USERNAME_REQUIRED = False

I have tested it thoroughly on local machine and its works fine but fails when deployed on server.

I cannot register to the website its keep on generating csrf_token not set.

I have added {% csrf_token %} inside form tag of the register.html file

register.html

{% extends 'base.html' %}
{% load static %}
{% load socialaccount %}

{% block title %}
<title>Sufintek</title>
{% endblock %}

{% block css %}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.3/font/bootstrap-icons.css">
<link rel="stylesheet" href="{% static 'css/users_reg.css' %}" />
{% endblock %}


{% block content %}
<div class="container-fluid">
    <div class="row mt-3">
        <div class="col-12  d-flex justify-content-center">
            <p class="display-6 fw-semibold" style="color: #ae00ffb3; text-shadow: 5px 5px 10px rgb(158, 158, 158);">
                Create Account</p>
        </div>
        <div class="col-12 d-flex justify-content-center mt-md-2">
            <div class="card border-1 shadow" style="max-width: 840px; max-height: 500px;">
                <div class="row g-0">
                    <div class="col-md-4 d-none d-md-block">
                        <img class="img-fluid rounded-start" src="{% static '/assets/images/leftImage.avif'%}">
                    </div>
                    <div class="col-md-8">
                        <div class="card-body">
                            <form class="form needs-validation" id="login" method="post"
                                onsubmit="return onFormSubmit(this)" action="/users/register/">
                                {% csrf_token %}
                                <div class="row mt-2 align-items-center">
                                    <div class="col-sm-12 col-md-3">
                                        <label class="form-label fs-6" for="validationUsername">First Name</label>
                                    </div>
                                    <div class="col-sm-12 col-md-9">
                                        <div class="input-group">
                                            <span class="input-group-text"><i class="bi bi-person"></i></span>
                                            <input id="firstName" type="text" class="form-control form-control-sm"
                                                placeholder="First Name *" name="firstName" required>
                                            <div class="invalid-feedback">
                                                Enter your First Name
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="row mt-3 align-items-center">
                                    <div class="col-sm-12 col-md-3">
                                        <label class="form-label fs-6" for="validationUsername">Last Name</label>
                                    </div>
                                    <div class="col-sm-12 col-md-9">
                                        <div class="input-group">
                                            <span class="input-group-text"><i class="bi bi-person"></i></span>
                                            <input id="lastName" type="text" class="form-control form-control-sm"
                                                placeholder="Last Name *" name="lastName" required>
                                            <div class="invalid-feedback">
                                                Enter your Last Name
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="row mt-3 align-items-center">
                                    <div class="col-sm-12 col-md-3">
                                        <label class="form-label fs-6" for="email_id">Email</label>
                                    </div>
                                    <div class="col-sm-12 col-md-9">
                                        <div class="input-group">
                                            <span class="input-group-text"><i class="bi bi-envelope"></i></span>
                                            <input id="email_id" type="email" class="form-control form-control-sm"
                                                placeholder="Enter your mail Address *" name="email_id" required>
                                            <div class="invalid-feedback">
                                                Enter your Email id
                                            </div>
                                        </div>

                                    </div>
                                </div>
                                <div class="row mt-3 align-items-center">
                                    <div class="col-sm-12 col-md-3">
                                        <label class="form-label fs-6" for="password">Password</label>
                                    </div>
                                    <div class="col-sm-12 col-md-9">
                                        <div class="input-group">
                                            <span class="input-group-text"><i class="bi bi-lock"></i></span>
                                            <input id="password" type="password" class="form-control form-control-sm"
                                                placeholder="Enter Password *" name="password" required>
                                            <div class="invalid-feedback">
                                                Enter the Password
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="row mt-3 align-items-center">
                                    <div class="col-sm-12 col-md-3">
                                        <label class="form-label fs-6" for="confirm-password">Confirm
                                            Password</label>
                                    </div>
                                    <div class="col-sm-12 col-md-9">
                                        <div class="input-group">
                                            <span class="input-group-text"><i class="bi bi-lock-fill"></i></span>
                                            <input id="confirm_password" type="password"
                                                class="form-control form-control-sm" placeholder="Confirm Password *"
                                                name="confirm_password" required>
                                        </div>
                                    </div>
                                </div>

                                <div class="row mt-3 mb-1 text-center">
                                    <div class="col">
                                        <!-- <button class="btn btn-info form-control btn-sm" style="width: 70px;" type="submit">Register</button> -->
                                        <button class="reg-button" type="submit">Register</button>
                                    </div>
                                </div>
                            </form>
                            <div>
                                {% for message in messages %}
                                <script>
                                    message = "{{message | safe}}"
                                    message = message.replace(/'/g, '"')
                                    console.log(message, typeof (message))
                                    json_message = JSON.parse(message)
                                    console.log(json_message, typeof (json_message))
                                    if (json_message.for === "register" && json_message.type === "error") {
                                        Swal.fire({
                                            title: json_message.title,
                                            text: json_message.msg,
                                            icon: 'warning',
                                            showCloseButton: true,
                                            confirmButtonText: 'Close',
                                            focusConfirm: false,
                                        })
                                    }
                                </script>
                                <!-- <p class="fw-4 mt-1" style="color: rgb(255, 144, 144);">{{ message }}</p>
                                <br> -->
                                {% endfor %}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- <div class="row text-center mt-2">
        <div class="col-12">
            <p>Have already an account? <a class="link-info fw-semibold"
                    href="{% url 'login' %}">Login here</a></p>
        </div>
    </div> -->
    <div class="row justify-content-center">
        <div class="col-6 text-center">
            <div class="mt-4" style="text-align: center; border-top: 1px solid rgb(124, 124, 124)">
                <div
                    style="display: inline-block; position: relative; top: -13px; color:rgb(255, 255, 255); background-color: #ffffff;">
                    <p style="color:rgb(162, 179, 195)">OR SignUp With</p>
                </div>
            </div>

        </div>
    </div>


    <div class="row text-center mt-2 mb-4 justify-content-center">
        <div class="col-12">
            <a class="me-2" href="{% provider_login_url 'google' method = 'oauth2' %}"><img
                    src="{% static '/assets/images/google-icon.png' %}" style="width: 28px; height: 28px;"></a>
            <a class="me-2"><img src="{% static '/assets/images/facebook-icon.png' %}"
                    style="width: 28px; height: 28px;"></a>
            <a class="me-2"><img src="{% static '/assets/images/linkedin-icon.png' %}"
                    style="width: 31px; height: 31px;"></a>
            <a><img src="{% static '/assets/images/twitter-icon.png' %}" style="width: 31px; height: 31px;"></a>
        </div>
        <!-- <div class="col-3">
        </div>
        <div class="col-3">
        </div>
        <div class="col-3">
        </div> -->
    </div>

</div>

{% endblock %}

{% block script %}
<script src="{% static 'js/users_reg.js' %}"></script>
{% endblock %}

Here's the register method in views.py

views.py

...
from django.views.decorators.csrf import ensure_csrf_cookie

@ensure_csrf_cookie
def register(request: HttpRequest):
    if request.user.is_authenticated:
        print("User is already authenticated")
        return redirect(reverse("home"))

    if request.method == "GET":
        return render(request, os.path.join("static", "html", "register.html"))
    elif request.method == "POST":

        firstName = request.POST["firstName"]
        lastName = request.POST["lastName"]

        email_address = request.POST["email_id"]

        password = request.POST["password"]
        confirm_password = request.POST["confirm_password"]

        print(firstName)
        print(lastName)
        print(email_address)
        print(password)
        print(confirm_password)
        print()

        if password != confirm_password:
            # messages.error(request, "Passwords Didn't Match!!!")
            messages.error(request, {"for": "register", "type": "error",
                           "msg": "Passwords Didn't Match!!!", "title": "Account Creation Failed"})
            return redirect("register")

        User = get_user_model()

        if User.objects.filter(email=email_address).exists():
            # messages.error(request, "Email Already Taken")
            messages.error(request, {"for": "register", "type": "error",
                           "msg": "Email Already Taken", "title": "Account Creation Failed"})
            return redirect("register")

        user_document = {
            "firstName": firstName,
            "lastName": lastName,
            "mailAddress": email_address,
            "pw": bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()),
        }
        updated_user_document = setDocumentFields(user_document)
        insertion_id = store_user(updated_user_document)
        print(f"Insertion Id {insertion_id}")

        if (insertion_id == None):
            messages.info(request, "Cannot Create User")
            return redirect("register")

        UserModel = get_user_model()
        user = UserModel.objects.create(
            email=email_address, password=password, first_name=firstName, last_name=lastName)
        user.set_password(password)
        user.save()

        print("user created")

        return redirect("login")
...

Command to run django server :

$ python manage.py runserver 0.0.0.0:8000
Udesh
  • 2,415
  • 2
  • 22
  • 32
  • Are you accessing your website by IP address or domain name? If it's the latter, your domain name should be in `CSRF_TRUSTED_ORIGINS`. – aaron Mar 05 '23 at 08:05
  • I am using the ip address to access the website – Udesh Mar 05 '23 at 11:03
  • It isn't clear from the question, does your site work fine when you run it locally? – Igonato Mar 06 '23 at 06:57
  • Yes website works find in localhost I can navigate all files and register with new account as well as login but can't register or login when the application is on server. – Udesh Mar 06 '23 at 07:31
  • This might be a surprising question, but does it work in Firefox? – Gabor Lengyel Mar 06 '23 at 17:24
  • 1
    I have tested it in firefox as well as google chrome browsers and also tested after clearing my browser cache many times but it doesn't work. – Udesh Mar 07 '23 at 01:32
  • Removing these lines from the settings.py file fixed the csrf_token issue: `SECURE_REFERRER_POLICY = "no-referrer-when-downgrade" CSRF_COOKIE_SECURE = False SESSION_COOKIE_SECURE = False CSRF_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SAMESITE = 'None'` – Udesh Mar 07 '23 at 10:32
  • 1
    Without these settings, your website is vulnerable against CSRF attacks – ruddra Mar 07 '23 at 12:38
  • @ruddra We need to have these setting `CSRF_COOKIE_SECURE = False SESSION_COOKIE_SECURE = False` since this website as of now uses `http` not `https` if we set them to `True` these settings then we will get `csrf_token` error because they work with `https`. – Udesh Mar 08 '23 at 11:38

1 Answers1

0

A lot problems could raise when you use un-trusted origins to test your website. https://www.w3.org/TR/secure-contexts/#potentially-trustworthy-origin

Edit

I'm dumb, .localhost always points to 127.0.0.1. Please enable port 443 to use TLS to test your submit form instead, or use some free service like Ngrok to tunnel to your HTTP port. With NodeJS installed, you can run it with this 1-liner

npx ngrok http 3.110.170.248:8000

enter image description here

Đào Minh Hạt
  • 2,742
  • 16
  • 20
  • I have made the changes but it show's the website can't be reached when I visited to the link provided(http://sunfitek.localhost:8000/) – Udesh Mar 06 '23 at 07:38