本記事では、 Google OAuth2を用いてDjangoアプリでGoogle認証を行う際にメールバリデーションを設定する方法を紹介します。
Google認証ではsocial-auth-app-djangoというサードパーティーのパッケージを使用します。social-auth-app-djangoでGoogleログイン認証を設定する方法は以下を↓
この記事の目次
Pipelineについて
social-auth-app-djangoはpython-social-authをラップしているものですが、その中にpipelineという機能があります。
pipelineをカスタマイズすればsocial authの処理を変更したり、独自の処理を間に入れ込むことが可能です。
pipelineのソースコードはこちら↓
social-core/social_core/pipeline at master · python-social-auth/social-core
Python Social Auth - Core. Contribute to python-social-auth/social-core development by creating an account on GitHub.
pipelineはsettings.pyにSOCIAL_AUTH_PIPELINEという名前でタプルを作成することでオーバーライドが可能です。
pipelineを何も設定しない場合はデフォルトで以下のパイプラインが実行されます。
SOCIAL_AUTH_PIPELINE = (
'social_core.pipeline.social_auth.social_details',
'social_core.pipeline.social_auth.social_uid',
'social_core.pipeline.social_auth.auth_allowed',
'social_core.pipeline.social_auth.social_user',
'social_core.pipeline.user.get_username',
'social_core.pipeline.user.create_user',
'social_core.pipeline.social_auth.associate_user',
'social_core.pipeline.social_auth.load_extra_data',
'social_core.pipeline.user.user_details',
)
デフォルトでは初回認証成功時にsocial_auth_usersocialuserテーブルにプロバイダーに紐づくユーザーを作成します。
この処理が不要な場合は、以下の様にユーザー作成処理を削除することで処理を省くことができます。
SOCIAL_AUTH_PIPELINE = (
'social_core.pipeline.social_auth.social_details',
'social_core.pipeline.social_auth.social_uid',
'social_core.pipeline.social_auth.auth_allowed',
'social_core.pipeline.social_auth.social_user',
# 'social_core.pipeline.user.get_username', ←削除
# 'social_core.pipeline.user.create_user', ←削除
'social_core.pipeline.social_auth.associate_user',
'social_core.pipeline.social_auth.load_extra_data',
'social_core.pipeline.user.user_details',
)
メールバリデーション追加
今回はpipelineの初めに自作メールバリデーションを追加します。
入れる場所は目的に応じて変更してください。
SOCIAL_AUTH_PIPELINE = (
'views.validate_email', # メールバリデーション用のカスタムパイプライン
'social_core.pipeline.social_auth.social_details',
'social_core.pipeline.social_auth.social_uid',
'social_core.pipeline.social_auth.auth_allowed',
'social_core.pipeline.social_auth.social_user',
'social_core.pipeline.user.get_username',
'social_core.pipeline.user.create_user',
'social_core.pipeline.social_auth.associate_user',
'social_core.pipeline.social_auth.load_extra_data',
'social_core.pipeline.user.user_details',
)
設定したvalidate_email関数の中身は以下のように設定します。
from social_core.exceptions import AuthForbidden, AuthException
def validate_email(backend, details, response, *args, **kwargs):
# responseの中にemailキーが存在するかチェック
if not response or 'email' not in response:
raise AuthException(backend, 'email dose not exists')
# メールのドメインがhoge以外の場合エラー
domain = response['email'].split('@')[1]
if domain != 'hoge':
raise AuthForbidden(backend)
backendには認証するバックエンドが、responseには選択したアカウントの情報が入っています。
このように自作のパイプラインを設定することでsocial djangoの挙動を変更することが可能です。
是非一度試してみてください。