| 1 |
import pytest |
| 2 |
|
| 3 |
sa = pytest.importorskip("sqlalchemy") |
| 4 |
|
| 5 |
import os |
| 6 |
|
| 7 |
import flask |
| 8 |
import responses |
| 9 |
from flask_caching import Cache |
| 10 |
from flask_login import ( |
| 11 |
FlaskLoginClient, |
| 12 |
LoginManager, |
| 13 |
UserMixin, |
| 14 |
current_user, |
| 15 |
login_user, |
| 16 |
logout_user, |
| 17 |
) |
| 18 |
from flask_sqlalchemy import SQLAlchemy |
| 19 |
from sqlalchemy import event |
| 20 |
|
| 21 |
from flask_dance.consumer import OAuth2ConsumerBlueprint, oauth_authorized, oauth_error |
| 22 |
from flask_dance.consumer.storage.sqla import OAuthConsumerMixin, SQLAlchemyStorage |
| 23 |
|
| 24 |
try: |
| 25 |
import blinker |
| 26 |
except ImportError: |
| 27 |
blinker = None |
| 28 |
requires_blinker = pytest.mark.skipif(not blinker, reason="requires blinker") |
| 29 |
|
| 30 |
pytestmark = [pytest.mark.usefixtures("responses")] |
| 31 |
|
| 32 |
|
| 33 |
@pytest.fixture |
| 34 |
def blueprint(): |
| 35 |
"Make a OAuth2 blueprint for a fictional OAuth provider" |
| 36 |
bp = OAuth2ConsumerBlueprint( |
| 37 |
"test-service", |
| 38 |
__name__, |
| 39 |
client_id="client_id", |
| 40 |
client_secret="client_secret", |
| 41 |
state="random-string", |
| 42 |
base_url="https://example.com", |
| 43 |
authorization_url="https://example.com/oauth/authorize", |
| 44 |
token_url="https://example.com/oauth/access_token", |
| 45 |
redirect_url="/oauth_done", |
| 46 |
) |
| 47 |
responses.add( |
| 48 |
responses.POST, |
| 49 |
"https://example.com/oauth/access_token", |
| 50 |
body='{"access_token":"foobar","token_type":"bearer","scope":""}', |
| 51 |
) |
| 52 |
return bp |
| 53 |
|
| 54 |
|
| 55 |
@pytest.fixture |
| 56 |
def db(): |
| 57 |
"Make a Flask-SQLAlchemy instance" |
| 58 |
return SQLAlchemy() |
| 59 |
|
| 60 |
|
| 61 |
@pytest.fixture |
| 62 |
def app(blueprint, db, request): |
| 63 |
"Make a Flask app, attach Flask-SQLAlchemy, and establish an app context" |
| 64 |
app = flask.Flask(__name__) |
| 65 |
app.config["SERVER_NAME"] = "a.b.c" |
| 66 |
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("DATABASE_URI", "sqlite://") |
| 67 |
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False |
| 68 |
app.config["CACHE_TYPE"] = "SimpleCache" |
| 69 |
app.secret_key = "secret" |
| 70 |
app.register_blueprint(blueprint, url_prefix="/login") |
| 71 |
db.init_app(app) |
| 72 |
# establish app context |
| 73 |
ctx = app.app_context() |
| 74 |
ctx.push() |
| 75 |
request.addfinalizer(ctx.pop) |
| 76 |
return app |
| 77 |
|
| 78 |
|
| 79 |
class record_queries: |
| 80 |
""" |
| 81 |
A context manager for recording the SQLAlchemy queries that were executed |
| 82 |
in a given context block. |
| 83 |
""" |
| 84 |
|
| 85 |
def __init__(self, target, identifier="before_cursor_execute"): |
| 86 |
self.target = target |
| 87 |
self.identifier = identifier |
| 88 |
|
| 89 |
def record_query(self, conn, cursor, statement, parameters, context, executemany): |
| 90 |
self.queries.append(statement) |
| 91 |
|
| 92 |
def __enter__(self): |
| 93 |
self.queries = [] |
| 94 |
event.listen(self.target, self.identifier, self.record_query) |
| 95 |
return self.queries |
| 96 |
|
| 97 |
def __exit__(self, exc_type, exc_value, traceback): |
| 98 |
event.remove(self.target, self.identifier, self.record_query) |
| 99 |
|
| 100 |
|
| 101 |
def test_sqla_storage_without_user(app, db, blueprint, request): |
| 102 |
class OAuth(OAuthConsumerMixin, db.Model): |
| 103 |
pass |
| 104 |
|
| 105 |
blueprint.storage = SQLAlchemyStorage(OAuth, db.session) |
| 106 |
|
| 107 |
db.create_all() |
| 108 |
|
| 109 |
def done(): |
| 110 |
db.session.remove() |
| 111 |
db.drop_all() |
| 112 |
|
| 113 |
request.addfinalizer(done) |
| 114 |
|
| 115 |
with record_queries(db.engine) as queries: |
| 116 |
with app.test_client() as client: |
| 117 |
# reset the session before the request |
| 118 |
with client.session_transaction() as sess: |
| 119 |
sess["test-service_oauth_state"] = "random-string" |
| 120 |
# make the request |
| 121 |
resp = client.get( |
| 122 |
"/login/test-service/authorized?code=secret-code&state=random-string", |
| 123 |
base_url="https://a.b.c", |
| 124 |
) |
| 125 |
# check that we redirected the client |
| 126 |
assert resp.status_code == 302 |
| 127 |
assert resp.headers["Location"] in ( |
| 128 |
"https://a.b.c/oauth_done", |
| 129 |
"/oauth_done", |
| 130 |
) |
| 131 |
|
| 132 |
assert len(queries) == 2 |
| 133 |
|
| 134 |
# check the database |
| 135 |
authorizations = OAuth.query.all() |
| 136 |
assert len(authorizations) == 1 |
| 137 |
oauth = authorizations[0] |
| 138 |
assert oauth.provider == "test-service" |
| 139 |
assert isinstance(oauth.token, dict) |
| 140 |
assert oauth.token == { |
| 141 |
"access_token": "foobar", |
| 142 |
"token_type": "bearer", |
| 143 |
"scope": [""], |
| 144 |
} |
| 145 |
|
| 146 |
|
| 147 |
def test_sqla_model_repr(app, db, request): |
| 148 |
class MyAwesomeOAuth(OAuthConsumerMixin, db.Model): |
| 149 |
pass |
| 150 |
|
| 151 |
db.create_all() |
| 152 |
|
| 153 |
def done(): |
| 154 |
db.session.remove() |
| 155 |
db.drop_all() |
| 156 |
|
| 157 |
request.addfinalizer(done) |
| 158 |
|
| 159 |
o = MyAwesomeOAuth() |
| 160 |
assert "MyAwesomeOAuth" in repr(o) |
| 161 |
o.provider = "supercool" |
| 162 |
assert 'provider="supercool"' in repr(o) |
| 163 |
o.token = {"access_token": "secret"} |
| 164 |
assert "secret" not in repr(o) |
| 165 |
|
| 166 |
db.session.add(o) |
| 167 |
db.session.commit() |
| 168 |
assert "id=" in repr(o) |
| 169 |
assert "secret" not in repr(o) |
| 170 |
|
| 171 |
|
| 172 |
def test_sqla_storage(app, db, blueprint, request): |
| 173 |
class User(db.Model): |
| 174 |
id = db.Column(db.Integer, primary_key=True) |
| 175 |
name = db.Column(db.String(80)) |
| 176 |
|
| 177 |
class OAuth(OAuthConsumerMixin, db.Model): |
| 178 |
user_id = db.Column(db.Integer, db.ForeignKey(User.id)) |
| 179 |
user = db.relationship(User) |
| 180 |
|
| 181 |
db.create_all() |
| 182 |
|
| 183 |
def done(): |
| 184 |
db.session.remove() |
| 185 |
db.drop_all() |
| 186 |
|
| 187 |
request.addfinalizer(done) |
| 188 |
|
| 189 |
# for now, we'll assume that Alice is the only user |
| 190 |
alice = User(name="Alice") |
| 191 |
db.session.add(alice) |
| 192 |
db.session.commit() |
| 193 |
# load alice's ID -- this issues a database query |
| 194 |
alice.id |
| 195 |
|
| 196 |
blueprint.storage = SQLAlchemyStorage(OAuth, db.session, user=alice) |
| 197 |
|
| 198 |
with record_queries(db.engine) as queries: |
| 199 |
with app.test_client() as client: |
| 200 |
# reset the session before the request |
| 201 |
with client.session_transaction() as sess: |
| 202 |
sess["test-service_oauth_state"] = "random-string" |
| 203 |
# make the request |
| 204 |
resp = client.get( |
| 205 |
"/login/test-service/authorized?code=secret-code&state=random-string", |
| 206 |
base_url="https://a.b.c", |
| 207 |
) |
| 208 |
# check that we redirected the client |
| 209 |
assert resp.status_code == 302 |
| 210 |
assert resp.headers["Location"] in ( |
| 211 |
"https://a.b.c/oauth_done", |
| 212 |
"/oauth_done", |
| 213 |
) |
| 214 |
|
| 215 |
assert len(queries) == 3 |
| 216 |
|
| 217 |
# check the database |
| 218 |
alice = User.query.first() |
| 219 |
authorizations = OAuth.query.all() |
| 220 |
assert len(authorizations) == 1 |
| 221 |
oauth = authorizations[0] |
| 222 |
assert oauth.user_id == alice.id |
| 223 |
assert oauth.provider == "test-service" |
| 224 |
assert isinstance(oauth.token, dict) |
| 225 |
assert oauth.token == { |
| 226 |
"access_token": "foobar", |
| 227 |
"token_type": "bearer", |
| 228 |
"scope": [""], |
| 229 |
} |
| 230 |
|
| 231 |
|
| 232 |
def test_sqla_load_token_for_user(app, db, blueprint, request): |
| 233 |
class User(db.Model): |
| 234 |
id = db.Column(db.Integer, primary_key=True) |
| 235 |
name = db.Column(db.String(80)) |
| 236 |
|
| 237 |
class OAuth(OAuthConsumerMixin, db.Model): |
| 238 |
user_id = db.Column(db.Integer, db.ForeignKey(User.id)) |
| 239 |
user = db.relationship(User) |
| 240 |
|
| 241 |
db.create_all() |
| 242 |
|
| 243 |
def done(): |
| 244 |
db.session.remove() |
| 245 |
db.drop_all() |
| 246 |
|
| 247 |
request.addfinalizer(done) |
| 248 |
|
| 249 |
# set token storage |
| 250 |
blueprint.storage = SQLAlchemyStorage(OAuth, db.session) |
| 251 |
|
| 252 |
# make users and OAuth tokens for several people |
| 253 |
alice = User(name="Alice") |
| 254 |
alice_token = {"access_token": "alice123", "token_type": "bearer"} |
| 255 |
alice_oauth = OAuth(user=alice, token=alice_token, provider="test-service") |
| 256 |
bob = User(name="Bob") |
| 257 |
bob_token = {"access_token": "bob456", "token_type": "bearer"} |
| 258 |
bob_oauth = OAuth(user=bob, token=bob_token, provider="test-service") |
| 259 |
sue = User(name="Sue") |
| 260 |
sue_token = {"access_token": "sue789", "token_type": "bearer"} |
| 261 |
sue_oauth = OAuth(user=sue, token=sue_token, provider="test-service") |
| 262 |
db.session.add_all([alice, bob, sue, alice_oauth, bob_oauth, sue_oauth]) |
| 263 |
db.session.commit() |
| 264 |
|
| 265 |
# by default, we should not have a token for anyone |
| 266 |
sess = blueprint.session |
| 267 |
assert not sess.token |
| 268 |
assert not blueprint.token |
| 269 |
|
| 270 |
# load token for various users |
| 271 |
blueprint.config["user"] = alice |
| 272 |
assert sess.token == alice_token |
| 273 |
assert blueprint.token == alice_token |
| 274 |
|
| 275 |
blueprint.config["user"] = bob |
| 276 |
assert sess.token == bob_token |
| 277 |
assert blueprint.token == bob_token |
| 278 |
|
| 279 |
blueprint.config["user"] = alice |
| 280 |
assert sess.token == alice_token |
| 281 |
assert blueprint.token == alice_token |
| 282 |
|
| 283 |
blueprint.config["user"] = sue |
| 284 |
assert sess.token == sue_token |
| 285 |
assert blueprint.token == sue_token |
| 286 |
|
| 287 |
# load for user ID as well |
| 288 |
del blueprint.config["user"] |
| 289 |
blueprint.config["user_id"] = bob.id |
| 290 |
assert sess.token == bob_token |
| 291 |
assert blueprint.token == bob_token |
| 292 |
|
| 293 |
# try deleting user tokens |
| 294 |
del blueprint.token |
| 295 |
assert sess.token == None |
| 296 |
assert blueprint.token == None |
| 297 |
|
| 298 |
# shouldn't affect alice's token |
| 299 |
blueprint.config["user_id"] = alice.id |
| 300 |
assert sess.token == alice_token |
| 301 |
assert blueprint.token == alice_token |
| 302 |
|
| 303 |
|
| 304 |
def test_sqla_flask_login(app, db, blueprint, request): |
| 305 |
login_manager = LoginManager(app) |
| 306 |
|
| 307 |
class User(db.Model, UserMixin): |
| 308 |
id = db.Column(db.Integer, primary_key=True) |
| 309 |
name = db.Column(db.String(80)) |
| 310 |
|
| 311 |
class OAuth(OAuthConsumerMixin, db.Model): |
| 312 |
user_id = db.Column(db.Integer, db.ForeignKey(User.id)) |
| 313 |
user = db.relationship(User) |
| 314 |
|
| 315 |
blueprint.storage = SQLAlchemyStorage(OAuth, db.session, user=current_user) |
| 316 |
app.test_client_class = FlaskLoginClient |
| 317 |
|
| 318 |
db.create_all() |
| 319 |
|
| 320 |
def done(): |
| 321 |
db.session.remove() |
| 322 |
db.drop_all() |
| 323 |
|
| 324 |
request.addfinalizer(done) |
| 325 |
|
| 326 |
# create some users |
| 327 |
u1 = User(name="Alice") |
| 328 |
u2 = User(name="Bob") |
| 329 |
u3 = User(name="Chuck") |
| 330 |
db.session.add_all([u1, u2, u3]) |
| 331 |
db.session.commit() |
| 332 |
|
| 333 |
# configure login manager |
| 334 |
@login_manager.user_loader |
| 335 |
def load_user(userid): |
| 336 |
return User.query.get(userid) |
| 337 |
|
| 338 |
with record_queries(db.engine) as queries: |
| 339 |
with app.test_client(user=u1) as client: |
| 340 |
# reset the session before the request |
| 341 |
with client.session_transaction() as sess: |
| 342 |
sess["test-service_oauth_state"] = "random-string" |
| 343 |
# make the request |
| 344 |
resp = client.get( |
| 345 |
"/login/test-service/authorized?code=secret-code&state=random-string", |
| 346 |
base_url="https://a.b.c", |
| 347 |
) |
| 348 |
# check that we redirected the client |
| 349 |
assert resp.status_code == 302 |
| 350 |
assert resp.headers["Location"] in ( |
| 351 |
"https://a.b.c/oauth_done", |
| 352 |
"/oauth_done", |
| 353 |
) |
| 354 |
|
| 355 |
assert len(queries) == 5 |
| 356 |
|
| 357 |
# lets do it again, with Bob as the logged in user -- he gets a different token |
| 358 |
if "_login_user" in flask.g: |
| 359 |
del flask.g._login_user # clear cache |
| 360 |
responses.reset() |
| 361 |
responses.add( |
| 362 |
responses.POST, |
| 363 |
"https://example.com/oauth/access_token", |
| 364 |
body='{"access_token":"abcdef","token_type":"bearer","scope":"bob"}', |
| 365 |
) |
| 366 |
with record_queries(db.engine) as queries: |
| 367 |
with app.test_client(user=u2) as client: |
| 368 |
# reset the session before the request |
| 369 |
with client.session_transaction() as sess: |
| 370 |
sess["test-service_oauth_state"] = "random-string" |
| 371 |
# make the request |
| 372 |
resp = client.get( |
| 373 |
"/login/test-service/authorized?code=secret-code&state=random-string", |
| 374 |
base_url="https://a.b.c", |
| 375 |
) |
| 376 |
# check that we redirected the client |
| 377 |
assert resp.status_code == 302 |
| 378 |
assert resp.headers["Location"] in ( |
| 379 |
"https://a.b.c/oauth_done", |
| 380 |
"/oauth_done", |
| 381 |
) |
| 382 |
|
| 383 |
assert len(queries) == 5 |
| 384 |
|
| 385 |
# check the database |
| 386 |
authorizations = OAuth.query.all() |
| 387 |
assert len(authorizations) == 2 |
| 388 |
u1_oauth = OAuth.query.filter_by(user=u1).one() |
| 389 |
assert u1_oauth.provider == "test-service" |
| 390 |
assert u1_oauth.token == { |
| 391 |
"access_token": "foobar", |
| 392 |
"token_type": "bearer", |
| 393 |
"scope": [""], |
| 394 |
} |
| 395 |
u2_oauth = OAuth.query.filter_by(user=u2).one() |
| 396 |
assert u2_oauth.provider == "test-service" |
| 397 |
assert u2_oauth.token == { |
| 398 |
"access_token": "abcdef", |
| 399 |
"token_type": "bearer", |
| 400 |
"scope": ["bob"], |
| 401 |
} |
| 402 |
u3_oauth = OAuth.query.filter_by(user=u3).all() |
| 403 |
assert len(u3_oauth) == 0 |
| 404 |
|
| 405 |
|
| 406 |
@requires_blinker |
| 407 |
def test_sqla_flask_login_misconfigured(app, db, blueprint, request): |
| 408 |
login_manager = LoginManager(app) |
| 409 |
|
| 410 |
class User(db.Model, UserMixin): |
| 411 |
id = db.Column(db.Integer, primary_key=True) |
| 412 |
name = db.Column(db.String(80)) |
| 413 |
|
| 414 |
class OAuth(OAuthConsumerMixin, db.Model): |
| 415 |
user_id = db.Column(db.Integer, db.ForeignKey(User.id)) |
| 416 |
user = db.relationship(User) |
| 417 |
|
| 418 |
blueprint.storage = SQLAlchemyStorage(OAuth, db.session, user=current_user) |
| 419 |
|
| 420 |
db.create_all() |
| 421 |
|
| 422 |
def done(): |
| 423 |
db.session.remove() |
| 424 |
db.drop_all() |
| 425 |
|
| 426 |
request.addfinalizer(done) |
| 427 |
|
| 428 |
# configure login manager |
| 429 |
@login_manager.user_loader |
| 430 |
def load_user(userid): |
| 431 |
return User.query.get(userid) |
| 432 |
|
| 433 |
calls = [] |
| 434 |
|
| 435 |
def callback(*args, **kwargs): |
| 436 |
calls.append((args, kwargs)) |
| 437 |
|
| 438 |
oauth_error.connect(callback) |
| 439 |
request.addfinalizer(lambda: oauth_error.disconnect(callback)) |
| 440 |
|
| 441 |
with app.test_client() as client: |
| 442 |
# reset the session before the request |
| 443 |
with client.session_transaction() as sess: |
| 444 |
sess["test-service_oauth_state"] = "random-string" |
| 445 |
# make the request |
| 446 |
resp = client.get( |
| 447 |
"/login/test-service/authorized?code=secret-code&state=random-string", |
| 448 |
base_url="https://a.b.c", |
| 449 |
) |
| 450 |
# check that we redirected the client |
| 451 |
assert resp.status_code == 302 |
| 452 |
assert resp.headers["Location"] in ("https://a.b.c/oauth_done", "/oauth_done") |
| 453 |
|
| 454 |
assert len(calls) == 1 |
| 455 |
assert calls[0][0] == (blueprint,) |
| 456 |
error = calls[0][1]["error"] |
| 457 |
assert isinstance(error, ValueError) |
| 458 |
assert str(error) == "Cannot set OAuth token without an associated user" |
| 459 |
|
| 460 |
|
| 461 |
@requires_blinker |
| 462 |
def test_sqla_flask_login_anon_to_authed(app, db, blueprint, request): |
| 463 |
login_manager = LoginManager(app) |
| 464 |
|
| 465 |
class User(db.Model, UserMixin): |
| 466 |
id = db.Column(db.Integer, primary_key=True) |
| 467 |
name = db.Column(db.String(80)) |
| 468 |
|
| 469 |
class OAuth(OAuthConsumerMixin, db.Model): |
| 470 |
user_id = db.Column(db.Integer, db.ForeignKey(User.id)) |
| 471 |
user = db.relationship(User) |
| 472 |
|
| 473 |
blueprint.storage = SQLAlchemyStorage(OAuth, db.session, user=current_user) |
| 474 |
|
| 475 |
db.create_all() |
| 476 |
|
| 477 |
def done(): |
| 478 |
db.session.remove() |
| 479 |
db.drop_all() |
| 480 |
|
| 481 |
request.addfinalizer(done) |
| 482 |
|
| 483 |
# configure login manager |
| 484 |
@login_manager.user_loader |
| 485 |
def load_user(userid): |
| 486 |
return User.query.get(userid) |
| 487 |
|
| 488 |
# create a user object when OAuth succeeds |
| 489 |
def logged_in(sender, token): |
| 490 |
assert token |
| 491 |
assert blueprint == sender |
| 492 |
resp = sender.session.get("/user") |
| 493 |
user = User(name=resp.json()["name"]) |
| 494 |
login_user(user) |
| 495 |
db.session.add(user) |
| 496 |
db.session.commit() |
| 497 |
flask.flash("Signed in successfully") |
| 498 |
|
| 499 |
oauth_authorized.connect(logged_in, blueprint) |
| 500 |
request.addfinalizer(lambda: oauth_authorized.disconnect(logged_in, blueprint)) |
| 501 |
|
| 502 |
# mock out the `/user` API call |
| 503 |
responses.add( |
| 504 |
responses.GET, "https://example.com/user", body='{"name":"josephine"}' |
| 505 |
) |
| 506 |
|
| 507 |
with record_queries(db.engine) as queries: |
| 508 |
with app.test_client() as client: |
| 509 |
with client.session_transaction() as sess: |
| 510 |
sess["test-service_oauth_state"] = "random-string" |
| 511 |
# make the request |
| 512 |
resp = client.get( |
| 513 |
"/login/test-service/authorized?code=secret-code&state=random-string", |
| 514 |
base_url="https://a.b.c", |
| 515 |
) |
| 516 |
# check that we redirected the client |
| 517 |
assert resp.status_code == 302 |
| 518 |
assert resp.headers["Location"] in ( |
| 519 |
"https://a.b.c/oauth_done", |
| 520 |
"/oauth_done", |
| 521 |
) |
| 522 |
|
| 523 |
assert len(queries) == 5 |
| 524 |
|
| 525 |
# check the database |
| 526 |
users = User.query.all() |
| 527 |
assert len(users) == 1 |
| 528 |
user = users[0] |
| 529 |
assert user.name == "josephine" |
| 530 |
|
| 531 |
authorizations = OAuth.query.all() |
| 532 |
assert len(authorizations) == 1 |
| 533 |
oauth = authorizations[0] |
| 534 |
assert oauth.provider == "test-service" |
| 535 |
assert oauth.token == { |
| 536 |
"access_token": "foobar", |
| 537 |
"token_type": "bearer", |
| 538 |
"scope": [""], |
| 539 |
} |
| 540 |
assert oauth.user_id == user.id |
| 541 |
|
| 542 |
|
| 543 |
def test_sqla_flask_login_preload_logged_in_user(app, db, blueprint, request): |
| 544 |
# need a URL to hit, so that tokens will be loaded, but result is irrelevant |
| 545 |
responses.add(responses.GET, "https://example.com/noop") |
| 546 |
|
| 547 |
login_manager = LoginManager(app) |
| 548 |
|
| 549 |
class User(db.Model, UserMixin): |
| 550 |
id = db.Column(db.Integer, primary_key=True) |
| 551 |
name = db.Column(db.String(80)) |
| 552 |
|
| 553 |
class OAuth(OAuthConsumerMixin, db.Model): |
| 554 |
user_id = db.Column(db.Integer, db.ForeignKey(User.id)) |
| 555 |
user = db.relationship(User) |
| 556 |
|
| 557 |
blueprint.storage = SQLAlchemyStorage(OAuth, db.session, user=current_user) |
| 558 |
|
| 559 |
db.create_all() |
| 560 |
|
| 561 |
def done(): |
| 562 |
db.session.remove() |
| 563 |
db.drop_all() |
| 564 |
|
| 565 |
request.addfinalizer(done) |
| 566 |
|
| 567 |
# create some users, and tokens for some of them |
| 568 |
alice = User(name="Alice") |
| 569 |
alice_token = {"access_token": "alice123", "token_type": "bearer"} |
| 570 |
alice_oauth = OAuth(user=alice, token=alice_token, provider="test-service") |
| 571 |
bob = User(name="Bob") |
| 572 |
bob_token = {"access_token": "bob456", "token_type": "bearer"} |
| 573 |
bob_oauth = OAuth(user=bob, token=bob_token, provider="test-service") |
| 574 |
chuck = User(name="Chuck") |
| 575 |
# chuck doesn't get a token |
| 576 |
db.session.add_all([alice, alice_oauth, bob, bob_oauth, chuck]) |
| 577 |
db.session.commit() |
| 578 |
|
| 579 |
# configure login manager |
| 580 |
@login_manager.user_loader |
| 581 |
def load_user(userid): |
| 582 |
return User.query.get(userid) |
| 583 |
|
| 584 |
# create a simple view |
| 585 |
@app.route("/") |
| 586 |
def index(): |
| 587 |
return "success" |
| 588 |
|
| 589 |
with app.test_request_context("/"): |
| 590 |
login_user(alice) |
| 591 |
# hit /noop to load tokens |
| 592 |
blueprint.session.get("/noop") |
| 593 |
# now the flask-dance session should have Alice's token loaded |
| 594 |
assert blueprint.session.token == alice_token |
| 595 |
|
| 596 |
with app.test_request_context("/"): |
| 597 |
# set bob as the logged in user |
| 598 |
login_user(bob) |
| 599 |
# hit /noop to load tokens |
| 600 |
blueprint.session.get("/noop") |
| 601 |
# now the flask-dance session should have Bob's token loaded |
| 602 |
assert blueprint.session.token == bob_token |
| 603 |
|
| 604 |
with app.test_request_context("/"): |
| 605 |
# now let's try chuck |
| 606 |
login_user(chuck) |
| 607 |
blueprint.session.get("/noop") |
| 608 |
assert blueprint.session.token == None |
| 609 |
|
| 610 |
with app.test_request_context("/"): |
| 611 |
# no one is logged in -- this is an anonymous user |
| 612 |
logout_user() |
| 613 |
with pytest.raises(ValueError): |
| 614 |
blueprint.session.get("/noop") |
| 615 |
|
| 616 |
|
| 617 |
def test_sqla_flask_login_no_user_required(app, db, blueprint, request): |
| 618 |
# need a URL to hit, so that tokens will be loaded, but result is irrelevant |
| 619 |
responses.add(responses.GET, "https://example.com/noop") |
| 620 |
|
| 621 |
login_manager = LoginManager(app) |
| 622 |
|
| 623 |
class User(db.Model, UserMixin): |
| 624 |
id = db.Column(db.Integer, primary_key=True) |
| 625 |
name = db.Column(db.String(80)) |
| 626 |
|
| 627 |
class OAuth(OAuthConsumerMixin, db.Model): |
| 628 |
user_id = db.Column(db.Integer, db.ForeignKey(User.id)) |
| 629 |
user = db.relationship(User) |
| 630 |
|
| 631 |
blueprint.storage = SQLAlchemyStorage( |
| 632 |
OAuth, db.session, user=current_user, user_required=False |
| 633 |
) |
| 634 |
|
| 635 |
db.create_all() |
| 636 |
|
| 637 |
def done(): |
| 638 |
db.session.remove() |
| 639 |
db.drop_all() |
| 640 |
|
| 641 |
request.addfinalizer(done) |
| 642 |
|
| 643 |
# configure login manager |
| 644 |
@login_manager.user_loader |
| 645 |
def load_user(userid): |
| 646 |
return User.query.get(userid) |
| 647 |
|
| 648 |
# create a simple view |
| 649 |
@app.route("/") |
| 650 |
def index(): |
| 651 |
return "success" |
| 652 |
|
| 653 |
with app.test_request_context("/"): |
| 654 |
# no one is logged in -- this is an anonymous user |
| 655 |
logout_user() |
| 656 |
# this should *not* raise an error |
| 657 |
blueprint.session.get("/noop") |
| 658 |
assert blueprint.session.token == None |
| 659 |
|
| 660 |
|
| 661 |
def test_sqla_delete_token(app, db, blueprint, request): |
| 662 |
class OAuth(OAuthConsumerMixin, db.Model): |
| 663 |
pass |
| 664 |
|
| 665 |
blueprint.storage = SQLAlchemyStorage(OAuth, db.session) |
| 666 |
|
| 667 |
db.create_all() |
| 668 |
|
| 669 |
def done(): |
| 670 |
db.session.remove() |
| 671 |
db.drop_all() |
| 672 |
|
| 673 |
request.addfinalizer(done) |
| 674 |
|
| 675 |
# Create an existing OAuth token for the service |
| 676 |
existing = OAuth( |
| 677 |
provider="test-service", |
| 678 |
token={"access_token": "something", "token_type": "bearer", "scope": ["blah"]}, |
| 679 |
) |
| 680 |
db.session.add(existing) |
| 681 |
db.session.commit() |
| 682 |
assert len(OAuth.query.all()) == 1 |
| 683 |
|
| 684 |
assert blueprint.token == { |
| 685 |
"access_token": "something", |
| 686 |
"token_type": "bearer", |
| 687 |
"scope": ["blah"], |
| 688 |
} |
| 689 |
del blueprint.token |
| 690 |
assert blueprint.token == None |
| 691 |
assert len(OAuth.query.all()) == 0 |
| 692 |
|
| 693 |
|
| 694 |
def test_sqla_overwrite_token(app, db, blueprint, request): |
| 695 |
class OAuth(OAuthConsumerMixin, db.Model): |
| 696 |
pass |
| 697 |
|
| 698 |
blueprint.storage = SQLAlchemyStorage(OAuth, db.session) |
| 699 |
|
| 700 |
db.create_all() |
| 701 |
|
| 702 |
def done(): |
| 703 |
db.session.remove() |
| 704 |
db.drop_all() |
| 705 |
|
| 706 |
request.addfinalizer(done) |
| 707 |
|
| 708 |
# Create an existing OAuth token for the service |
| 709 |
existing = OAuth( |
| 710 |
provider="test-service", |
| 711 |
token={"access_token": "something", "token_type": "bearer", "scope": ["blah"]}, |
| 712 |
) |
| 713 |
db.session.add(existing) |
| 714 |
db.session.commit() |
| 715 |
assert len(OAuth.query.all()) == 1 |
| 716 |
|
| 717 |
with record_queries(db.engine) as queries: |
| 718 |
with app.test_client() as client: |
| 719 |
# reset the session before the request |
| 720 |
with client.session_transaction() as sess: |
| 721 |
sess["test-service_oauth_state"] = "random-string" |
| 722 |
# make the request |
| 723 |
resp = client.get( |
| 724 |
"/login/test-service/authorized?code=secret-code&state=random-string", |
| 725 |
base_url="https://a.b.c", |
| 726 |
) |
| 727 |
# check that we redirected the client |
| 728 |
assert resp.status_code == 302 |
| 729 |
assert resp.headers["Location"] in ( |
| 730 |
"https://a.b.c/oauth_done", |
| 731 |
"/oauth_done", |
| 732 |
) |
| 733 |
|
| 734 |
assert len(queries) == 2 |
| 735 |
|
| 736 |
# check that the database record was overwritten |
| 737 |
authorizations = OAuth.query.all() |
| 738 |
assert len(authorizations) == 1 |
| 739 |
oauth = authorizations[0] |
| 740 |
assert oauth.provider == "test-service" |
| 741 |
assert isinstance(oauth.token, dict) |
| 742 |
assert oauth.token == { |
| 743 |
"access_token": "foobar", |
| 744 |
"token_type": "bearer", |
| 745 |
"scope": [""], |
| 746 |
} |
| 747 |
|
| 748 |
|
| 749 |
def test_sqla_cache(app, db, blueprint, request): |
| 750 |
cache = Cache(app) |
| 751 |
|
| 752 |
class OAuth(OAuthConsumerMixin, db.Model): |
| 753 |
pass |
| 754 |
|
| 755 |
blueprint.storage = SQLAlchemyStorage(OAuth, db.session, cache=cache) |
| 756 |
|
| 757 |
db.create_all() |
| 758 |
|
| 759 |
def done(): |
| 760 |
db.session.remove() |
| 761 |
db.drop_all() |
| 762 |
|
| 763 |
request.addfinalizer(done) |
| 764 |
|
| 765 |
with record_queries(db.engine) as queries: |
| 766 |
with app.test_client() as client: |
| 767 |
# reset the session before the request |
| 768 |
with client.session_transaction() as sess: |
| 769 |
sess["test-service_oauth_state"] = "random-string" |
| 770 |
# make the request |
| 771 |
resp = client.get( |
| 772 |
"/login/test-service/authorized?code=secret-code&state=random-string", |
| 773 |
base_url="https://a.b.c", |
| 774 |
) |
| 775 |
# check that we redirected the client |
| 776 |
assert resp.status_code == 302 |
| 777 |
assert resp.headers["Location"] in ( |
| 778 |
"https://a.b.c/oauth_done", |
| 779 |
"/oauth_done", |
| 780 |
) |
| 781 |
|
| 782 |
assert len(queries) == 2 |
| 783 |
|
| 784 |
expected_token = {"access_token": "foobar", "token_type": "bearer", "scope": [""]} |
| 785 |
|
| 786 |
# check the database |
| 787 |
authorizations = OAuth.query.all() |
| 788 |
assert len(authorizations) == 1 |
| 789 |
oauth = authorizations[0] |
| 790 |
assert oauth.provider == "test-service" |
| 791 |
assert isinstance(oauth.token, dict) |
| 792 |
assert oauth.token == expected_token |
| 793 |
|
| 794 |
# cache should be invalidated |
| 795 |
assert cache.get("flask_dance_token|test-service|None") is None |
| 796 |
|
| 797 |
# first reference to the token should generate SQL queries |
| 798 |
with record_queries(db.engine) as queries: |
| 799 |
assert blueprint.token == expected_token |
| 800 |
assert len(queries) == 1 |
| 801 |
|
| 802 |
# should now be in the cache |
| 803 |
assert cache.get("flask_dance_token|test-service|None") == expected_token |
| 804 |
|
| 805 |
# subsequent references should not generate SQL queries |
| 806 |
with record_queries(db.engine) as queries: |
| 807 |
assert blueprint.token == expected_token |
| 808 |
assert len(queries) == 0 |