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. 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)
  2. 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
  3. 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.
  4. 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
  5. 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
  6. 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
  7. 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)  …
  8. 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
  9. 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
  10. 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
  11. 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
  12. 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
  13. 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
  14. 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.
  15. 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.
  16. 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
  17. 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
  18. 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
  19. 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?
  20. Our Focus Today Extended User Attributes e.g. Favorite color User

    Permissions User Model django.contrib.auth User Registration & Login Authorization Authentication Profile
  21. 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
  22. 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
  23. Authentication Packages  50 packages!  Lets try to process

    that and make the decision a little easier
  24. 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
  25. 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?
  26. 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?
  27. 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
  28. 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
  29. 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.
  30. Where do they specialize? Package Specialty Stack django-social-auth  3rd

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

    user accounts  Email activation  (semi)public user profiles  User-to-user messaging
  33. 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
  34. 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”
  35. 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
  36. 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
  37. 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
  38. 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
  39. 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
  40. 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", ... )
  41. 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’}, }
  42. 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
  43. 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), ... )
  44. Configuring AllAuth Templates  Optional  Override if you want/need

    to  But you don’t have to: It.just.works out of the box
  45. 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
  46. 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>
  47. 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 %}
  48. 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
  49. 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): ...
  50. 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