Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Signing Up and Signing In: Users in Django with Django-AllAuth

Signing Up and Signing In: Users in Django with Django-AllAuth

Presented to the boston django meetup 4/26/2013.

Overview of the User Registration space in django, comparison of django-allauth, django-registration, django-social-auth, and django-userena, demonstration of adding facebook login to a site using django-allauth.

tedtieken

April 26, 2013
Tweet

More Decks by tedtieken

Other Decks in Technology

Transcript

  1. View Slide

  2. Have you met Ted?
     Technical founder of SittingAround.com
     Full stack developer
     except the adobe products
     Using Django since 1.0.2
     ~4.5 years
     @tedtieken (not very active)

    View Slide

  3. Problem
    We have an app that lets audience members of a django
    meetup submit and vote on questions they’d like the
    speaker to answer.
    Anyone can upvote any question as many times as they
    want, so it is being trolled

    View Slide

  4. View Slide

  5. Problem
    We have an app that lets audience members of a Django
    meetup talk submit and vote on questions
    Anyone can upvote any question as many times as they
    want, so it is being trolled
    If we added user accounts, we could restrict people to only
    voting on each question once.

    View Slide

  6. Problem
    http://q4ts.herokuapp.com/
    Turn Kevin Harvey’s Torquemada app from January testing
    meetup into user-enabled clone QuestionsForTheSpeaker

    View Slide

  7. 1. Overview of Users & Auth
    2. Community Packages
    3. Example FB Integration
    Signing Up and Signing In
    User Registration, Authentication, and Social
    Authentication with Django

    View Slide

  8. 1. Overview of Users & Auth
    2. Community Packages
    3. Example FB Integration
    Signing Up and Signing In
    User Registration, Authentication, and Social
    Authentication with Django

    View Slide

  9. Why Accounts?
     Anonymous users are particularly poorly behaved
     You need them to build the next socialbookspace
     Users expect customization & interaction
     Most interesting things you’re going to want to do with
    a webapp are going to require tying things to users
     $$$
     Active users is an easy valuation metric
     Done well, sign up and sign in can drive a lot of value

    View Slide

  10. User Stack: Base
    User Model
    Password Security
    Standard User anchor point
    django.contrib.auth
    django.contrib.auth:
     Basic user fields (email, name, password
    hash)
     Password hashing
     Standard user model used throughout
    your app and other apps (e.g. admin)
     …

    View Slide

  11. User Stack: Authentication
    User Model
    Password Security
    Standard User anchor point
    django.contrib.auth
    User Registration & Login
    Authentication
    Authentication:
     Who is it?
     Verify identity using a
    username/password combo

    View Slide

  12. User Stack: Authorization
    User Permissions
    Authorization
    Authorization:
     Is this user allowed to do that?
     Is this user logged in or anonymous?
    User Model
    Password Security
    Standard User anchor point
    django.contrib.auth

    View Slide

  13. User Stack: Profiles
    User Model
    Password Security
    Standard User anchor point
    django.contrib.auth
    Profile:
     What is your favorite color?
     What is your quest?
     Both “facebook style” and “hidden”
     Pre 1.5, your user_profile model
     Post 1.5, user_profile model or
    extended User model
    Extended User Attributes
    Profile

    View Slide

  14. User Permissions
    Authorization
    The User Stack with Django
    Extended User Attributes
    User Registration & Login
    Authentication Profile
    User Model
    Password Security
    Standard User anchor point
    django.contrib.auth

    View Slide

  15. Your Responsibility
    django.contrib.auth
    Division of Labor
    Authorization
    Authentication Profile

    View Slide

  16. What Django handles
     Salts & hashes user passwords
     Standard User model
     Handles sessions, setting cookies
     View logic for common user operations:
     Login, logout, password reset, lost-password recovery
     But not the templates
    django.contrib.auth library comes bundled with Django

    View Slide

  17. What Django handles
     Utilities for customizing experience for logged in users vs
    anonymous site visitors
     @login_required view decorator with redirect
     request.user.is_authenticated()
     User model integrated into admin for both staff access
    and end-user searching
     Salts & hashes user passwords
    django.contrib.auth library comes bundled with Django

    View Slide

  18. This is important:
    Salting and Hashing

    View Slide

  19. Salting and Hashing
    Django does the right thing with user passwords, so you
    can’t shoot yourself in the foot
     Salting is: adding characters to the user’s password
     Salting is: Important for user security
     Hashing is: using one-way math to obfuscate stored pw
     Hashing is: Important for user security
     Django does this for you, so you can’t it would be hard
    for you to shoot yourself in the foot.
     Not every framework does this.

    View Slide

  20. View Slide

  21. Back to our regularly
    scheduled programming

    View Slide

  22. What Django almost handles
     Permissions Model: Handles basic binary permissions,
    but not object permissions
     It does do: User can create news stories
     It does do: User can edit news stories
     It doesn’t do: User can edit own news stories
     Group Model: Provides a grouping model
     Useful in providing grouped permissions to staff
     Not a very good fit for end-user groupings
    Built in perms & groups work well for staff, but little else.

    View Slide

  23. What Django leaves to you
    Auth module is focused on doing a few critical things very
    well, leaves out a lot of common use cases
     Password strength checking
     Throttling of login attempts
     i.e. locking an account after 5 failed passwords
     Two-Factor authentication
     Email verification

    View Slide

  24. What Django leaves to you
    You have to roll your own or use community libraries to
    actually sign up end users
     Registration is up to you
     Authentication against third-parties
     e.g. Facebook Connect or Oath
     Some people try to hack admin to do end-user
    Registration and Login
     Don’t try to use admin for end-user stuff
     It’s built for staff use
     Opens up security holes
     It only takes a few minutes to do it the right way

    View Slide

  25. 1. Overview of Users & Auth
    2. Community Packages
    3. Example FB Integration
    Signing Up and Signing In
    User Registration, Authentication, and Social
    Authentication with Django

    View Slide

  26. Back to our problem
    We need to implement user accounts, and would like to
    integrate with FB
    Should we roll our own or use a community library?
    If library, which one should we use?

    View Slide

  27. Our Focus Today
    Extended User Attributes
    e.g. Favorite color
    User Permissions
    User Model
    django.contrib.auth
    User Registration & Login
    Authorization
    Authentication Profile

    View Slide

  28. Our Focus Today
    Extended User Attributes
    e.g. Favorite color
    User Permissions
    3rd Party / Social
    User Model
    django.contrib.auth
    Internal to your App
    Authorization
    Authentication Profile

    View Slide

  29. DjangoPackages.com
    First stop when evaluating community packages

    View Slide

  30. DjangoPackages.com
     Thematic groupings
     Authentication, Auth, Payments, Pagination, etc.
     Well formatted, easily digestible grid
     Popularity Indicators (# Repo Watchers)
     Feature comparisons (in some groups)
     Last updated & Activity indicators
    First stop when evaluating community packages

    View Slide

  31. Authentication Packages
     50 packages!
     Lets try to process that and make the decision a little
    easier

    View Slide

  32. Survey Says
     Survey trying to find out: what are people actually using
     93 starts, 85 complete responses
     Sample drawn from
     Boston Django Meetup
     django-users mailing list
     r/django reddit
     Collected over two months: February thru March ‘13

    View Slide

  33. Experience level
    31.20%
    36.60%
    32.30%
    3+ years
    1 or 2ish years (6-32 months)
    Just Started (<6 months)
    How long have you been using Django?

    View Slide

  34. Past Use & Awareness
    0 50 100 150
    Other
    Roll your own
    django-allauth
    django-userena
    Larger framework*
    django-social-auth
    django-registration
    Have used this package
    Would Use
    Have evaluated this
    package
    Aware of this package
    * e.g. Pinax, Mezzanine
    Which packages have you considered, evaluated, or used?

    View Slide

  35. Future Use
    * e.g. Pinax, Mezzanine
    If you were starting a new project, what would you use?
    0.00% 10.00% 20.00% 30.00% 40.00% 50.00%
    Other
    Roll your own
    django-allauth
    django-userena
    Larger framework*
    django-social-auth
    django-registration

    View Slide

  36. What’s gaining?
    * e.g. Pinax, Mezzanine
    Would use in new project / Have used in past
    0% 25% 50% 75% 100% 125% 150%
    Other
    Roll your own
    django-allauth
    django-userena
    Larger framework*
    django-social-auth
    django-registration

    View Slide

  37. http://tinyurl.com/djangoauth
    View the results yourself

    View Slide

  38. Lets take a look at some
    libraries

    View Slide

  39. Stack map shorthand
    Extended User
    Attributes
    e.g. Favorite color
    User Permissions
    3rd Party / Social
    Internal to your
    App
    Authorization
    Authentication Profile
    User Model
    django.contrib.auth
    django-registration
    The django-registration package handles local user account creation and
    sign-in only. It doesn’t touch the Authorization, Profile, or Social
    Authentication parts of the problem.

    View Slide

  40. Where do they specialize?
    Package Specialty Stack
    django-registration  Local user accounts
     Email activation

    View Slide

  41. Where do they specialize?
    Package Specialty Stack
    django-social-auth  3rd Party/social accounts
     Multiple 3rd party accounts

    View Slide

  42. Where do they specialize?
    Package Specialty Stack
    django-allauth  Local and/or social accounts
     Multiple 3rd party accounts
     Multiple emails
     Require email even w/ social

    View Slide

  43. Where do they specialize?
    Package Specialty Stack
    django-userena  Local user accounts
     Email activation
     (semi)public user profiles
     User-to-user messaging

    View Slide

  44. Where do they specialize?
    Package Specialty Stack
    django-registration  Local user accounts
     Email activation
    django-social-auth  3rd Party/social accounts
     Multiple 3rd party accounts
    django-allauth  Local and/or social accounts
     Multiple 3rd party accounts
     Multiple emails
     Require email even w/ social
    django-userena  Local user accounts
     Email activation
     (semi)public user profiles
     User-to-user messaging

    View Slide

  45. Recommendation
    django-allauth
    Pro
     It.Just.Works
     Templates included
     Social w/ verified email
     Multiple emails
     Handles full authentication problem
     Without creep into other areas
     Rapidly gaining traction, maturing
     Well tested
     Easily add new backends
    Con
     Puts site-tokens in the database
     Documentation has a few gaps
     More “magic”

    View Slide

  46. Second Place
    django-registration
    +
    django-social-auth
    Pro
     Most popular combo
     Established
     Well tested
     Lots of existing social-auth-backends
     Djangopackages has grid for them
     Easily add new backends
     Social-auth pipeline = customization
    Con
     Have to roll your own templates
     Hard for newcomers
     Will take longer
     Glue work needed
     On your own for corner cases
     i.e. need email for social
    accounts verified
     Documentation is complained
    about in both

    View Slide

  47. Beware
    django-social-auth
    django-socialauth
    We’ve been talking about this one

    View Slide

  48. 1. Overview of Users & Auth
    2. Community Packages
    3. Example FB Integration
    Signing Up and Signing In
    User Registration, Authentication, and Social
    Authentication with Django

    View Slide

  49. Back to our Problem
    We’re going to add user accounts, and signup via facebook.
    We’ve decided that AllAuth looks like a good package, so
    we’re going to go with that
    We’ve already got our non-user enabled app, which we
    downloaded from github.com/kcharvey/testing-in-django

    View Slide

  50. Getting Started with AllAuth
    1. pip install django_allauth
    2. Goto https://github.com/pennersr/django-allauth
    3. Follow the instructions
    4. Grab a beer

    View Slide

  51. Getting Started with AllAuth
    1. pip install django_allauth
    2. Goto https://github.com/pennersr/django-allauth
    3. Follow the instructions
    4. Grab a beer
    It is almost this easy

    View Slide

  52. Mature
    Rapidly Maturing

    View Slide

  53. Mature
    Rapidly Maturing
    Even with the remaining bumps,
    it’s the easiest social auth package to use

    View Slide

  54. Configuring AllAuth: Settings.py
    TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    "django.core.context_processors.request",
    ...
    "allauth.account.context_processors.account",
    "allauth.socialaccount.context_processors.socialaccount",
    ...
    )
    AUTHENTICATION_BACKENDS = (
    ...
    "django.contrib.auth.backends.ModelBackend",
    #allauth authentication methods (i.e. login by e-mail)
    "allauth.account.auth_backends.AuthenticationBackend",
    ...
    )

    View Slide

  55. Configuring AllAuth: Settings.py
    INSTALLED_APPS = (

    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.facebook',
    #Other providers as you want
    )
    SOCIALACCOUNT_PROVIDERS = \
    { 'facebook':
    { 'SCOPE': ['email'],
    'AUTH_PARAMS': { 'auth_type': 'reauthenticate'},
    'METHOD': 'oauth2' ,
    'LOCALE_FUNC': lambda request: return ‘en_US’},
    }

    View Slide

  56. Decide what flow you want
    Settings.py
    ACCOUNT_AUTHENTICATION_METHOD = "username"
    ACCOUNT_EMAIL_REQUIRED = True
    ACCOUNT_EMAIL_VERIFICATION = "optional"
    ACCOUNT_EMAIL_SUBJECT_PREFIX = "[q4ts]"
    ACCOUNT_PASSWORD_MIN_LENGTH = 6
     This step is optional, ships with reasonable defaults
     Most common flows are configurable by default
     Full list at https://github.com/pennersr/django-allauth

    View Slide

  57. Configuring AllAuth: Urls.py
    urlpatterns = patterns('',
    ...
    (r'^accounts/', include('allauth.urls')),
    ...
    #The profile isn’t free with allauth
    #This is a good thing
    (r'^accounts/profile/', YOUR_OWN_PROFILE_VIEW),
    ...
    )

    View Slide

  58. This gets the following URLS

    View Slide

  59. Configuring AllAuth Templates

    View Slide

  60. Configuring AllAuth Templates
     Optional
     Override if you want/need to
     But you don’t have to: It.just.works out of the box

    View Slide

  61. Register your app w/ Facebook

    View Slide

  62. Register your app w/ Facebook
     https://developers.facebook.com/apps/
     Create an app
     Record your keys in the database
     Secrets in db. Doh!
     Biggest complaint with allauth

    View Slide

  63. Register your app w/ Facebook

    View Slide

  64. Register your app w/ Facebook

    View Slide

  65. Register your app w/ Facebook

    View Slide

  66. Record keys in the database

    View Slide

  67. Record keys in the database

    View Slide

  68. Make it work locally: two apps

    View Slide

  69. Remember to turn off sandbox

    View Slide

  70. Add links to to base.html
    {% load url from future %}
    {% load socialaccount %}
    Sign Up
    Log in

    Sign Up / Login with Facebook

    View Slide

  71. http://q4ts.herokuapp.com/accounts/facebook/login/?method=oauth2
    http://q4ts.herokuapp.com/accounts/facebook/login/callback/?code=##&state=##

    View Slide

  72. Show apt links for user state
    {% if user.is_authenticated %}
    Log out
    My Account
    {% else %}
    Sign Up
    Log in
    Facebook Connect
    {% endif %}

    View Slide

  73. Profile view & templates
     Sorry, you’re still on your own for this one.
     But, the hard work has already been done
     Short on time?
     My Account
     ul > li
     username
     email + manage email link
     linked social accounts + manage social accounts link
     password change links
     logout link

    View Slide

  74. New Decorator
    from django.contrib.auth.decorators import login_required
    @login_required
    Def authenticated_users_only_view(request):
    ...
    from allauth.account.decorators import verified_email_required
    @verified_email_required
    def verified_users_only_view(request):
    ...

    View Slide

  75. Go do interesting things

    View Slide

  76. Appendix

    View Slide

  77. # of packages tracked
    57
    9 11
    28
    0
    10
    20
    30
    40
    50
    60

    View Slide

  78. What’s gaining (alt metric)?
    * e.g. Pinax, Mezzanine
    Would use in future / Have used in past
    0% 25% 50% 75% 100% 125% 150%
    Roll your own
    django-allauth
    django-userena
    Larger framework*
    django-social-auth
    django-registration

    View Slide