見出し画像

Part2 Djangoのall-authライブラリでユーザー認証からソーシャルアカウントログイン

この記事はPart1 Djangoのall-authライブラリでユーザー認証からソーシャルアカウントログインの続きです。

独自テンプレートを準備する

自身でテンプレートを用意していればいつでも見た目の変更ができるので用意しましょう。

templatesフォルダの中にaccountフォルダを作り、その中に
login.html
logout.html
signup.html
verification_sent.html
email_confirm.html
password_reset.html
password_reset_done.html
password_reset_from_key.html
password_reset_from_key_done.html
を作りましょう。

ついでにtemplatesフォルダの中にsocialaccountフォルダも作りましょう。

templates/account/login.html

{% extends 'base.html' %}

{% block content %}
<h1>ログイン</h1>
<form method="post">
 {% csrf_token %}
 {{ form.as_p }}
 <button type="submit">ログイン</button>
 <p><a class="button" href="{% url 'account_reset_password' %}">パスワードをお忘れですか?</a></p>
 <p><a class="button" href="{% url 'index' %}">トップページへ</a></p>
</form>
{% endblock %}

スクリーンショット 2021-01-06 16.51.03

templates/account/logout.html

{% extends 'base.html' %}

{% block content %}
 <h1>ログアウト</h1>
 <form method="post" action="{% url 'account_logout' %}">
   {% csrf_token %}
   {% if redirect_field_value %}
   <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}"/>
   {% endif %}
   <button type="submit">ログアウト</button>
 </form>
{% endblock %}

スクリーンショット 2021-01-06 18.45.00

templates/account/signup.html

{% extends 'base.html' %}

{% block content %}
 <h1>新規登録</h1>
   <form method="post">
     {% csrf_token %}
     {{ form.as_p }}
     <button type="submit">登録</button>
  </form>
 <a href="{% url 'account_login' %}">ログイン</a>
 <p><a class="button" href="{% url 'index' %}">トップページへ</a></p>

{% endblock %}

スクリーンショット 2021-01-06 16.50.57

templates/account/verification_sent.html

{% extends 'base.html' %}

{% block content %}
   <h1>確認メールを送信しました</h1>

   <p>受信ボックスを確認してください。</p>

{% endblock %}

スクリーンショット 2021-01-09 14.59.40

templates/account/email_confirm.html

{% extends 'base.html' %}

{% load account %}

{% block content %}
<h1>メールアドレスの確認</h1>

{% if confirmation %}

{% user_display confirmation.email_address.user as user_display %}

<p>{{ user_display }}様、以下のメールアドレスが正しければ確認をクリックしてください。<a href="mailto:{{ confirmation.email_address.email }}">{{ confirmation.email_address.email }}</a></p>

<form method="post" action="{% url 'account_confirm_email' confirmation.key %}">
{% csrf_token %}
   <button type="submit">確認</button>
</form>

{% else %}

{% url 'account_email' as email_url %}

<p>このメールアドレスの認証期限が過ぎました。もう一度<a href="{{ email_url }}"></a></p>

{% endif %}

{% endblock %}

スクリーンショット 2021-01-11 18.43.47

templates/account/password_reset.html

{% extends 'base.html' %}

{% block content %}
 <h1>パスワード再設定</h1>
   {% if user.is_authenticated %}
     {% include "account/snippets/already_logged_in.html" %}
   {% endif %}

 <p>パスワードをお忘れですか? メールアドレス入力後、パスワードリセットメールをお送りします</p>

 <form method="POST" action="{% url 'account_reset_password' %}" class="password_reset">
   {% csrf_token %}
   {{ form.as_p }}
   <input type="submit" value="送信" />
 </form>

{% endblock %}

スクリーンショット 2021-01-06 16.51.10

templates/account/password_reset_done.html

{% extends 'base.html' %}
{% block content %}
 <h1>パスワード再設定</h1>
 <p>パスワード再設定用のメールを送信しました。<br>
 メール受信箱をご確認ください。</p>
{% endblock %}

