utamaro’s blog

誰かの役に立つ情報を発信するブログ

DjangoでGoogleアカウントの認証機能を入れる方法

Djangoのログイン機能でGoogleのアカウントを使った方法を入れます。

必要なライブラリをインストールします。

pip install django python3-openid social-auth-app-django

(ついでにherokuで必要なライブラリも入れたい場合は↓をどうぞ)

pip install django djangorestframework psycopg2 psycopg2-binary whitenoise dj-database-url gunicorn python3-openid social-auth-app-django

urls.py

from django.contrib import admin
from django.contrib.auth.views import LogoutView, LoginView
from django.urls import path, include
from django.views.generic import TemplateView

urlpatterns = [
    path('admin/', admin.site.urls),
    # ↓ ログイン用の画面
    path('login/', LoginView.as_view(template_name='top.html'), name='login'),
    # ↓ ログアウトしたあとの画面
    path('logout/', LogoutView.as_view(), name='logout'),
    # トップ画面
    path('', TemplateView.as_view(template_name='top.html'), name='home'),
    # ↓ socialログインに必要なpath
    path('auth/', include('social_django.urls', namespace='social')),
]

次にtemplatesディレクトリに以下のようにファイルを作成します。

Project/templates
├── registration
│   └── logged_out.html
└── top.html

registration以下にlogged_out.htmlを作成している理由について。

Logoutviewのtemplate_nameにそのように指定されているからです。(デフォルト)

もちろん、.as_view(template_name='logout.html')のように書き換えても良いです。

class LogoutView(SuccessURLAllowedHostsMixin, TemplateView):
    """
    Log out the user and display the 'You are logged out' message.
    """
    next_page = None
    redirect_field_name = REDIRECT_FIELD_NAME
    template_name = 'registration/logged_out.html'
    extra_context = None

settings.py

以下の設定を追加します。

LOGIN_URL = 'login'  # urls.pyで設定したnameに一致するように
LOGIN_REDIRECT_URL = 'home'  # urls.pyで設定したnameに一致するように

# ↓ はgoogleから取得すること。
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'xxxxxxxxxxxx.apps.googleusercontent.com'  #Paste CLient Key
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'xxxxxxxxxxxx' #Paste Secret Key

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,  'templates')],  # ← を追加
        # ry...
    },
]

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'social_django',  # ← を追加
]

AUTHENTICATION_BACKENDS = (
    # 'social_core.backends.open_id.OpenIdAuth',  # for Google authentication
    # 'social_core.backends.google.GoogleOpenId',  # for Google authentication
    'social_core.backends.google.GoogleOAuth2',  # for Google authentication
    # 'social_core.backends.github.GithubOAuth2',  # for Github authentication
    # 'social_core.backends.facebook.FacebookOAuth2',  # for Facebook authentication

    'django.contrib.auth.backends.ModelBackend',
)

html

top.html

top画面では、ログインするためのボタンと、ログアウトするためのボタンを用意します。

それぞれのボタンは、ユーザがログインしているかどうかで表示されるかが決まります。

<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="utf-8">
        <title>Sample</title>
        <meta name="description" content="google login project">

        {% load static %}
    </head>
    <body class="">
        {% if user.is_authenticated %}
            <a href="{% url 'logout' %}">
                <span>ログアウト</span>
            </a>
        {% else %}
            <a href="{% url 'social:begin' 'google-oauth2' %}">
                <span>ログイン</span>
            </a>
        {% endif %}
    </body>
</html>

logged_out.html

めんどくさいので簡単に作りました。

ログアウト実行後の画面です。

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Logout</title>
    </head>
    <body>
        <p class="display-4">You logged out.</p>
        <a class="lead" href="{% url 'home' %}">Home</a>
    </body>
</html>

備考

わざわざlogged_out.htmlを作らなくても、以下の方法でも良いです。

settingsファイルにLOGOUT_REDIRECT_URLを設定しても良いです。

LOGOUT_REDIRECT_URL = 'home

あるいは、urls.pyでnext_pageを指定しても良いです。

path('logout/', LogoutView.as_view(next_page='home'), name='logout'),