|
1 | 1 | from collections.abc import Sequence |
2 | | -from contextlib import nullcontext |
3 | 2 | from typing import TypedDict |
4 | 3 |
|
5 | 4 | from glom import assign |
6 | | -from pyquery import PyQuery as pq |
7 | | -from requests import Session |
8 | 5 |
|
9 | 6 | from mozilla_django_oidc_db.models import ( |
10 | 7 | OIDCClient, |
|
14 | 11 | from mozilla_django_oidc_db.typing import JSONObject |
15 | 12 |
|
16 | 13 |
|
17 | | -def keycloak_login( |
18 | | - login_url: str, |
19 | | - username: str = "testuser", |
20 | | - password: str = "testuser", |
21 | | - session: Session | None = None, |
22 | | -) -> str: |
23 | | - """ |
24 | | - Test helper to perform a keycloak login. |
25 | | -
|
26 | | - :param login_url: A login URL for keycloak with all query string parameters. E.g. |
27 | | - `client.get(reverse("login"))["Location"]`. |
28 | | - :returns: The redirect URI to consume in the django application, with the ``code`` |
29 | | - ``state`` query parameters. Consume this with ``response = client.get(url)``. |
30 | | - """ |
31 | | - cm = Session() if session is None else nullcontext(session) |
32 | | - with cm as session: |
33 | | - login_page = session.get(login_url) |
34 | | - assert login_page.status_code == 200 |
35 | | - |
36 | | - # process keycloak's login form and submit the username + password to |
37 | | - # authenticate |
38 | | - document = pq(login_page.text) |
39 | | - login_form = document("form#kc-form-login") |
40 | | - submit_url = login_form.attr("action") |
41 | | - assert isinstance(submit_url, str) |
42 | | - login_response = session.post( |
43 | | - submit_url, |
44 | | - data={ |
45 | | - "username": username, |
46 | | - "password": password, |
47 | | - "credentialId": "", |
48 | | - "login": "Sign In", |
49 | | - }, |
50 | | - allow_redirects=False, |
51 | | - ) |
52 | | - |
53 | | - assert login_response.status_code == 302 |
54 | | - assert (redirect_uri := login_response.headers["Location"]).startswith( |
55 | | - "http://testserver/" |
56 | | - ) |
57 | | - |
58 | | - return redirect_uri |
59 | | - |
60 | | - |
61 | 14 | class OIDCConfigOptions(TypedDict, total=False): |
62 | 15 | """ |
63 | 16 | Provider and/or client configuration options, which map to model fields. |
|
0 commit comments