-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Get nextcloud id from email with another identity provider
- Loading branch information
Showing
4 changed files
with
202 additions
and
81 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,84 +1,19 @@ | ||
import click | ||
import requests | ||
from flask import Blueprint | ||
from flask import current_app | ||
|
||
bp = Blueprint("commands", __name__, cli_group=None) | ||
|
||
|
||
class TooManyUsers(Exception): | ||
"""Exception raised if email returns more than one user. | ||
Attributes: | ||
message -- explanation of the error | ||
""" | ||
|
||
def __init__(self, message="More than one user is using this email"): | ||
self.message = message | ||
super().__init__(self.message) | ||
|
||
|
||
class NoUserFound(Exception): | ||
"""Exception raised if email returns no user. | ||
Attributes: | ||
message -- explanation of the error | ||
""" | ||
|
||
def __init__(self, message="No user with this email was found"): | ||
self.message = message | ||
super().__init__(self.message) | ||
|
||
|
||
@bp.cli.command("get-apps-id") | ||
@click.argument("email") | ||
def get_apps_id(email): | ||
try: | ||
token_response = requests.post( | ||
f"{current_app.config['SECONDARY_IDENTITY_PROVIDER_URI']}/auth/realms/{current_app.config['SECONDARY_IDENTITY_PROVIDER_REALM']}/protocol/openid-connect/token", | ||
headers={"Content-Type": "application/x-www-form-urlencoded"}, | ||
data={ | ||
"grant_type": "client_credentials", | ||
"client_id": f"{current_app.config['SECONDARY_IDENTITY_PROVIDER_CLIENT_ID']}", | ||
"client_secret": f"{current_app.config['SECONDARY_IDENTITY_PROVIDER_CLIENT_SECRET']}", | ||
}, | ||
) | ||
token_response.raise_for_status() | ||
except requests.exceptions.HTTPError as exception: | ||
current_app.logger.error( | ||
"Get token request error: %s, %s", exception, token_response.text | ||
) | ||
raise exception | ||
access_token = token_response.json()["access_token"] | ||
from b3desk.models.users import get_secondary_identity_provider_id_from_email | ||
|
||
try: | ||
users_response = requests.get( | ||
f"{current_app.config['SECONDARY_IDENTITY_PROVIDER_URI']}/auth/admin/realms/{current_app.config['SECONDARY_IDENTITY_PROVIDER_REALM']}/users", | ||
headers={ | ||
"Authorization": f"Bearer {access_token}", | ||
"cache-control": "no-cache", | ||
}, | ||
params={"email": email}, | ||
) | ||
users_response.raise_for_status() | ||
except requests.exceptions.HTTPError as exception: | ||
current_app.logger.error( | ||
"Get user from email request error: %s, %s", exception, users_response.text | ||
secondary_id = get_secondary_identity_provider_id_from_email(email) | ||
current_app.logger.info( | ||
"ID from secondary identity provider for email %s: %s", email, secondary_id | ||
) | ||
raise exception | ||
found_users = users_response.json() | ||
if (user_count := len(found_users)) > 1: | ||
too_many_users_exception = TooManyUsers( | ||
f"There are {user_count} users with the email {email}" | ||
) | ||
current_app.logger.error(too_many_users_exception.message) | ||
raise too_many_users_exception | ||
elif user_count < 1: | ||
no_user_found_exception = NoUserFound( | ||
f"There are no users with the email {email}" | ||
) | ||
current_app.logger.error(no_user_found_exception.message) | ||
raise no_user_found_exception | ||
|
||
[user] = found_users | ||
return user["username"] | ||
except Exception as e: | ||
current_app.logger.error(e) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,11 +1,15 @@ | ||
from datetime import date | ||
|
||
import pytest | ||
import requests | ||
from freezegun import freeze_time | ||
|
||
from b3desk.models import db | ||
from b3desk.models.users import NoUserFound | ||
from b3desk.models.users import TooManyUsers | ||
from b3desk.models.users import User | ||
from b3desk.models.users import get_or_create_user | ||
from b3desk.models.users import get_secondary_identity_provider_id_from_email | ||
from b3desk.models.users import make_nextcloud_credentials_request | ||
|
||
|
||
|
@@ -108,3 +112,75 @@ def test_make_nextcloud_credentials_request_force_secure_for_missing_scheme( | |
headers={"X-API-KEY": app.config["NC_LOGIN_API_KEY"]}, | ||
) | ||
assert credentials["nclocator"].startswith("https://") | ||
|
||
|
||
def test_get_secondary_identity_provider_id_from_email_token_error( | ||
client_app, mocker, caplog | ||
): | ||
class TokenErrorAnswer: | ||
text = "Unable to get token" | ||
|
||
def raise_for_status(): | ||
raise requests.exceptions.HTTPError | ||
|
||
mocker.patch( | ||
"b3desk.models.users.get_secondary_identity_provider_token", | ||
return_value=TokenErrorAnswer, | ||
) | ||
with pytest.raises(requests.exceptions.HTTPError): | ||
get_secondary_identity_provider_id_from_email("[email protected]") | ||
assert "Get token request error:" in caplog.text | ||
|
||
|
||
def test_get_secondary_identity_provider_id_from_email_request_error( | ||
client_app, mocker, caplog, valid_secondary_identity_token | ||
): | ||
class RequestErrorAnswer: | ||
text = "Unable to ask identity provider" | ||
|
||
def raise_for_status(): | ||
raise requests.exceptions.HTTPError | ||
|
||
mocker.patch( | ||
"b3desk.models.users.get_secondary_identity_provider_users_from_email", | ||
return_value=RequestErrorAnswer, | ||
) | ||
with pytest.raises(requests.exceptions.HTTPError): | ||
get_secondary_identity_provider_id_from_email("[email protected]") | ||
assert "Get user from email request error:" in caplog.text | ||
|
||
|
||
def test_get_secondary_identity_provider_id_from_email_many_users( | ||
client_app, app, mocker, valid_secondary_identity_token | ||
): | ||
class ManyUsersAnswer: | ||
def raise_for_status(): | ||
pass | ||
|
||
def json(): | ||
return [{"username": "freddy"}, {"username": "fred"}] | ||
|
||
mocker.patch( | ||
"b3desk.models.users.get_secondary_identity_provider_users_from_email", | ||
return_value=ManyUsersAnswer, | ||
) | ||
with pytest.raises(TooManyUsers): | ||
get_secondary_identity_provider_id_from_email("[email protected]") | ||
|
||
|
||
def test_get_secondary_identity_provider_id_from_email_no_user( | ||
client_app, app, mocker, valid_secondary_identity_token | ||
): | ||
class NoUsersAnswer: | ||
def raise_for_status(): | ||
pass | ||
|
||
def json(): | ||
return [] | ||
|
||
mocker.patch( | ||
"b3desk.models.users.get_secondary_identity_provider_users_from_email", | ||
return_value=NoUsersAnswer, | ||
) | ||
with pytest.raises(NoUserFound): | ||
get_secondary_identity_provider_id_from_email("[email protected]") |