尝试注册到 Django 网站时,请禁止访问(未设置 CSRF cookie。):/users/register

问题描述 投票:0回答:0

该网站是实时的并且托管在远程服务器(aws ec2)上但是当我尝试注册到该网站时出现错误。

注册网站时出错

我已经浏览过之前的 SO 帖子,但他们没有帮助我修复:

设置.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

我已经在本地机器上对它进行了彻底的测试,它工作正常但在服务器上部署时失败了。

我无法注册到网站,它一直在生成

csrf_token
未设置。

我在

register.html
文件的
{% csrf_token %}
标签内添加了form

注册.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/[email protected]/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 %}

这里是views.py中的register方法

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")
...

运行django服务器的命令:

$ python manage.py runserver 0.0.0.0:8000

Website URL
http://3.110.170.248:8000/

python django csrf django-csrf
© www.soinside.com 2019 - 2024. All rights reserved.