User Accounts With django-allauth – Building SaaS #41 · Matt Layman

1-ый вариант решения: обновить allauth до версии 0.36.0

В allauth версии 0.36.0 этот параметр добавили, поэтому обновите allauth до указанной версии и всё должно заработать.

2-ой вариант решения: переопределить vk провайдер

Если по каким-то причинам не хотите обновлять allauth, то вы можете и другим способом решеть проблему, добавив свой кастомный VK провайдер. Для этого нужно скопировать провайдер vk из приложения allauth (находится в allauth/socialaccount/providers/vk/) куда-нибудь в своё приложение, например, spec/providers/vk.

Добавляем в файле spec/providers/vk/views.py параметр ‘v’: ‘5.101’, в словарь params в функции complete_login класса VKOAuth2Adapter. Полный листинг приведён ниже:

Api creation and configuration:

Follow the below steps and seek out extra referees or tutorials on how to do this on the internet. A brief description is below.

Basic configuration

Most django-allauth features are can be configured using the built-in adapters and variables by placing them in the file settings.py. Although the documentation has tons of such options with good explanations, I have highlighted some important ones below.

Email confirmation expiry: Sets the number of days within which an account should be activated.

Eg: ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS=7

Email required for activation: This option allows you to set whether the email address should be verified to register. Set False to disable email requirement.

Eg: ACCOUNT_EMAIL_REQUIRED = True

Basic setup

You can download the files used in the tutorial to get a head start. The steps below guide you through the setup in detail.

  1. Create a Django project if you already don’t have one.

  2. Install django-allauth using the command pip install django-allauth

Add,allauthallauth.account, allauth.socialaccount and all the social login features you need to INSTALLED_APPS section in settings.py.

You can view the entire list of supported API’s here.

The social login feature is described later in the post. You can scroll down to that subheading if you would like to just read that. After you configure your installed apps section, it should be similar to the code given below.

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

Configure the template context processor settings in settings.py and also add the url pattern in the project’s urls.py.

TEMPLATES = [
  {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.normpath(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',
                'django.template.context_processors.request',
            ],
        },
    },
]

Add the following authentication backend.

Copy the template files from the django-allauth repository or you can also use my custom repository(I have made some modifications and some good structuring) and paste it in the folder templates in your project directory.

Add the allauth urls in urls.py of your main project directory. After adding the allauth urls the urls file should look similar to,

You can also add the custom CSS yourself or my CSS (Well commented and documented but simple) that I have created during my use of the allauth templates. It includes styling for almost all the pages, and even mobile-friendly email templates for confirmation and password reset emails.

Run python manage.py makemigrations and python manage.py migrate to make all the necessary migrations and run python manage.py runserver to start the django server.

Follow the URL patterns to display the registration form.Eg: Visit localhost:8000/accounts/login to display the login page.

Доверенный redirect uri

Во многих соц. сетях при добавлении приложения спрашивают про некий Доверенный redirect URI (или Действительные URL-адреса для перенаправления OAuth) например в ВК:

Доверенный redirect URI нужен для дополнительной защиты приложения от утечек токенов зарегистрировавшихся пользователей в следствие хакерских атак.

В django-allauthДоверенный redirect URI строится по следующему принципу:

Ошибка resp.json()[‘response’][0] keyerror: ‘response’ для vk провайдера

Данная ошибка возникает в версиях allauth ниже 0.36.0 из-за того, что ВКонтакте изменили api, сделав параметр v обязательным (v – версия api vk).

Extending the django-alluth class and advanced customizations

This section deals with customizing django-allauth signup forms, intervening in registration flow to add custom process and validations of your own.

Похожее:  Пишем чат бота для ВКонтакте на python с помощью longpoll / Хабр

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *