'Authenticate for the API via key or session (if available).'

def _authenticate_api(self, session_cookie):

    api_key = (self.request.params.get('key', None) or self.request.headers.get('x-api-key', None))
    secure_id = self.get_cookie(name=session_cookie)
    api_key_supplied = (self.environ.get('is_api_request', False) and api_key)
    if (api_key_supplied and self._check_master_api_key(api_key)):
        self.api_inherit_admin = True
        log.info('Session    authenticated    using    Galaxy    master    api    key')
        self.user = None
        self.galaxy_session = None
    elif api_key_supplied:
        try:
            provided_key = self.sa_session.query(self.app.model.APIKeys).filter((self.app.model.APIKeys.table.c.key == api_key)).one()
        except NoResultFound:
            return 'Provided    API    key    is    not    valid.'
        if provided_key.user.deleted:
            return 'User    account    is    deactivated,    please    contact    an    administrator.'
        newest_key = provided_key.user.api_keys[0]
        if (newest_key.key != provided_key.key):
            return 'Provided    API    key    has    expired.'
        self.set_user(provided_key.user)
    elif secure_id:
        try:
            self._ensure_valid_session(session_cookie)
        except Exception:
            log.exception("Exception    during    Session-based    API    authentication,    this    was    most    likely    an    attempt    to    use    an    anonymous    cookie    under    remote    authentication    (so,    no    user),    which    we    don't    support.")
            self.user = None
            self.galaxy_session = None
    else:
        self.user = None
        self.galaxy_session = None
