Djangoでtwitterログインするのにdjango-social-authが便利

railsアプリでtwitterログインさせるのにomniauthというライブラリをつかってたことがありまして、Djangoではどんなライブラリがあるのかなーと思って探してみたところ、django-social-authというのがよさそうだったので試してみました。

omniauth
https://github.com/intridea/omniauth

django-social-auth
https://github.com/omab/django-social-auth

インストール

pip install django-social-auth

使ってみたときのメモ

Djangoアプリを作成したらsettings.pyにいろいろ設定を追加します
Twitterログインのことだけ考えてます

# 抜粋

INSTALLED_APPS = (
    #...
    'social_auth', # <-  追加
)


# 以下追加

AUTHENTICATION_BACKENDS = (
    'social_auth.backends.twitter.TwitterBackend',
    # 他にもいろいろ
    )

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    "django.core.context_processors.tz",
    "django.contrib.messages.context_processors.messages",
    'social_auth.context_processors.social_auth_by_type_backends') 


TWITTER_CONSUMER_KEY              = '*******************'
TWITTER_CONSUMER_SECRET           = '******************************************'

LOGIN_URL          = '/login/'
LOGIN_REDIRECT_URL = '/'
LOGIN_ERROR_URL    = '/login-error/'


urls.pyに1行追加します

urlpatterns = patterns('',
    #...
    url(r'', include('social_auth.urls')),

)

設定はこれだけです。
あとはテンプレートにログイン用のリンクを作ればログインできるようになります

<a href="{% url socialauth_begin 'twitter' %}">Twitter login</a>


ログインするとDjangoのUserモデルが作成されます。request.userで参照できます。
また、ライブラリが用意しているUserSocialAuthというモデルも作成されます。

UserSocialAuthのtokensというプロパティでoauth_token_secretとoauth_tokenが取得できますので、それを使ってapiアクセスができます

以下はログインしてる場合はtweepyを使ってapiにアクセスして、プロフィールの画像のパスをコンテキストに設定して返す例です

def index(request):
    ctx = {}

    if request.user.is_authenticated():
         auth = UserSocialAuth.objects.filter(user=request.user).get()

         print auth.tokens
         # => {u'oauth_token_secret': u************************************', u'oauth_token': u'***********************************'}

         handler = tweepy.OAuthHandler(settings.TWITTER_CONSUMER_KEY, settings.TWITTER_CONSUMER_SECRET)
         handler.set_access_token(auth.tokens["oauth_token"],
                             auth.tokens["oauth_token_secret"])
         api = tweepy.API(auth_handler=handler)

         ctx.update({"image_url": api.me().profile_image_url})

    return render_to_response('app/index.html', ctx, RequestContext(request))


djangoのUserモデルを使ってるので、login_requiredとかも使えるはずですし、何よりログインできるまでがあっというまにできるので便利です