magpie.adapter

Package Contents

Classes

MagpieOWSSecurity

MagpieServiceStore

Registry for OWS services.

SingletonMeta

A metaclass that creates a Singleton base class when called.

MagpieAdapter

Functions

raise_http(http_error: Type[pyramid.httpexceptions.HTTPError] = HTTPInternalServerError, http_kwargs: Optional[magpie.typedefs.ParamsType] = None, detail: magpie.typedefs.Str = '', content: Optional[magpie.typedefs.JSON] = None, content_type: magpie.typedefs.Str = CONTENT_TYPE_JSON, nothrow: bool = False) → NoReturn

Raises error HTTP with standardized information formatted with content type.

valid_http(http_success: Union[Type[pyramid.httpexceptions.HTTPSuccessful], Type[pyramid.httpexceptions.HTTPRedirection]] = HTTPOk, http_kwargs: Optional[magpie.typedefs.ParamsType] = None, detail: Optional[magpie.typedefs.Str] = '', content: Optional[magpie.typedefs.JSON] = None, content_type: Optional[magpie.typedefs.Str] = CONTENT_TYPE_JSON) → Union[pyramid.httpexceptions.HTTPSuccessful, pyramid.httpexceptions.HTTPRedirection]

Returns successful HTTP with standardized information formatted with content type. (see raise_http() for HTTP

get_engine(container: Optional[magpie.typedefs.AnySettingsContainer] = None, prefix: magpie.typedefs.Str = 'sqlalchemy.', **kwargs: Any) → sqlalchemy.engine.base.Engine

get_session_factory(engine)

get_tm_session(session_factory, transaction_manager)

Get a sqlalchemy.orm.Session instance backed by a transaction.

get_auth_config(container: magpie.typedefs.AnySettingsContainer) → pyramid.config.Configurator

Generates Magpie application configuration with all utilities required for security and access control.

get_logger(name: magpie.typedefs.Str, level: Optional[int] = None, force_stdout: bool = None, message_format: Optional[magpie.typedefs.Str] = None, datetime_format: Optional[magpie.typedefs.Str] = None) → logging.Logger

Immediately sets the logger level to avoid duplicate log outputs from the root logger and this logger when

get_magpie_url(container: Optional[magpie.typedefs.AnySettingsContainer] = None) → magpie.typedefs.Str

Obtains the configured Magpie URL entrypoint based on the various combinations of supported configuration settings.

get_settings(container: Optional[magpie.typedefs.AnySettingsContainer], app: bool = False) → magpie.typedefs.SettingsType

Retrieve application settings from a supported container.

debug_cookie_identify(request)

Logs debug information about request cookie.

get_user(request: pyramid.request.Request) → Optional[magpie.models.User]

Obtains the authenticated user from the request (if any).

verify_user(request: pyramid.request.Request) → pyramid.httpexceptions.HTTPException

Verifies that a valid user authentication on the pointed Magpie instance (via configuration) also results into a

Attributes

SigninAPI

CONTENT_TYPE_JSON

LOGGER

class magpie.adapter.MagpieOWSSecurity(request)[source]

Bases: twitcher.owssecurity.OWSSecurityInterface

_get_service_cached(self: magpie.typedefs.Str, service_name)Tuple[magpie.services.ServiceInterface, Dict[str, magpie.typedefs.AnyValue]]

Cache this method with beaker based on the provided caching key parameters.

If the cache is not hit (expired timeout or new key entry), calls get_service() to retrieve the actual ServiceInterface implementation. Otherwise, returns the cached service to avoid SQL queries.

Note

Function arguments are required to generate caching keys by which cached elements will be retrieved.

get_service(self: pyramid.request.Request, request)magpie.services.ServiceInterface

Obtains the service referenced by the request.

Caching is automatically handled according to configured application settings and whether the specific service name being requested was already processed recently and not expired.

check_request(self: pyramid.request.Request, request)Optional[NoReturn]

Verifies if the request user has access to the targeted resource according to parent service and permissions.

If the request path corresponds to configured Twitcher proxy, evaluate the ACL. Otherwise, ignore request access validation.

In the case Twitcher proxy path is matched, the Logged User MUST be allowed access following Effective Permissions resolution via ACL. Otherwise, :exception:`OWSForbidden` is raised. Failing to parse the request or any underlying component also raises that exception.

Raises

OWSForbidden – if user does not have access to the targeted resource under the service.

Returns

nothing if user has access.

update_request_cookies(self, request)

Ensure login of the user and update the request cookies if Twitcher is in a special configuration.

Only update if MAGPIE_COOKIE_NAME is missing and is retrievable from access_token field within the Authorization header. Counter-validate the login procedure by calling Magpie’s /session which should indicate if there is a logged user.

class magpie.adapter.MagpieServiceStore(: pyramid.request.Request, request)[source]

Bases: twitcher.store.ServiceStoreInterface

Registry for OWS services.

Uses magpie to fetch service url and attributes.

abstract save_service(self, service, overwrite=True, request=None)

Magpie store is read-only, use magpie api to add services.

abstract delete_service(self, name, request=None)

Magpie store is read-only, use magpie api to delete services.

list_services(self, request=None)

Lists all services registered in magpie.

_fetch_by_name_cached(self: magpie.typedefs.Str, service_name)twitcher.datatype.Service

Cache this method with beaker based on the provided caching key parameters.

If the cache is not hit (expired timeout or new key entry), calls fetch_by_name() to retrieve the actual twitcher.datatype.Service definition. Otherwise, returns the cached item to avoid SQL queries.

Note

Function arguments are required to generate caching keys by which cached elements will be retrieved.

Note

Method fetch_by_name() gets triggered by twitcher.owsproxy.owsproxy_view() after successful validation of granted access for Logged User to the service / resources following call to magpie.adapter.magpieowssecurity.MagpieOWSSecurity.check_request() in order to send and retrieve the actual response of that proxied service and forward it back to the requesting user. Caching helps greatly reduce recurrent SQL queries to convert Twitcher to Magpie service.

fetch_by_name(self: magpie.typedefs.Str, name)twitcher.datatype.Service

Gets twitcher.datatype.Service corresponding to magpie.models.Service by name.

fetch_by_url(self, url, request=None)

Gets service for given url from mongodb storage.

abstract clear_services(self, request=None)

Magpie store is read-only, use magpie api to delete services.

magpie.adapter.raise_http(http_error: Type[pyramid.httpexceptions.HTTPError] = HTTPInternalServerError, http_kwargs: Optional[magpie.typedefs.ParamsType] = None, detail: magpie.typedefs.Str = '', content: Optional[magpie.typedefs.JSON] = None, content_type: magpie.typedefs.Str = CONTENT_TYPE_JSON, nothrow: bool = False)NoReturn[source]

Raises error HTTP with standardized information formatted with content type.

The content contains the corresponding http error code, the provided message as detail and optional specified additional json content (kwarg dict).

See also

valid_http() for HTTP successful calls

Parameters
  • http_error – any derived class from base HTTPError (default: HTTPInternalServerError)

  • http_kwargs – additional keyword arguments to pass to http_error if called in case of HTTP exception

  • detail – additional message information (default: empty)

  • content – json formatted content to include

  • content_type – format in which to return the exception (one of magpie.common.SUPPORTED_ACCEPT_TYPES)

  • nothrow – returns the error response instead of raising it automatically, but still handles execution errors

Raises

HTTPError – formatted raised exception with additional details and HTTP code

Returns

HTTPError formatted exception with additional details and HTTP code only if nothrow is True

magpie.adapter.valid_http(http_success: Union[Type[pyramid.httpexceptions.HTTPSuccessful], Type[pyramid.httpexceptions.HTTPRedirection]] = HTTPOk, http_kwargs: Optional[magpie.typedefs.ParamsType] = None, detail: Optional[magpie.typedefs.Str] = '', content: Optional[magpie.typedefs.JSON] = None, content_type: Optional[magpie.typedefs.Str] = CONTENT_TYPE_JSON)Union[pyramid.httpexceptions.HTTPSuccessful, pyramid.httpexceptions.HTTPRedirection][source]

Returns successful HTTP with standardized information formatted with content type. (see raise_http() for HTTP error calls)

Parameters
  • http_success – any derived class from valid HTTP codes (<400) (default: HTTPOk)

  • http_kwargs – additional keyword arguments to pass to http_success when called

  • detail – additional message information (default: empty)

  • content – json formatted content to include

  • content_type – format in which to return the exception (one of magpie.common.SUPPORTED_ACCEPT_TYPES)

Returns

formatted successful response with additional details and HTTP code

magpie.adapter.SigninAPI[source]
magpie.adapter.get_engine(container: Optional[magpie.typedefs.AnySettingsContainer] = None, prefix: magpie.typedefs.Str = 'sqlalchemy.', **kwargs: Any)sqlalchemy.engine.base.Engine[source]
magpie.adapter.get_session_factory(engine)[source]
magpie.adapter.get_tm_session(session_factory, transaction_manager)[source]

Get a sqlalchemy.orm.Session instance backed by a transaction.

This function will hook the session to the transaction manager which will take care of committing any changes.

  • When using pyramid_tm it will automatically be committed or aborted depending on whether an exception is raised.

  • When using scripts you should wrap the session in a manager yourself. For example:

    import transaction
    
    engine = get_engine(settings)
    session_factory = get_session_factory(engine)
    with transaction.manager:
        db_session = get_tm_session(session_factory, transaction.manager)
    
magpie.adapter.get_auth_config(container: magpie.typedefs.AnySettingsContainer)pyramid.config.Configurator[source]

Generates Magpie application configuration with all utilities required for security and access control.

magpie.adapter.CONTENT_TYPE_JSON = application/json[source]
class magpie.adapter.SingletonMeta[source]

Bases: type

A metaclass that creates a Singleton base class when called.

Create a class such that:

@six.add_metaclass(SingletonMeta)
class A(object):
    pass

@six.add_metaclass(SingletonMeta)
class B(object):
    pass

a1 = A()
a2 = A()
b1 = B()
b2 = B()
a1 is a2    # True
b1 is b2    # True
a1 is b1    # False
_instances
__call__(cls, *args, **kwargs)

Call self as a function.

magpie.adapter.get_logger(name: magpie.typedefs.Str, level: Optional[int] = None, force_stdout: bool = None, message_format: Optional[magpie.typedefs.Str] = None, datetime_format: Optional[magpie.typedefs.Str] = None)logging.Logger[source]

Immediately sets the logger level to avoid duplicate log outputs from the root logger and this logger when level is logging.NOTSET.

magpie.adapter.get_magpie_url(container: Optional[magpie.typedefs.AnySettingsContainer] = None)magpie.typedefs.Str[source]

Obtains the configured Magpie URL entrypoint based on the various combinations of supported configuration settings.

See also

Documentation section Application Settings for available setting combinations.

Parameters

container – container that provides access to application settings.

Returns

resolved Magpie URL

magpie.adapter.get_settings(container: Optional[magpie.typedefs.AnySettingsContainer], app: bool = False)magpie.typedefs.SettingsType[source]

Retrieve application settings from a supported container.

Parameters
  • container – supported container with an handle to application settings.

  • app – allow retrieving from current thread registry if no container was defined.

Returns

found application settings dictionary.

Raises

TypeError – when no application settings could be found or unsupported container.

magpie.adapter.LOGGER[source]

Logs debug information about request cookie.

Warning

This function is intended for debugging purposes only. It reveals sensible configuration information.

Re-implements basic functionality of pyramid.AuthTktAuthenticationPolicy.cookie.identify() called via request.unauthenticated_userid() within get_user() to provide additional logging.

See also

  • pyramid.authentication.AuthTktCookieHelper

  • pyramid.authentication.AuthTktAuthenticationPolicy

magpie.adapter.get_user(request: pyramid.request.Request)Optional[magpie.models.User][source]

Obtains the authenticated user from the request (if any).

Parameters

request – incoming HTTP request potentially containing authentication definitions.

Returns

the authenticated user if parameters were valid (good credentials, not expired, etc.) or None.

magpie.adapter.verify_user(request: pyramid.request.Request)pyramid.httpexceptions.HTTPException[source]

Verifies that a valid user authentication on the pointed Magpie instance (via configuration) also results into a valid user authentication with the current Twitcher instance to ensure settings match between them.

Parameters

request – an HTTP request with valid authentication token/cookie credentials.

Returns

appropriate HTTP success or error response with details about the result.

class magpie.adapter.MagpieAdapter(container)[source]

Bases: twitcher.adapter.base.AdapterInterface

property name(self)magpie.typedefs.Str[source]
describe_adapter(self)magpie.typedefs.JSON[source]
servicestore_factory(self: pyramid.request.Request, request)magpieservice.MagpieServiceStore[source]
abstract tokenstore_factory(self: pyramid.request.Request, request)twitcher.store.AccessTokenStoreInterface[source]
owssecurity_factory(self: magpie.typedefs.AnySettingsContainer, request)magpieowssecurity.MagpieOWSSecurity[source]
owsproxy_config(self: magpie.typedefs.AnySettingsContainer, container)None[source]
configurator_factory(self: magpie.typedefs.AnySettingsContainer, container)pyramid.config.Configurator[source]