スクリーンショット 2021-01-06 16.51.27

templates/account/password_reset_form_key.html

{% extends 'base.html' %}

{% block content %}
 <h1>{% if token_fail %}不正なトークンです{% else %}パスワード変更{% endif %}</h1>

 {% if token_fail %}
   {% url 'account_reset_password' as passwd_reset_url %}
   <p>このリンクは既に使用されています。<a href="{{ passwd_reset_url }}">パスワードリンクを再発行する</a></p>
 {% else %}
   {% if form %}
     <form method="POST" action="{{ action_url }}">
       {% csrf_token %}
       {{ form.as_p }}
       <input type="submit" name="action" value="変更"/>
     </form>
   {% else %}
     <p>あなたのパスワードは変更済みです</p>
   {% endif %}
 {% endif %}
 
{% endblock %}

スクリーンショット 2021-01-06 16.51.37

templates/account/password_reset_from_key_done.html

{% extends 'base.html' %}

{% block content %}
 <h1>パスワードの変更が完了しました。</h1>
 <p>ログインしてください。<a href="{% url 'account_login' %}">ログイン</a></p>
{% endblock %}

スクリーンショット 2021-01-06 16.51.51

templates/socialaccount/signup.html

{% extends "base.html" %}

{% block content %}
   <h1>新規登録</h1>

<p>あなたは "{{account.get_provider.name}}"アカウントを使ってログインします。下のフォームを入力してください。
"{{site.name}}"</p>

<form class="signup" id="signup_form" method="post" action="{% url 'socialaccount_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">新規登録 &raquo;</button>
</form>

{% endblock %}

見栄えもすっきりしました。

ソーシャルアカウントでログイン

今回はgoogleを使用してログインしていきます。

まずはsettings.pyにallauth.socialaccount.providers.googleを追加します。

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

ログインページにgoogle用のリンクをセットします。

templates/account/login.html

{% extends 'base.html' %}

{% block content %}

{% load account socialaccount %}

{% get_providers as socialaccount_providers %}

{% if socialaccount_providers %}

  <div class="socialaccount_ballot">

    <ul class="socialaccount_providers">
      {% include "socialaccount/snippets/provider_list.html" with process="login" %}
    </ul>

  </div>

{% include "socialaccount/snippets/login_extra.html" %}

{% else %}
<p>まだアカウントをお持ちでない方は<a href="{{ account_signup_url }}">新規登録</a>してください</p>
{% endif %}

<h1>ログイン</h1>
<form method="post">
 {% csrf_token %}
 {{ form.as_p }}
 <button type="submit">ログイン</button>
</form>
<p><a class="button" href="{% url 'account_reset_password' %}">パスワードをお忘れですか?</a></p>
<p><a class="button" href="{% url 'index' %}">トップページへ</a></p>
{% endblock %}

スクリーンショット 2021-01-06 18.50.28

includeで読み込んでいる socialaccount/snippet/はallauthライブラリが既に持っています。編集したい人はファイル名をコピーして編集しましょう。
githubページで全ての詳細が確認できます。
allauthのgithubページ

Google Cloud Platformの設定

Google Cloud Platform(GCP)はgoogleアカウントを持っている人はすぐに使えますが、持っていない人はGoogleアカウントを作りましょう。

Google認証するにはgoogle APIの設定が必要になります。
設定が完了するとClient idSecret keyが発行されるのでそれをDjangoに登録します。

GCPにアクセスするために次のリンクをクリックしましょう。

個々によって多少ページの表示に違いがあると思いますが、赤枠をクリックして新しいプロジェクトを作ります。

画像の文字は全て英文になっていますが、わかりにくい方は一番左にあるアイコンを見て行うことをお勧めします。

スクリーンショット 2021-01-08 10.23.56

NEW PROJECTをクリック

スクリーンショット 2021-01-08 10.24.11

プロジェクト名はデフォルトでも自身でわかりやすい名前を付けてもらっても構いません。LocationはNo organizationで大丈夫です。

