| 1 |
Multi-User Setups |
| 2 |
================= |
| 3 |
|
| 4 |
Many websites are designed to have multiple user accounts, where each user has |
| 5 |
one or more OAuth connections to other websites, like Google or Twitter. |
| 6 |
This is a perfectly valid use-case for OAuth, but in order to implement it |
| 7 |
correctly, you need to think carefully about how these OAuth connections are |
| 8 |
created and used. There are a lot of unexpected edge-cases |
| 9 |
that can take you by surprise. |
| 10 |
|
| 11 |
Defining Expected Behavior |
| 12 |
-------------------------- |
| 13 |
|
| 14 |
User Association vs User Creation |
| 15 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 16 |
|
| 17 |
Are users expected to create an account on your website *first*, and then |
| 18 |
associate OAuth connections *afterwards*? Or does logging in with an an OAuth |
| 19 |
provider *create an account* for the user on your site automatically? |
| 20 |
|
| 21 |
The first option (user association) is useful when you expect users to |
| 22 |
primarily log in to your website using a username/password combination, |
| 23 |
but want to allow your users to perform actions on other sites via OAuth. |
| 24 |
For example, maybe you want to build your own social network website, |
| 25 |
and allow users to invite their friends from Facebook and their followers |
| 26 |
on Twitter. Typically, this setup means that users are able to associate |
| 27 |
their accounts with other websites via OAuth, but they are not required to |
| 28 |
do so. |
| 29 |
|
| 30 |
The second option (user creation) is useful when you expect users to |
| 31 |
primarily (or exclusively) log in to your website using an OAuth connection. |
| 32 |
For example, maybe you don't want your users to have to remember another |
| 33 |
username/password combination, so instead, you have a "Log In with Google" |
| 34 |
or "Log In with GitHub" button on your website. When a user clicks on that |
| 35 |
button and logs in with the respective service, they automatically create an |
| 36 |
account on your website in the process. Typically, this setup means that users |
| 37 |
cannot create an account on your website without associating it with an |
| 38 |
OAuth connection. |
| 39 |
|
| 40 |
Associations with Multiple Providers |
| 41 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 42 |
|
| 43 |
Can a user associate one account with multiple different OAuth providers? |
| 44 |
For example, can a user login with Google *or* login with GitHub, and log into |
| 45 |
the same account whichever option they pick? |
| 46 |
|
| 47 |
This is particularly complicated if you've chosen user creation via OAuth, |
| 48 |
instead of user association. When a user logs in with a provider, and your |
| 49 |
website hasn't seen that particular user on that particular provider before, |
| 50 |
how does your website know whether to create a new user on your website, or |
| 51 |
link this provider to an existing user on your website? If you use user |
| 52 |
association, you can simply require that the user should already be logged |
| 53 |
in to their local account before they can associate that local account |
| 54 |
with an OAuth provider. But if you use user creation, that requirement is |
| 55 |
almost impossible to enforce, because typically people don't understand |
| 56 |
that they *have* a local user account. |
| 57 |
|
| 58 |
Flask-Dance's Default Behavior |
| 59 |
------------------------------ |
| 60 |
|
| 61 |
Flask-Dance does the best it can to resolve these issues for you, while |
| 62 |
allowing you to take control in complex circumstances. Different token storages |
| 63 |
may handle this differently, but for simplicity, this document will |
| 64 |
refer to the :ref:`SQLAlchemy storage <sqlalchemy-storage>`. |
| 65 |
|
| 66 |
User Association vs User Creation |
| 67 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 68 |
|
| 69 |
Flask-Dance will *never* create user accounts for your users automatically. |
| 70 |
Flask-Dance *only* handles creating OAuth associations and retrieving them |
| 71 |
on a per-user basis. By default, Flask-Dance will associate new OAuth |
| 72 |
connections with the local user that is currently logged in. |
| 73 |
|
| 74 |
What happens if there no local user is currently logged in? That depends |
| 75 |
on the ``user_required`` parameter of the |
| 76 |
:class:`~flask_dance.consumer.storage.sqla.SQLAlchemyStorage` class. If it is |
| 77 |
``False``, Flask-Dance will create an association that isn't linked to |
| 78 |
any particular user in your application. |
| 79 |
This is handy if you don't actually *have* local user accounts in your |
| 80 |
application, and are using Flask-Dance to connect your entire website to one |
| 81 |
single remote user. For example, this could be the desired behavior if your |
| 82 |
website is actually a bot that responds to incoming requests by making API |
| 83 |
calls to a third-party website, like a Twitter bot that tweets in response |
| 84 |
to certain HTTP requests. |
| 85 |
|
| 86 |
If the ``user_required`` parameter is set to ``True``, and no local user is |
| 87 |
currently logged in, then Flask-Dance will raise an exception when trying to |
| 88 |
associate an OAuth connection with the local user. The only way to correctly |
| 89 |
resolve this situation is to override Flask-Dance's default behavior and |
| 90 |
specify exactly how to create a local user. |
| 91 |
|
| 92 |
Associations with Multiple Providers |
| 93 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 94 |
|
| 95 |
By default, Flask-Dance will happily associate multiple different |
| 96 |
OAuth providers with a single user account. This is why the ``OAuth`` model |
| 97 |
in SQLAlchemy must be separate from the ``User`` model: so that you can |
| 98 |
associate multiple different ``OAuth`` models with a single ``User`` model. |
| 99 |
|
| 100 |
Since Flask-Dance does user association by default, rather than user creation, |
| 101 |
you don't need to worry about the question of how Flask-Dance will handle |
| 102 |
new OAuth associations. Using the default behavior, Flask-Dance will *never* |
| 103 |
create a new user for the connection; instead, it will *always* associate |
| 104 |
the connection with an existing user. |
| 105 |
|
| 106 |
Overriding the Default Behavior |
| 107 |
------------------------------- |
| 108 |
|
| 109 |
If you want to allow users to log in with OAuth, and create local user accounts |
| 110 |
automatically when they do so, you'll need to override Flask-Dance's default |
| 111 |
behavior. To do so, you'll need to hook into the |
| 112 |
:data:`~flask_dance.consumer.oauth_authorized` signal. |
| 113 |
|
| 114 |
Flask-Dance's default behavior comes from storing the OAuth token for you |
| 115 |
automatically. To override the default behavior, write a function that |
| 116 |
subscribes to this signal, handles it the way *you* want, |
| 117 |
and returns ``False`` or a :class:`~werkzeug.wrappers.Response` object. |
| 118 |
Returning ``False`` or a :class:`~werkzeug.wrappers.Response` object |
| 119 |
from this signal handler indicates to Flask-Dance that it should not |
| 120 |
try to store the OAuth token for you. For example, returning a custom redirect |
| 121 |
like :func:`flask.redirect` would override the default behavior. |
| 122 |
|
| 123 |
.. warning:: |
| 124 |
|
| 125 |
If you return ``False`` from a |
| 126 |
:data:`~flask_dance.consumer.oauth_authorized` signal handler, |
| 127 |
and you do *not* store the OAuth token in your database, |
| 128 |
the OAuth token will be lost, and you will not be able to use it to make |
| 129 |
API calls in the future! |
| 130 |
|
| 131 |
Here's an example of how you might want to override Flask-Dance's default |
| 132 |
behavior in order to create user accounts automatically: |
| 133 |
|
| 134 |
.. code-block:: python |
| 135 |
|
| 136 |
import flask |
| 137 |
from flask import flash |
| 138 |
from flask_security import current_user, login_user |
| 139 |
from flask_dance.consumer import oauth_authorized |
| 140 |
from flask_dance.consumer.storage.sqla import SQLAlchemyStorage |
| 141 |
from flask_dance.contrib.github import make_github_blueprint |
| 142 |
from sqlalchemy.orm.exc import NoResultFound |
| 143 |
from myapp.models import db, OAuth, User |
| 144 |
|
| 145 |
|
| 146 |
github_bp = make_github_blueprint( |
| 147 |
storage=SQLAlchemyStorage(OAuth, db.session, user=current_user) |
| 148 |
) |
| 149 |
|
| 150 |
|
| 151 |
# create/login local user on successful OAuth login |
| 152 |
@oauth_authorized.connect_via(github_bp) |
| 153 |
def github_logged_in(blueprint, token): |
| 154 |
if not token: |
| 155 |
flash("Failed to log in with GitHub.", category="error") |
| 156 |
return False |
| 157 |
|
| 158 |
resp = blueprint.session.get("/user") |
| 159 |
if not resp.ok: |
| 160 |
msg = "Failed to fetch user info from GitHub." |
| 161 |
flash(msg, category="error") |
| 162 |
return False |
| 163 |
|
| 164 |
github_info = resp.json() |
| 165 |
github_user_id = str(github_info["id"]) |
| 166 |
|
| 167 |
# Find this OAuth token in the database, or create it |
| 168 |
query = OAuth.query.filter_by( |
| 169 |
provider=blueprint.name, |
| 170 |
provider_user_id=github_user_id, |
| 171 |
) |
| 172 |
try: |
| 173 |
oauth = query.one() |
| 174 |
except NoResultFound: |
| 175 |
oauth = OAuth( |
| 176 |
provider=blueprint.name, |
| 177 |
provider_user_id=github_user_id, |
| 178 |
token=token, |
| 179 |
) |
| 180 |
|
| 181 |
if oauth.user: |
| 182 |
# If this OAuth token already has an associated local account, |
| 183 |
# log in that local user account. |
| 184 |
# Note that if we just created this OAuth token, then it can't |
| 185 |
# have an associated local account yet. |
| 186 |
login_user(oauth.user) |
| 187 |
flash("Successfully signed in with GitHub.") |
| 188 |
|
| 189 |
else: |
| 190 |
# If this OAuth token doesn't have an associated local account, |
| 191 |
# create a new local user account for this user. We can log |
| 192 |
# in that account as well, while we're at it. |
| 193 |
user = User( |
| 194 |
# Remember that `email` can be None, if the user declines |
| 195 |
# to publish their email address on GitHub! |
| 196 |
email=github_info["email"], |
| 197 |
name=github_info["name"], |
| 198 |
) |
| 199 |
# Associate the new local user account with the OAuth token |
| 200 |
oauth.user = user |
| 201 |
# Save and commit our database models |
| 202 |
db.session.add_all([user, oauth]) |
| 203 |
db.session.commit() |
| 204 |
# Log in the new local user account |
| 205 |
login_user(user) |
| 206 |
flash("Successfully signed in with GitHub.") |
| 207 |
|
| 208 |
# Since we're manually creating the OAuth model in the database, |
| 209 |
# we should return False so that Flask-Dance knows that |
| 210 |
# it doesn't have to do it. If we don't return False, the OAuth token |
| 211 |
# could be saved twice, or Flask-Dance could throw an error when |
| 212 |
# trying to incorrectly save it for us. |
| 213 |
return False |
| 214 |
|
| 215 |
This example code does not include implementations for the ``User`` |
| 216 |
and ``OAuth`` models: you can see that these models are imported from another |
| 217 |
file. However, notice that the ``OAuth`` model has a field called |
| 218 |
``provider_user_id``, which is used to store the user ID of the GitHub user. |
| 219 |
The example code uses that ID to check if we've already saved an OAuth token |
| 220 |
in the database for this GitHub user. |