[PYTHON] Implement login function with django-allauth

Continuing from the previous session. http://qiita.com/yukidallas/items/9cd0ca5cda7f459533c3

django-allauth A library that makes it easy to implement social login on Django applications. https://github.com/pennersr/django-allauth

It seems that it currently supports the following social logins.

Installation

Add django-allauth to requirements.txt and pip install.

requirements.txt


django==1.11
django-allauth==0.31.0 #add to
django-extensions==1.7.8
mysqlclient==1.3.10

terminal


pip install -r requirements.txt -t libs

Register / login with email address

Add django admin and allauth to INSTALLED_APPS.

django-sample/settings.py


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.messages',
    'django.contrib.sessions',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'django_extensions',

    'allauth',
    'allauth.account'
]

AUTHENTICATION_BACKENDS = [
   'allauth.account.auth_backends.AuthenticationBackend'
]

Create a View class around registration / login.

django-sample/views.py


from allauth.account import views


class SigninView(views.LoginView):
    template_name = 'signin/index.html'

    def dispatch(self, request, *args, **kwargs):
        response = super(SigninView, self).dispatch(request, *args, **kwargs)
        return response

    def form_valid(self, form):
      return super(SigninView, self).form_valid(form)

signin_view = SigninView.as_view()


class SignupView(views.SignupView):
    template_name = 'signup/index.html'

    def get_context_data(self, **kwargs):
        context = super(SignupView, self).get_context_data(**kwargs)
        return context

signup_view = SignupView.as_view()

Create the corresponding template. Allauth also has a default template, but in most cases it is customized, so I prepared it separately. The code has copied what is in the allauth library.

templates/signin/index.html


{% block content %}
<form method="post" action="{% url 'account_login' %}">
{% csrf_token %}
{{form.as_p}}
<button type="submit">Sign In</button>
</form>
{% endblock %}

templates/signup/index.html


{% block content %}
<form method="post" action="{% url 'account_signup' %}">
  {% csrf_token %}
  {{ form.as_p }}
  {% if redirect_field_value %}
  <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />
  {% endif %}
  <button type="submit">Signup</button>
</form>
{% endblock %}

Add the routing.

django-sample/urls.py


urlpatterns = [
  url(r'^$', views.home_view),
  url(r'^auth/', include('allauth.urls')),
  url(r'^signin/?$', views.signin_view),
  url(r'^signup/?$', views.signup_view),
]

Access [http: // localhost: 8000 / signup](http: // localhost: 8000 / signup) and register as a user. You will be able to log in at [http: // localhost: 8000 / signin](http: // localhost: 8000 / signin).

You can't sign out as it is, so add View and routing.

django-sample/views.py


from django.shortcuts import redirect


class SignoutView(views.LogoutView):

    def get(self, *args, **kwargs):
        return self.post(*args, **kwargs)

    def post(self, *args, **kwargs):
        if self.request.user.is_authenticated():
            self.logout()
        return redirect('/')

signout_view = SignoutView.as_view()

django-sample/urls.py


urlpatterns = [
  # {...}
  url(r'^signout/?$', views.signout_view)
]

You will be able to sign out at [http: // localhost: 8000 / signout](http: // localhost: 8000 / signout).

SNS login with Twitter account

This time we will implement social login on Twitter. Please create an app with Twitter Developers in advance. It seems that you can't do it without registering your phone number. https://apps.twitter.com

Enter the required information in Create New App → Application Details. Set the following values in the Callback URL.

callback_url


http://localhost:8000/auth/twitter/login/callback/

Django will add settings around allauth.

django-sample/settings.py


INSTALLED_APPS = [
    # {...}
    'allauth.socialaccount',
    'allauth.socialaccount.providers.twitter'
]

Add a route to access Django admin.

django-sample/urls.py


# {...}
from django.contrib import admin
admin.autodiscover()

urlpatterns = [
  # {...}
  url(r'^admin/', include(admin.site.urls))
]

Create an account to log in to the management screen.

terminal


$ python manage.py createsuperuser

Go to [http: // localhost: 8000 / admin](http: // localhost: 8000 / admin) and log in.

Access SOCIAL ACCOUNTS> [social applications](http: // localhost: 8000 / admin / socialaccount / socialapp / add /) and make various settings.

After saving, log out from the management screen once and access [http: // localhost: 8000 / auth / twitter / login /](http: // localhost: 8000 / auth / twitter / login /) to jump to the Twitter link screen. You can log in (register) to SNS.

If you want to put a link on the screen, do as follows.

templates/home/index.html


<a href="/auth/twitter/login/">Login with Twitter</a>
<!--Or-->
<a href="{% url 'twitter_login' %}">Login with Twitter</a>

If you want to check around the routing like rails routes, use the following command. (django-extensions)

terminal


$ python manage.py show_urls

#abridgement
/auth/twitter/login/	allauth.socialaccount.providers.oauth.views.view	twitter_login	
/auth/twitter/login/callback/	allauth.socialaccount.providers.oauth.views.view	twitter_callback

To distinguish by whether you are logged in or not, do the following.

templates/home/index.html


{% if user.is_authenticated %}
<p>Hello{{ user.username }}Mr.</p>
{% else %}
<p>Please login</p>
{% endif %}

bonus

You can freely customize the model used for login.

terminal


$ cd ./django-sample/django-sample
$ python ../manage.py startapp accounts

django-sample/settings.py


INSTALLED_APPS = [
     # {...}
    'django-sample.accounts'
]

django-sample/accounts/models.py


from django.db import models
from django.contrib.auth.models import AbstractUser, UserManager


class User(AbstractUser):
    objects = UserManager()

    class Meta(object):
        app_label = 'accounts'

django-sample/settings.py


AUTH_USER_MODEL = 'accounts.User'

Migrate the database. If you get moss with migrate, you may want to delete the database and try again.

terminal


$ python manage.py makemigrations
$ python manage.py migrate

Finally

I have posted the source on Github (updated the previous one) https://github.com/yukidallas/django-sample

Recommended Posts

Implement login function with django-allauth
Easily implement login authentication function with Laravel
Implement large size stamp function with discordBOT
Implement FReLU with tf.keras
Twitter posting client made with Flask with simple login function
Try function optimization with Optuna
Implement subcommands with Python's argparse
Approximate sin function with TensorFlow
Implement timer function in pygame
Implement PyTorch + GPU with Docker
[QtDesigner] Implement WebView with PyQt5
Easy proxy login with django-hijack
Zura with softmax function implemented
Implement blockchain with about 60 lines
Login with django rest framework
[python3] Implement debug log output function easily with logging and Click
[LINE login] Verify state with Flask
Implement R's power.prop.test function in python
Set up social login with Django
Function parameters with only an asterisk'*'
Multilayer Perceptron with Chainer: Function Fitting
Easily implement subcommands with python click
Implementation of login function in Django
One-variable function approximation with four-layer DNN
Implement Keras LSTM feedforward with numpy
Login with PycURL and receive response
Use MULTI_ORG function with re: dash
Achieve Linux/dev/null with Windows system function
Implement "Data Visualization Design # 2" with matplotlib
Image upload function with Vue.js + Flask