CREATEをクリックしたらプロジェクトの完成です。

スクリーンショット 2021-01-08 10.30.09

ダッシュボード画面に戻ってきたら先ほど作ったプロジェクト(My Project 31167)に移動もしくは既に移動されています。(API とサービス)そのページのCredentialsをクリックします。

スクリーンショット 2021-01-08 10.38.03

+CREATE CREDENTIALS → OAuth client IDをクリックします。

スクリーンショット 2021-01-08 10.38.30

Configure consent screen をクリックします。

スクリーンショット 2021-01-08 10.42.47

External → CREATE

スクリーンショット 2021-01-08 10.42.58

App nameUser support emailを入力します。

スクリーンショット 2021-01-08 10.48.01

Application home pageはローカルのhttp://127.0.0.1:8000を入力します。
Developer contact informationにメールアドレスを入力してSAVE AND CONTINUE をクリックします。

スクリーンショット 2021-01-08 10.48.14

そしてScopesTest user何も入力せずにSAVE AND CONTINUEをクリックします。

スクリーンショット 2021-01-08 10.56.26

最後のSummaryでBACK TO DASHBOARD をクリックします。

スクリーンショット 2021-01-08 10.56.40

ダッシュボードに戻り再びCredentialsをクリックします。

スクリーンショット 2021-01-08 11.04.40

そして+CREATE CREDENTIALS → OAuth client IDをクリックします。

スクリーンショット 2021-01-08 11.05.21

Application typeをWeb applicationにして、 Nameに任意の名前を入力します。  Authorized redirect URIsのURIsにallauthライブラリが指定しているURIsを貼り付けます。http://127.0.0.1:8000/accounts/google/login/callback/
以下のページで確認できます。
https://django-allauth.readthedocs.io/en/latest/providers.html#google
最後に画像には写っていませんが一番下のCREATINGボタンをクリックします。

スクリーンショット 2021-01-08 11.10.37

これでClient idSecret keyが取得できました。

スクリーンショット 2021-01-08 17.02.54

Client idとSecret keyをDjangoに保存

admin画面を開き外部アカウントのsocial applicationをクリックします。
そして、画面右上のsocial application を追加をクリックして中身を入力します。

名前の項目に好きな名前を入力し取得し、先ほど取得したClient idとSecret keyを入力しSitesも右の枠に移動させ保存ボタンをクリックします。

スクリーンショット 2021-01-08 17.24.27

保存後の表示画面。

スクリーンショット 2021-01-08 17.23.47

これでDjangoにClient idとSecret keyを保存することができました。

APIを有効にする

取得したClient idとSecret keyをDjangoに保存したら、google APIを有効にしておきます。※既に有効にしている人はこの手順を飛ばしてください。

GCPの画面に戻り画面左サイドバーのDashboardをクリックします。

スクリーンショット 2021-01-08 17.09.13

ENABLE AND SERVICESをクリックします。

スクリーンショット 2021-01-08 17.09.56

検索バーに "google plus" と入力したらGoogle APIが表示されるのでクリックします。

スクリーンショット 2021-01-08 17.11.18

ENABLEをクリックしたらAPIが使用できます。

スクリーンショット 2021-01-08 17.11.33

これで全ての準備が整いました。

Google認証の確認

ターミナルでサーバーを起動させます。

python manage.py runserver

ログインしている人はログアウトしてログインページに遷移します。

スクリーンショット 2021-01-08 17.40.21

使用したいGoogleアカウントを選択します。

スクリーンショット 2021-01-08 17.41.29

既にアカウントを持っている人はそのまま下のページのように簡単にログインできます。

スクリーンショット 2021-01-08 17.59.17

最後に

2回に分けてallauthを使用したDjangoの認証を解説しました。
allauthは様々なアカウントでログインできるので試してみてください。
あとpart1で作ったカスタムユーザーモデルでいろいろフィールドを追加するともっと幅が広がります。

この記事が気に入ったらサポートをしてみませんか?