Files
notifications-api/app/service/utils.py
Chris Hill-Scott 320bca70f7 Serialise service, API keys and permissions
By serialising these straight away we can:
- not go back to the database later, potentially closing the connection
  sooner
- potentially cache the serialised data, meaning we don’t touch the
  database at all
2020-06-23 16:00:41 +01:00

61 lines
1.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import itertools
from notifications_utils.recipients import allowed_to_send_to
from app.models import (
ServiceWhitelist,
MOBILE_TYPE, EMAIL_TYPE,
KEY_TYPE_TEST, KEY_TYPE_TEAM, KEY_TYPE_NORMAL)
from app.dao.services_dao import dao_fetch_service_by_id
def get_recipients_from_request(request_json, key, type):
return [(type, recipient) for recipient in request_json.get(key)]
def get_whitelist_objects(service_id, request_json):
return [
ServiceWhitelist.from_string(service_id, type, recipient)
for type, recipient in (
get_recipients_from_request(request_json,
'phone_numbers',
MOBILE_TYPE) +
get_recipients_from_request(request_json,
'email_addresses',
EMAIL_TYPE)
)
]
def service_allowed_to_send_to(recipient, service, key_type, allow_whitelisted_recipients=True):
if key_type == KEY_TYPE_TEST:
return True
if key_type == KEY_TYPE_NORMAL and not service.restricted:
return True
# Revert back to the ORM model here so we can get some things which
# arent in the serialised model
service = dao_fetch_service_by_id(service.id)
team_members = itertools.chain.from_iterable(
[user.mobile_number, user.email_address] for user in service.users
)
whitelist_members = [
member.recipient for member in service.whitelist
if allow_whitelisted_recipients
]
if (
(key_type == KEY_TYPE_NORMAL and service.restricted) or
(key_type == KEY_TYPE_TEAM)
):
return allowed_to_send_to(
recipient,
itertools.chain(
team_members,
whitelist_members
)
)