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.

50442907f3f9f2bce34b49768357e503?s=128

tedtieken

April 26, 2013
Tweet

Transcript

  1. None
  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)
  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
  4. None
  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.
  6. Problem http://q4ts.herokuapp.com/ Turn Kevin Harvey’s Torquemada app from January testing

    meetup into user-enabled clone QuestionsForTheSpeaker
  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
  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
  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
  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)  …
  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
  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
  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
  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
  15. Your Responsibility django.contrib.auth Division of Labor Authorization Authentication Profile

  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
  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
  18. This is important: Salting and Hashing

  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.
  20. None
  21. Back to our regularly scheduled programming

  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.
  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
  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
  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
  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?
  27. Our Focus Today Extended User Attributes e.g. Favorite color User

    Permissions User Model django.contrib.auth User Registration & Login Authorization Authentication Profile
  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
  29. DjangoPackages.com First stop when evaluating community packages

  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
  31. Authentication Packages  50 packages!  Lets try to process

    that and make the decision a little easier
  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
  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?
  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?
  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
  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
  37. http://tinyurl.com/djangoauth View the results yourself

  38. Lets take a look at some libraries

  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.
  40. Where do they specialize? Package Specialty Stack django-registration  Local

    user accounts  Email activation
  41. Where do they specialize? Package Specialty Stack django-social-auth  3rd

    Party/social accounts  Multiple 3rd party accounts
  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
  43. Where do they specialize? Package Specialty Stack django-userena  Local

    user accounts  Email activation  (semi)public user profiles  User-to-user messaging
  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
  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”
  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
  47. Beware django-social-auth django-socialauth We’ve been talking about this one

  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
  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
  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
  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
  52. Mature Rapidly Maturing

  53. Mature Rapidly Maturing Even with the remaining bumps, it’s the

    easiest social auth package to use
  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", ... )
  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’}, }
  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
  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), ... )
  58. This gets the following URLS

  59. Configuring AllAuth Templates

  60. Configuring AllAuth Templates  Optional  Override if you want/need

    to  But you don’t have to: It.just.works out of the box
  61. Register your app w/ Facebook

  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
  63. Register your app w/ Facebook

  64. Register your app w/ Facebook

  65. Register your app w/ Facebook

  66. Record keys in the database

  67. Record keys in the database

  68. Make it work locally: two apps

  69. Remember to turn off sandbox

  70. Add links to to base.html {% load url from future

    %} {% load socialaccount %} <a href="{% url 'account_signup' %}">Sign Up</a> <a href="{% url 'account_login' %}">Log in</a> <a href=“{% provider_login_url 'facebook' method='oauth2' %}"> Sign Up / Login with Facebook </a>
  71. http://q4ts.herokuapp.com/accounts/facebook/login/?method=oauth2 http://q4ts.herokuapp.com/accounts/facebook/login/callback/?code=##&state=##

  72. Show apt links for user state {% if user.is_authenticated %}

    <a href="{% url 'account_logout' %}">Log out</a> <a href="/accounts/profile/">My Account</a> {% else %} <a href="{% url 'account_signup' %}">Sign Up</a> <a href="{% url 'account_login' %}">Log in</a> <a href="{% provider_login_url 'facebook' method='oauth2' %}">Facebook Connect</a> {% endif %}
  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?  <h1> My Account</h1>  ul > li  username  email + manage email link  linked social accounts + manage social accounts link  password change links  logout link
  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): ...
  75. Go do interesting things

  76. Appendix

  77. # of packages tracked 57 9 11 28 0 10

    20 30 40 50 60
  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