-
Notifications
You must be signed in to change notification settings - Fork 7
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
PP-337 Quicksight dashboard embed URL generation #1378
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
5104cfe
Quicksight dashboard embed URL generation
RishiDiwanTT cdc595f
Pydantic 1.1 under python 3.8 does not allow custom datatypes with Ge…
RishiDiwanTT 397055e
Added test cases for coverage
RishiDiwanTT 4b562bd
Switched from using arrays to a descriptive dict for quicksight ARNs
RishiDiwanTT File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
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 |
---|---|---|
@@ -0,0 +1,117 @@ | ||
import logging | ||
from typing import Dict | ||
|
||
import boto3 | ||
import flask | ||
|
||
from api.admin.model.quicksight import ( | ||
QuicksightDashboardNamesResponse, | ||
QuicksightGenerateUrlRequest, | ||
QuicksightGenerateUrlResponse, | ||
) | ||
from api.controller import CirculationManagerController | ||
from api.problem_details import NOT_FOUND_ON_REMOTE | ||
from core.config import Configuration | ||
from core.model.admin import Admin | ||
from core.model.library import Library | ||
from core.problem_details import INTERNAL_SERVER_ERROR, INVALID_INPUT | ||
from core.util.problem_detail import ProblemError | ||
|
||
|
||
class QuickSightController(CirculationManagerController): | ||
def generate_quicksight_url(self, dashboard_name) -> Dict: | ||
log = logging.getLogger(self.__class__.__name__) | ||
admin: Admin = getattr(flask.request, "admin") | ||
request_data = QuicksightGenerateUrlRequest(**flask.request.args) | ||
|
||
all_authorized_arns = Configuration.quicksight_authorized_arns() | ||
if not all_authorized_arns: | ||
log.error("No Quicksight ARNs were configured for this server.") | ||
raise ProblemError( | ||
INTERNAL_SERVER_ERROR.detailed( | ||
"Quicksight has not been configured for this server." | ||
) | ||
) | ||
|
||
authorized_arns = all_authorized_arns.get(dashboard_name) | ||
if not authorized_arns: | ||
raise ProblemError( | ||
INVALID_INPUT.detailed( | ||
"The requested Dashboard ARN is not recognized by this server." | ||
) | ||
) | ||
|
||
# The first dashboard id is the primary ARN | ||
dashboard_arn = authorized_arns[0] | ||
# format aws:arn:quicksight:<region>:<account id>:<dashboard> | ||
arn_parts = dashboard_arn.split(":") | ||
# Pull the region and account id from the ARN | ||
aws_account_id = arn_parts[4] | ||
region = arn_parts[3] | ||
dashboard_id = arn_parts[5].split("/", 1)[1] # drop the "dashboard/" part | ||
|
||
allowed_libraries = [] | ||
for library in self._db.query(Library).all(): | ||
if admin.is_librarian(library): | ||
allowed_libraries.append(library) | ||
|
||
if request_data.library_ids: | ||
allowed_library_ids = list( | ||
set(request_data.library_ids).intersection( | ||
{l.id for l in allowed_libraries} | ||
) | ||
) | ||
else: | ||
allowed_library_ids = [l.id for l in allowed_libraries] | ||
|
||
if not allowed_library_ids: | ||
raise ProblemError( | ||
NOT_FOUND_ON_REMOTE.detailed( | ||
"No library was found for this Admin that matched the request." | ||
) | ||
) | ||
|
||
libraries = ( | ||
self._db.query(Library).filter(Library.id.in_(allowed_library_ids)).all() | ||
) | ||
|
||
try: | ||
delimiter = "|" | ||
client = boto3.client("quicksight", region_name=region) | ||
response = client.generate_embed_url_for_anonymous_user( | ||
AwsAccountId=aws_account_id, | ||
Namespace="default", # Default namespace only | ||
AuthorizedResourceArns=authorized_arns, | ||
ExperienceConfiguration={ | ||
"Dashboard": {"InitialDashboardId": dashboard_id} | ||
}, | ||
SessionTags=[ | ||
dict( | ||
Key="library_name", | ||
Value=delimiter.join([l.name for l in libraries]), | ||
) | ||
], | ||
) | ||
except Exception as ex: | ||
log.error(f"Error while fetching the Quisksight Embed url: {ex}") | ||
raise ProblemError( | ||
INTERNAL_SERVER_ERROR.detailed( | ||
"Error while fetching the Quisksight Embed url." | ||
) | ||
) | ||
|
||
embed_url = response.get("EmbedUrl") | ||
if response.get("Status") // 100 != 2 or embed_url is None: | ||
log.error(f"QuiskSight Embed url error response {response}") | ||
raise ProblemError( | ||
INTERNAL_SERVER_ERROR.detailed( | ||
"Error while fetching the Quisksight Embed url." | ||
) | ||
) | ||
|
||
return QuicksightGenerateUrlResponse(embed_url=embed_url).api_dict() | ||
|
||
def get_dashboard_names(self): | ||
"""Get the named dashboard IDs defined in the configuration""" | ||
config = Configuration.quicksight_authorized_arns() | ||
return QuicksightDashboardNamesResponse(names=list(config.keys())).api_dict() |
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 |
---|---|---|
@@ -0,0 +1,23 @@ | ||
from typing import List | ||
|
||
from pydantic import Field, validator | ||
|
||
from core.util.flask_util import CustomBaseModel, str_comma_list_validator | ||
|
||
|
||
class QuicksightGenerateUrlRequest(CustomBaseModel): | ||
library_ids: List[int] = Field( | ||
description="The list of libraries to include in the dataset, an empty list is equivalent to all the libraries the user is allowed to access." | ||
) | ||
|
||
@validator("library_ids", pre=True) | ||
def parse_library_ids(cls, value): | ||
return str_comma_list_validator(value) | ||
|
||
|
||
class QuicksightGenerateUrlResponse(CustomBaseModel): | ||
embed_url: str = Field(description="The dashboard embed url.") | ||
|
||
|
||
class QuicksightDashboardNamesResponse(CustomBaseModel): | ||
names: List[str] = Field(description="The named quicksight dashboard ids") |
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,7 +1,7 @@ | ||
import json | ||
import logging | ||
import os | ||
from typing import Dict | ||
from typing import Dict, List | ||
|
||
from flask_babel import lazy_gettext as _ | ||
from sqlalchemy.engine.url import make_url | ||
|
@@ -51,6 +51,10 @@ class Configuration(ConfigurationConstants): | |
OD_FULFILLMENT_CLIENT_KEY_SUFFIX = "OVERDRIVE_FULFILLMENT_CLIENT_KEY" | ||
OD_FULFILLMENT_CLIENT_SECRET_SUFFIX = "OVERDRIVE_FULFILLMENT_CLIENT_SECRET" | ||
|
||
# Quicksight | ||
# Comma separated aws arns | ||
QUICKSIGHT_AUTHORIZED_ARNS_KEY = "QUICKSIGHT_AUTHORIZED_ARNS" | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. See comment above re dictionary. |
||
|
||
# Environment variable for SirsiDynix Auth | ||
SIRSI_DYNIX_APP_ID = "SIMPLIFIED_SIRSI_DYNIX_APP_ID" | ||
|
||
|
@@ -284,6 +288,12 @@ def overdrive_fulfillment_keys(cls, testing=False) -> Dict[str, str]: | |
raise CannotLoadConfiguration("Invalid fulfillment credentials.") | ||
return {"key": key, "secret": secret} | ||
|
||
@classmethod | ||
def quicksight_authorized_arns(cls) -> Dict[str, List[str]]: | ||
"""Split the comma separated arns""" | ||
arns_str = os.environ.get(cls.QUICKSIGHT_AUTHORIZED_ARNS_KEY, "") | ||
return json.loads(arns_str) | ||
|
||
@classmethod | ||
def localization_languages(cls): | ||
return [LanguageCodes.three_to_two["eng"]] | ||
|
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
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Added this in so we can globally manage raising ProblemErrors