예제 #1
0
    def post(self):
        user = users.get_current_user()
        data = json.loads(self.request.POST["data"])

        if data['general']:
            settings = Settings.get()
            updateMobile = lambda s:None
        else:
            mobile = get_mobile_by_id(data['mobile_id'])
            azzert(mobile.user == user)
            settings = MobileSettings.get(mobile)
            settings.color = data['color']
            mobile.description = data['description']
            if settings.version:
                settings.version += 1
            mobile.put()
            request = UpdateSettingsRequestTO()
            def updateMobile(s):
                request.settings = SettingsTO.fromDBSettings(s, get_app_settings(App.APP_ID_ROGERTHAT))
                logging.info("Updating mobile " + mobile.description)
                updateSettings(update_settings_response_handler, logError, mobile.user, request=request)

        settingsTO = parse_complex_value(SettingsTO, data, False)
        if settingsTO.geoLocationSamplingIntervalBattery < Settings.MINIMUM_INTERVAL:
            return
        if settingsTO.geoLocationSamplingIntervalCharging < Settings.MINIMUM_INTERVAL:
            return
        if settingsTO.xmppReconnectInterval < Settings.MINIMUM_INTERVAL:
            return
        settingsTO.apply(settings)
        settings.put()

        updateMobile(settings)
예제 #2
0
    def __init__(self, configuration):
        super(TffBackendPlugin, self).__init__(configuration)
        self.configuration = parse_complex_value(
            TffConfiguration, configuration, False)  # type: TffConfiguration

        rogerthat_api_plugin = get_plugin('rogerthat_api')
        assert (isinstance(rogerthat_api_plugin, RogerthatApiPlugin))
        rogerthat_api_plugin.subscribe('messaging.flow_member_result',
                                       rogerthat_callbacks.flow_member_result)
        rogerthat_api_plugin.subscribe('messaging.form_update',
                                       rogerthat_callbacks.form_update)
        rogerthat_api_plugin.subscribe('messaging.update',
                                       rogerthat_callbacks.messaging_update)
        rogerthat_api_plugin.subscribe('messaging.poke',
                                       rogerthat_callbacks.messaging_poke)
        rogerthat_api_plugin.subscribe('friend.is_in_roles',
                                       rogerthat_callbacks.friend_is_in_roles)
        rogerthat_api_plugin.subscribe('friend.update',
                                       rogerthat_callbacks.friend_update)
        rogerthat_api_plugin.subscribe('friend.invited',
                                       rogerthat_callbacks.friend_invited)
        rogerthat_api_plugin.subscribe('friend.register',
                                       rogerthat_callbacks.friend_register,
                                       trigger_only=True)
        rogerthat_api_plugin.subscribe(
            'friend.invite_result',
            rogerthat_callbacks.friend_invite_result,
            trigger_only=True)
        rogerthat_api_plugin.subscribe('system.api_call',
                                       rogerthat_callbacks.system_api_call)
        patch_onfido_lib()
예제 #3
0
def _execute_flow(service_identity_user, message_flow_design, message_flow_run_record, members, message_parent_key,
                  context=None, resultKey=None, force_language=None, broadcast_type=None, broadcast_guid=None, tag=None):
    logging.info("Executing message flow for %s with force_language %s" %
                 (service_identity_user.email(), force_language))

    xml_doc = _create_message_flow_run_xml_doc(service_identity_user, message_flow_design, message_flow_run_record,
                                               members, force_language)
    logging.info(xml_doc.toxml())
    xml = xml_doc.toxml("utf-8")

    settings = get_server_settings()

    headers = {
        'X-Nuntiuz-Service-Identifier-Key': get_mfr_sik(service_identity_user).sik,
        'X-Nuntiuz-Service-Identity': base64.b64encode(get_identity_from_service_identity_user(service_identity_user)),
        'X-Nuntiuz-Service-API-Key': get_mfr_api_key(service_identity_user).key().name(),
        'X-Nuntiuz-Shared-Secret': settings.secret,
        'X-Nuntiuz-MessageFlowRunId': message_flow_run_record.messageFlowRunId,
        'X-Nuntiuz-MessageParentKey': message_parent_key if message_parent_key else "",
        'X-Nuntiuz-Context': context if context else "",
        'X-Nuntiuz-ResultKey': resultKey,
        'Content-type': 'text/xml'
    }

    if broadcast_guid:
        headers['X-Nuntiuz-BroadcastGuid'] = broadcast_guid
    if tag:
        headers['X-Nuntiuz-Tag'] = tag.encode('utf')

    logging.debug('Executing flow with run id %s for members %s', message_flow_run_record.messageFlowRunId, members)
    result = urlfetch.fetch(
        "%s/api" % settings.messageFlowRunnerAddress, xml, "POST", headers, False, False, deadline=10 * 60)
    if result.status_code != 200:
        error_message = "MFR returned status code %d" % result.status_code
        if result.status_code == 400:
            logging.error(error_message, _suppress=False)
            raise deferred.PermanentTaskFailure(error_message)
        raise Exception(error_message)

    logging.debug('MFR response: %s', result.content)
    if len(members) == 1 and result.content:
        try:
            flow_start_result = parse_complex_value(FlowStartResultCallbackResultTO, json.loads(result.content), False)
            if isinstance(flow_start_result.value, MessageCallbackResultTypeTO):
                sendMessage(service_identity_user, [UserMemberTO(members[0], flow_start_result.value.alert_flags)],
                            flow_start_result.value.flags, 0, message_parent_key, flow_start_result.value.message,
                            flow_start_result.value.answers, None, flow_start_result.value.branding,
                            flow_start_result.value.tag, flow_start_result.value.dismiss_button_ui_flags, context,
                            key=resultKey, is_mfr=True, broadcast_type=broadcast_type, broadcast_guid=broadcast_guid,
                            attachments=flow_start_result.value.attachments,
                            step_id=None if flow_start_result.value.step_id is MISSING else flow_start_result.value.step_id)
            elif isinstance(flow_start_result.value, FormCallbackResultTypeTO):
                sendForm(service_identity_user, message_parent_key, members[0], flow_start_result.value.message,
                         flow_start_result.value.form, flow_start_result.value.flags, flow_start_result.value.branding,
                         flow_start_result.value.tag, flow_start_result.value.alert_flags, context, key=resultKey,
                         is_mfr=True, broadcast_type=broadcast_type, attachments=flow_start_result.value.attachments,
                         broadcast_guid=broadcast_guid,
                         step_id=None if flow_start_result.value.step_id is MISSING else flow_start_result.value.step_id)
        except:
            logging.exception("Failed to parse result from message flow runner.")
예제 #4
0
def get_payment_assets(app_user, currency=None):
    args = dict()
    args["app_user"] = app_user.email()
    result = _execute_payment_request(u'assets', args)
    if not result:
        return []
    return parse_complex_value(PaymentProviderAssetTO, result, True)
예제 #5
0
def update_presence(params, user_detail):
    presence = parse_complex_value(BasePresenceTO, params, False)
    iyo_username = get_iyo_username(user_detail)
    participant = EventParticipant.get_or_create_participant(presence.event_id, iyo_username)
    participant.status = presence.status
    participant.wants_recording = presence.wants_recording
    participant.put()
    return participant.to_dict()
예제 #6
0
def merge_steps(flow_run, new_steps):
    # In case of sub flows, new_steps won't contain steps from the previous flow.
    steps = parse_complex_value(object_factory('step_type', FLOW_STEP_MAPPING),
                                flow_run.steps, True)
    saved_step_ids = [step.step_id for step in steps]
    for step in new_steps:
        if step.step_id not in saved_step_ids:
            steps.append(step)
    return steps
예제 #7
0
def _get_transactions_by_type(asset_id, transaction_type, cursor):
    args = dict()
    args["asset_id"] = asset_id
    args["transaction_type"] = transaction_type
    if cursor:
        args["cursor"] = cursor
    result = _execute_payment_request(u'transactions', args)
    if not result:
        return [], None
    to = parse_complex_value(GetPaymentTransactionsResponseTO, result, False)
    return to.transactions, to.cursor
예제 #8
0
def get_oauth_identity(identity_url, access_token, response_type, identity_url_parameters=None):
    if identity_url_parameters is None:
        identity_url_parameters = {}
    headers = {"Authorization": access_token,
               'Accept': "application/json"}

    response = urlfetch.fetch(identity_url % identity_url_parameters, method=urlfetch.GET, headers=headers, deadline=20)
    logging.debug(response.content)
    if response.status_code == httplib.OK:
        return parse_complex_value(response_type, json.loads(response.content), False)
    else:
        logging.error('%s responded with status code %s.\n%s', identity_url, response.status_code, response.content)
        raise BusinessException('Could not get oauth identity')
예제 #9
0
 def put(self, *args, **kwargs):
     GenericRESTRequestHandler.setCurrent(self.request, self.response)
     f = self.get_handler('put', self.request.route)
     if not f:
         return
     self.update_kwargs(f, kwargs)
     post_data_type = f.meta['kwarg_types'].get('data')
     if post_data_type:
         is_list = type(post_data_type) is list
         if is_list:
             post_data_type = post_data_type[0]
         post_data = json.loads(self.request.body) if self.request.body else {}
         kwargs['data'] = parse_complex_value(post_data_type, post_data, is_list)
     self.write_result(self.run(f, args, kwargs))
예제 #10
0
def get_bank_details(iban):
    """
    Args:
        iban (unicode)
    Returns:
        OpenIbanResultTO
    """
    response = urlfetch.fetch('https://openiban.com/validate/%s?getBIC=true' % iban)
    if response.status_code != httplib.OK:
        raise BusinessException('Could not fetch bank details.\'Status: %s\'Content: %s', response.status_code,
                                response.content)
    json_result = json.loads(response.content)
    logging.debug('Bank details for iban %s: %s', iban, json_result)
    return parse_complex_value(OpenIbanResultTO, json_result, False)
 def __init__(self, configuration):
     super(RogerthatApiPlugin, self).__init__(configuration)
     self.configuration = parse_complex_value(RogerthatApiPluginConfiguration,
                                              configuration if configuration is not MISSING else {},
                                              False)  # type: RogerthatApiPluginConfiguration
     if self.configuration.rogerthat_server_url is MISSING \
         or not self.configuration.rogerthat_server_url \
             or self.configuration.rogerthat_server_url == 'https://rogerth.at':
         logging.warn('[RogerthatApiPlugin]: Set the \'rogerthat_server_url\' in the configuration file'
                      'to an appengine application url (<project-id>.appspot.com) to decrease the latency of the'
                      ' requests to rogerthat.')
         self.configuration.rogerthat_server_url = 'https://rogerth.at'
     elif 'localhost' in self.configuration.rogerthat_server_url and not DEBUG:
         logging.error('Invalid rogerthat_server_url %s', self.configuration.rogerthat_server_url)
예제 #12
0
def form_update(rt_settings, request_id, status, form_result, answer_id, member, message_key, tag, received_timestamp,
                acked_timestamp, parent_message_key, result_key, service_identity, user_details, **kwargs):
    if not is_flag_set(Message.STATUS_ACKED, status):
        return None

    user_details = log_and_parse_user_details(user_details)
    form_result = parse_complex_value(FormResultTO, form_result, False)

    f = FMR_TAG_MAPPING.get(parse_to_human_readable_tag(tag))
    if not f:
        return None

    result = f(status, form_result, answer_id, member, message_key, tag, received_timestamp, acked_timestamp,
               parent_message_key, result_key, service_identity, user_details)
    return result and serialize_complex_value(result, FormAcknowledgedCallbackResultTO, False, skip_missing=True)
def import_service_data(service_user, zip_file):
    zip_file = zipfile.ZipFile(StringIO(zip_file))
    brandings = []
    menu = None
    roles = []
    # list of tuples (branding_id, branding_content)
    branding_contents = []  # type: tuple(unicode, unicode)
    message_flows = []
    try:
        for file_name in set(zip_file.namelist()):
            if file_name == 'brandings.json':
                brandings = parse_complex_value(BrandingTO, json.loads(zip_file.read(file_name)), True)
            elif file_name == 'menu.json':
                menu = parse_complex_value(WebServiceMenuTO, json.loads(zip_file.read(file_name)), False)
            elif file_name == 'roles.json':
                roles = parse_complex_value(RoleTO, json.loads(zip_file.read(file_name)), True)  # type:list[RoleTO]
            elif '/' in file_name:
                folder = file_name.split('/')[0]
                if folder == 'message_flows':
                    message_flows.append(
                        parse_complex_value(ExportMessageFlowDesignTO, json.loads(zip_file.read(file_name)), False))
                elif folder == 'brandings':
                    branding_hash = file_name.split('/')[1].replace('.zip', '')
                    branding_contents.append((branding_hash, zip_file.read(file_name)))
    finally:
        zip_file.close()
    import_brandings_result = _import_brandings(service_user, brandings, branding_contents)
    _import_flows(service_user, message_flows, import_brandings_result)
    new_roles = _import_roles(service_user, roles)
    role_mapping = {}
    for old_role in roles:
        for new_role in new_roles:
            if old_role.name == new_role.name:
                role_mapping[old_role.id] = new_role.role_id
    if menu:
        _import_menu(service_user, menu, role_mapping)
예제 #14
0
 def put(self, *args, **kwargs):
     GenericRESTRequestHandler.setCurrent(self.request, self.response)
     f = self.get_handler('put', self.request.route)
     if not f:
         return
     self.update_kwargs(f, kwargs)
     post_data_type = f.meta['kwarg_types'].get('data')
     if post_data_type:
         is_list = type(post_data_type) is list
         if is_list:
             post_data_type = post_data_type[0]
         post_data = json.loads(
             self.request.body) if self.request.body else {}
         kwargs['data'] = parse_complex_value(post_data_type, post_data,
                                              is_list)
     self.write_result(self.run(f, args, kwargs))
예제 #15
0
    def post(self):
        app_id = self.request.POST.get("app_id", None)
        azzert(app_id is not None, "app_id is not found")
        azzert(app_id is not "com.mobicage.osa.launcher", "app_id is invalid")

        mobileInfo = self.request.POST.get("mobileInfo", None)
        logging.debug("GetOSALaucherAppsHandler mobileInfo: %s" % mobileInfo)
        azzert(mobileInfo is not None, "mobileInfo is not found")
        mobileInfoJSON = json.loads(mobileInfo)
        mobileInfo = parse_complex_value(MobileInfoTO, mobileInfoJSON, False)

        result = []

        for a in OSALauncherApp.all():
            result.append({"app_id": a.app_id, "version_code": a.version_code})

        r = json.dumps(dict(result=result))
        self.response.out.write(r)
예제 #16
0
def get_oauth_access_token(access_token_url, client_id, client_secret, code, redirect_url, state,
                           grant_type=None):
    params = urllib.urlencode({
        'client_id': client_id,
        'client_secret': client_secret,
        'code': code,
        'redirect_uri': redirect_url,
        'state': state,
        'grant_type': grant_type if grant_type else ""
    })

    headers = {'Accept': "application/json"}
    response = urlfetch.fetch(access_token_url, payload=params, method=urlfetch.POST, headers=headers, deadline=20,
                              validate_certificate=not DEBUG)
    logging.debug(response.content)
    if response.status_code == httplib.OK:
        return parse_complex_value(OauthAccessTokenTO, json.loads(response.content), False)
    else:
        logging.error('%s responded with status code %s.\n%s\n%s', access_token_url, response.status_code, params, response.content)
        raise BusinessException('Could not get oauth access token')
예제 #17
0
def flow_member_result(rt_settings, request_id, message_flow_run_id, member,
                       steps, end_id, end_message_flow_id, parent_message_key,
                       tag, result_key, flush_id, flush_message_flow_id,
                       service_identity, user_details, flow_params, **kwargs):
    user_details = log_and_parse_user_details(user_details)
    steps = parse_complex_value(object_factory("step_type", FLOW_STEP_MAPPING),
                                steps, True)

    f = FMR_TAG_MAPPING.get(parse_to_human_readable_tag(tag))
    if not f:
        logging.info('[tff] Ignoring flow_member_result with tag %s', tag)
        return None

    result = f(message_flow_run_id, member, steps, end_id, end_message_flow_id,
               parent_message_key, tag, result_key, flush_id,
               flush_message_flow_id, service_identity, user_details,
               flow_params)

    return result and serialize_complex_value(
        result, FlowMemberResultCallbackResultTO, False, skip_missing=True)
예제 #18
0
def flow_member_result(rt_settings, request_id, message_flow_run_id, member, steps, end_id, end_message_flow_id,
                       parent_message_key, tag, result_key, flush_id, flush_message_flow_id, service_identity,
                       user_details, flow_params, timestamp, **kwargs):
    user_details = log_and_parse_user_details(user_details)
    steps = parse_complex_value(object_factory("step_type", FLOW_STEP_MAPPING), steps, True)

    f = FMR_TAG_MAPPING.get(parse_to_human_readable_tag(tag))
    should_process_flush = f and not flush_id.startswith('flush_monitoring')

    result = None
    try:
        if should_process_flush:
            logging.info('Processing flow_member_result with tag %s and flush_id %s', tag, flush_id)
            result = f(message_flow_run_id, member, steps, end_id, end_message_flow_id, parent_message_key, tag,
                       result_key, flush_id, flush_message_flow_id, service_identity, user_details, flow_params)
            return result and serialize_complex_value(result, FlowMemberResultCallbackResultTO, False,
                                                      skip_missing=True)
        else:
            logging.info('[tff] Ignoring flow_member_result with tag %s and flush_id %s', tag, flush_id)
    finally:
        deferred.defer(save_flow_statistics, parent_message_key, steps, end_id, tag, flush_id, flush_message_flow_id,
                       user_details[0], timestamp, result)
    def __init__(self, configuration):
        super(ItsYouOnlineAuthPlugin, self).__init__(configuration)
        self.configuration = parse_complex_value(ItsYouOnlineConfiguration, configuration,
                                                 False)  # type: ItsYouOnlineConfiguration
        if self.configuration.api_domain is MISSING:
            self.configuration.api_domain = u'itsyou.online'
        if self.configuration.iyo_public_key is MISSING:
            # key from https://itsyou.online by default
            self.configuration.iyo_public_key = """-----BEGIN PUBLIC KEY-----
MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAES5X8XrfKdx9gYayFITc89wad4usrk0n2
7MjiGYvqalizeSWTHEpnd7oea9IQ8T5oJjMVH5cc0H5tFSKilFFeh//wngxIyny6
6+Vq5t5B0V0Ehy01+2ceEon2Y0XDkIKv
-----END PUBLIC KEY-----"""
        if self.configuration.fetch_information is MISSING:
            self.configuration.fetch_information = False
        rogerthat_api_plugin = get_plugin('rogerthat_api')
        assert isinstance(rogerthat_api_plugin, RogerthatApiPlugin)
        rogerthat_api_plugin.subscribe('friend.register', friend_register)
        self.base_uri = u'https://%s/' % self.configuration.api_domain
        self.api_uri = u'%sapi' % self.base_uri
        self.oauth_base_url = '%sv1/oauth' % self.base_uri
        HTTPClient._handle_data = _new_handle_data
예제 #20
0
def broadcast(api_key, broadcast_type, message, answers, flags, branding, tag, service_identity=None,
              alert_flags=Message.ALERT_FLAG_VIBRATE, dismiss_button_ui_flags=0, target_audience=None, attachments=None,
              timeout=0, json_rpc_id=None):
    method = 'messaging.broadcast'
    if not attachments:
        attachments = list()
    params = dict(
        broadcast_type=broadcast_type,
        message=message,
        answers=serialize_complex_value(answers, AnswerTO, True, skip_missing=True),
        flags=flags,
        branding=branding,
        tag=tag,
        service_identity=service_identity,
        alert_flags=alert_flags,
        dismiss_button_ui_flags=dismiss_button_ui_flags,
        target_audience=serialize_complex_value(target_audience, BroadcastTargetAudienceTO, False, skip_missing=True),
        attachments=serialize_complex_value(attachments, AttachmentTO, True, skip_missing=True),
        timeout=timeout
    )
    result = call_rogerthat(api_key, method, params, json_rpc_id)
    return parse_complex_value(BroadcastResultTO, result, False)
예제 #21
0
    def test_mix_type_property(self):
        class MyLittleTO(object):
            name = unicode_property('name')
            age = long_property('age')

            def __str__(self):
                return u"%s is %s years old" % (self.name, self.age)

            def __eq__(self, other):
                return self.name == other.name and self.age == other.age

        class MyPetTO(object):
            person = typed_property('person', (unicode, MyLittleTO))
            crew = typed_property('crew', (unicode, MyLittleTO), True)

        felix = MyPetTO()
        felix.person = u"nice"
        felix.crew = [u"bart", u"donatello"]

        ceaser = MyPetTO()
        ceaser.person = MyLittleTO()
        ceaser.person.name = u"ceaser"
        ceaser.person.age = 35
        ceaser.crew = [u"bart", MyLittleTO()]
        ceaser.crew[1].name = u"donatello"
        ceaser.crew[1].age = 34

        for person in ceaser.crew:
            print person

        serialized = serialize_complex_value(ceaser, MyPetTO, False)
        print serialized
        ceaser2 = parse_complex_value(MyPetTO, serialized, False)
        self.assertEquals(ceaser.person.name, ceaser2.person.name)
        self.assertEquals(ceaser.person.age, ceaser2.person.age)
        self.assertEquals(ceaser.crew[0], ceaser2.crew[0])
        self.assertEquals(ceaser.crew[1], ceaser2.crew[1])
예제 #22
0
 def from_dict(cls, data):
     # type: (Type[TO_TYPE], dict) -> TO_TYPE
     return parse_complex_value(cls, data, False)
예제 #23
0
 def attachments(self):
     return parse_complex_value(AttachmentTO,
                                json.loads(self.json_attachments), True)
 def from_dict(cls, data):
     return parse_complex_value(cls, data, False)
예제 #25
0
 def from_list(cls, data):
     # type: (Type[TO_TYPE], list[dict]) -> list[TO_TYPE]
     return parse_complex_value(cls, data, True)
    def post(self):
        from rogerthat.bizz.registration import finish_registration
        account = self.request.POST['account']
        password = self.request.POST['password']
        accounts = self.request.POST.get('accounts', u"[]")
        if not users.set_json_rpc_user(account, password, True):
            self.response.set_status(401, "could not authenticate")
            return

        app_id = self.request.POST.get("app_id", App.APP_ID_ROGERTHAT)
        app = _verify_app_id(app_id)
        azzert(app is not None, "app_id is not found")

        mobileInfoJSON = json.loads(self.request.POST["mobileInfo"])
        if mobileInfoJSON.get('version', 1) == 1:
            oldMobileInfo = parse_complex_value(DeprecatedMobileInfoTO, mobileInfoJSON, False)
            mobileInfo = MobileInfoTO.fromDeprecatedMobileInfoTO(oldMobileInfo)
        else:
            mobileInfo = parse_complex_value(MobileInfoTO, mobileInfoJSON, False)

        invitor_code = self.request.POST.get('invitor_code')
        invitor_secret = self.request.POST.get('invitor_secret')

        beaconsString = self.request.POST.get('beacons')
        if beaconsString:
            beacons = json.loads(beaconsString)
        else:
            beacons = mobileInfoJSON.get('beacons')  # Beacons where places inside mobile info in 1.0.161.I

        ipaddress = os.environ.get('HTTP_X_FORWARDED_FOR', None)
        if not ipaddress:
            server_settings = get_server_settings()
            xmpp.send_message(server_settings.xmppInfoMembers, "Received finish registration request without origin ipaddress!")
        else:
            ipaddress = unicode(ipaddress)

        mobile = finish_registration(account, mobileInfo, accounts, invitor_code, invitor_secret, ipaddress)

        discoveredBeacons = dict()
        if beacons:
            logging.info("User discovered the following beacons during registration: %s", beacons)
            for b in beacons:
                beacon_discovered_request_to = parse_complex_value(BeaconDiscoveredRequestTO, b, False)
                beacon_uuid = beacon_discovered_request_to.uuid.lower()
                beacon = get_beacon(beacon_uuid, beacon_discovered_request_to.name)
                if not beacon:
                    logging.warn("Beacon not found uuid: %s name: %s" % (beacon_uuid, beacon_discovered_request_to.name))
                else:
                    friend_map = get_friends_map(mobile.user)
                    if remove_slash_default(beacon.service_identity_user) not in friend_map.friends:
                        si = get_service_identity(beacon.service_identity_user)
                        if si.beacon_auto_invite:
                            if app_id in si.appIds:
                                translator = get_translator(si.service_user, [ServiceTranslation.IDENTITY_TEXT], mobile.localeLanguage)
                                discoveredBeacons[beacon.service_identity_user] = dict(name=translator.translate(ServiceTranslation.IDENTITY_TEXT, si.name, mobile.localeLanguage),
                                                                                       avatar_url=si.avatarUrl,
                                                                                       friend_email=remove_slash_default(beacon.service_identity_user).email())
                            else:
                                logging.info("Beacon detected but %s does not contain app_id %s: {uuid: %s, name: %s}",
                                            beacon.service_identity_user, app_id, beacon_uuid, beacon_discovered_request_to.name)
                        else:
                            logging.info("Beacon detected but %s does not allow auto invite {app_id %s, uuid: %s, name: %s}",
                                            beacon.service_identity_user, app_id, beacon_uuid, beacon_discovered_request_to.name)
        r = json.dumps(dict(discovered_beacons=sorted(discoveredBeacons.values(), key=lambda x: x['name'])))
        logging.info("User discovered the following new beacons during registration: %s", r)
        self.response.out.write(r)
 def from_list(cls, data):
     return parse_complex_value(cls, data, True)
예제 #28
0
def get_payment_asset(app_user, asset_id):
    result = _execute_payment_request(u'assets/%s' % urllib.quote(asset_id), dict())
    if not result:
        return None
    return parse_complex_value(PaymentProviderAssetTO, result, False)
 def __init__(self, configuration):
     super(RogerthatControlCenterPlugin, self).__init__(configuration)
     self.configuration = parse_complex_value(RogerthatControlCenterConfiguration, configuration,
                                              False)  # type: RogerthatControlCenterConfiguration
     JINJA_ENVIRONMENT.add_extension(CopyrightExtension)
def log_and_parse_user_details(user_details):
    # type: (dict) -> UserDetailsTO
    user_detail = user_details[0] if isinstance(user_details, list) else user_details
    logging.debug('Current user: %(email)s:%(app_id)s', user_detail)
    return parse_complex_value(UserDetailsTO, user_detail, False)
예제 #31
0
    def post(self):
        success = False
        app_id = self.request.POST.get("app_id_hidden", None)
        name = self.request.POST.get("name", None)
        app_type = self.request.POST.get("app_type", None)
        fb_app_id = self.request.POST.get("fb_app_id", None)
        ios_app_id = self.request.POST.get("ios_app_id", None)
        android_app_id = self.request.POST.get("android_app_id", None)
        dashboard_email_address = self.request.POST.get("dashboard_email_address", None)
        contact_email_address = self.request.POST.get("contact_email_address", None)
        user_regex = self.request.POST.get("user_regex", None)
        qr_templates_count = int(self.request.POST.get("qr_templates_count", 0))
        default_qr_template_index = int(self.request.POST.get("default_qr_template_index", 0))
        has_core_branding = self.request.POST.get("has_core_branding", None)
        auto_connected_services_string = self.request.POST.get("auto_connected_services", "[]")
        logging.debug("auto_connected_services = %s", auto_connected_services_string)
        auto_connected_services = parse_complex_value(AutoConnectedService,
                                                      json.loads(auto_connected_services_string),
                                                      True)
        admin_services = json.loads(self.request.POST.get('admin_services', '[]'))
        qr_templates_to_delete = json.loads(self.request.POST.get("qr_templates_to_delete", "[]"))
        beacon_regions = json.loads(self.request.POST.get("beacon_regions", "[]"))
        beacon_major_str = self.request.POST.get("beacon_major", 0)
        beacon_major = int(beacon_major_str) if beacon_major_str else 0
        demo = bool(self.request.POST.get("demo", ''))
        beta = bool(self.request.POST.get("beta", ''))
        mdp_client_id = self.request.POST.get('mdp_client_id', None)
        mdp_client_secret = self.request.POST.get('mdp_client_secret', None)

        try:
            has_core_branding = None if not has_core_branding else int(has_core_branding)
        except Exception:
            has_core_branding = None

        try:
            app_type = None if not app_type else int(app_type)
        except Exception:
            app_type = None

        try:
            fb_app_id = None if not fb_app_id else int(fb_app_id)
        except Exception:
            fb_app_id = None

        if not app_id:
            result = "BUG!!! Failed to update app (app_id was empty)!"
        if not name:
            result = "Failed to update app (name was empty)!"
        elif app_type is None:
            result = "Failed to update app (app_type was empty)!"
        elif not ios_app_id:
            result = "Failed to update app (ios_app_id was empty)!"
        elif not android_app_id:
            result = "Failed to update app (android_app_id was empty)!"
        elif not dashboard_email_address:
            result = "Failed to update app (dashboard_email_address was empty)!"
        else:
            app = get_app_by_id(app_id)
            if app:
                try:
                    if user_regex:
                        validate_user_regex(user_regex)

                    to_be_put = [app]
                    app.name = name
                    app.type = app_type

                    if has_core_branding:
                        zip_stream = self.request.POST.get('core_branding').file
                        zip_stream.seek(0)
                        try:
                            zip_ = ZipFile(zip_stream)
                        except BadZipfile, e:
                            raise BrandingValidationException(e.message)

                        branding = store_branding_zip(None, zip_, u"Core branding of %s" % app_id)
                        app.core_branding_hash = branding.hash

                    for qr_template_key_name in qr_templates_to_delete:
                        app.qrtemplate_keys.remove(qr_template_key_name)

                    for i in xrange(qr_templates_count):
                        description = self.request.POST.get("qr_template_description_%s" % i)
                        key_name = create_qr_template_key_name(app_id, description)
                        if self.request.POST.get('qr_template_new_%s' % i) == "1":
                            file_ = self.request.POST.get('qr_template_%s' % i)
                            color = self.request.POST.get("qr_template_color_%s" % i)
                            file_ = file_.file.getvalue() if isinstance(file_, FieldStorage) else None
                            store_template(None, file_, description, color, key_name)
                            if default_qr_template_index == i:
                                app.qrtemplate_keys.insert(0, key_name)
                            else:
                                app.qrtemplate_keys.append(key_name)
                        else:
                            if default_qr_template_index == i:
                                app.qrtemplate_keys.remove(key_name)
                                app.qrtemplate_keys.insert(0, key_name)

                    app.facebook_app_id = fb_app_id
                    app.ios_app_id = ios_app_id
                    app.android_app_id = android_app_id
                    app.dashboard_email_address = dashboard_email_address
                    app.contact_email_address = contact_email_address
                    app.user_regex = user_regex
                    app.demo = demo
                    app.beta = beta
                    app.mdp_client_id = mdp_client_id or None
                    app.mdp_client_secret = mdp_client_secret or None

                    old_auto_connected_services = {acs.service_identity_email for acs in app.auto_connected_services}

                    app.auto_connected_services = AutoConnectedServices()
                    for acs in auto_connected_services:
                        service_identity_user = add_slash_default(users.User(acs.service_identity_email))
                        si = get_service_identity(service_identity_user)
                        bizz_check(si, "ServiceIdentity %s not found" % service_identity_user)
                        if app_id not in si.appIds:
                            si.appIds.append(app_id)
                            to_be_put.append(si)

                        acs.service_identity_email = service_identity_user.email()
                        app.auto_connected_services.add(acs)

                    admin_profiles = db.get([get_profile_key(u) for u in map(users.User, admin_services)])
                    non_existing = list()
                    for admin_email, admin_profile in zip(admin_services, admin_profiles):
                        if not admin_profile:
                            non_existing.append(admin_email)
                    bizz_check(not non_existing, "Non existing services specified: %s" % non_existing)
                    app.admin_services = admin_services

                    old_beacon_regions = list(app.beacon_regions(keys_only=True))
                    new_beacon_regions = list()

                    should_update_beacon_regions = False

                    for beacon_region in beacon_regions:
                        uuid = beacon_region.get("uuid")
                        major = beacon_region.get("major")
                        minor = beacon_region.get("minor")
                        br_key = BeaconRegion.create_key(app.key(), uuid, major, minor)
                        new_beacon_regions.append(br_key)
                        if br_key not in old_beacon_regions:
                            should_update_beacon_regions = True
                            br = BeaconRegion(key=br_key)
                            br.uuid = uuid.lower()
                            br.major = major
                            br.minor = minor
                            br.creation_time = now()
                            to_be_put.append(br)

                    to_be_deleted = []
                    for beacon_region_key in old_beacon_regions:
                        if beacon_region_key not in new_beacon_regions:
                            should_update_beacon_regions = True
                            to_be_deleted.append(beacon_region_key)

                    app.beacon_major = beacon_major
                    app.beacon_last_minor = app.beacon_last_minor if app.beacon_last_minor else 0

                    put_and_invalidate_cache(*to_be_put)
                    if to_be_deleted:
                        db.delete(db.get(to_be_deleted))

                    for acs in app.auto_connected_services:
                        if acs.service_identity_email not in old_auto_connected_services:
                            logging.info("There is a new auto-connected service: %s", acs.service_identity_email)
                            run_job(get_user_profile_keys_by_app_id, [app_id],
                                    hookup_with_default_services.run_for_auto_connected_service, [acs, None])

                    if should_update_beacon_regions:
                        schedule_update_beacon_regions_for_all_users(app_id)

                    result = "Updated app!"
                    success = True
                except BusinessException, e:
                    logging.info("BusinessException: %s", e, exc_info=1)
                    result = e.message
                except Exception, e:
                    logging.exception(str(e), exc_info=1)
                    result = "Unknown error has occurred."
예제 #32
0
def log_and_parse_user_details(user_details):
    # type: (dict) -> UserDetailsTO
    is_list = isinstance(user_details, list)
    user_detail = user_details[0] if is_list else user_details
    logging.debug('Current user: %(email)s:%(app_id)s', user_detail)
    return parse_complex_value(UserDetailsTO, user_details, is_list)
예제 #33
0
def friend_is_in_roles(rt_settings, request_id, service_identity, user_details,
                       roles, **kwargs):
    user_details = log_and_parse_user_details(user_details)
    roles = parse_complex_value(RoleTO, roles, True)
    return is_user_in_roles(user_details[0], roles)
예제 #34
0
def finish_registration(mobile_account, mobileInfo, invitor_code, invitor_secret, ipaddress, anonymous_account=None):
    from rogerthat.service.api import friends as service_api_friends
    m = get_mobile_by_account(mobile_account)
    mobile_key = m.key()
    ms_key = get_mobile_settings_cached(m).key()
    profile_key = get_user_profile_key(m.user)

    def trans():
        mobile, ms, my_profile = db.get((mobile_key, ms_key, profile_key))

        mobile.status = mobile.status | Mobile.STATUS_REGISTERED
        mobile.type = mobileInfo.app_type
        mobile.simCountry = mobileInfo.sim_country if mobileInfo.sim_country != MISSING else None
        mobile.simCountryCode = mobileInfo.sim_country_code if mobileInfo.sim_country_code != MISSING else None
        mobile.simCarrierCode = mobileInfo.sim_carrier_code if mobileInfo.sim_carrier_code != MISSING else None
        mobile.simCarrierName = mobileInfo.sim_carrier_name if mobileInfo.sim_carrier_name != MISSING else None
        mobile.netCountry = mobileInfo.net_country if mobileInfo.net_country != MISSING else None
        mobile.netCountryCode = mobileInfo.net_country_code if mobileInfo.net_country_code != MISSING else None
        mobile.netCarrierCode = mobileInfo.net_carrier_code if mobileInfo.net_carrier_code != MISSING else None
        mobile.netCarrierName = mobileInfo.net_carrier_name if mobileInfo.net_carrier_name != MISSING else None
        mobile.hardwareModel = mobileInfo.device_model_name
        mobile.osVersion = mobileInfo.device_os_version if mobileInfo.device_os_version != MISSING else None
        mobile.localeLanguage = mobileInfo.locale_language if mobileInfo.locale_language and mobileInfo.locale_language != MISSING else DEFAULT_LANGUAGE
        mobile.localeCountry = mobileInfo.locale_country
        mobile.timezone = mobileInfo.timezone if mobileInfo.timezone != MISSING else None
        mobile.timezoneDeltaGMT = mobileInfo.timezone_delta_gmt if mobileInfo.timezone_delta_gmt != MISSING else None

        if mobileInfo.app_major_version != MISSING and mobileInfo.app_minor_version != MISSING:
            ms.majorVersion = mobileInfo.app_major_version
            ms.minorVersion = mobileInfo.app_minor_version

        # This is the official place where we set the profile language
        my_profile.language = mobile.localeLanguage
        my_profile.country = mobile.netCountry or mobile.simCountry or mobile.localeCountry
        my_profile.timezone = mobile.timezone
        my_profile.timezoneDeltaGMT = mobile.timezoneDeltaGMT

        my_profile.mobiles = MobileDetails()
        my_profile.mobiles.addNew(mobile.account, mobile.type, mobile.pushId, mobile.app_id)

        put_and_invalidate_cache(mobile, ms, my_profile)

        deferred.defer(_finishup_mobile_registration, mobile, invitor_code, invitor_secret, ipaddress, ms_key,
                       _transactional=True, _queue=FAST_QUEUE)

        return mobile, my_profile

    mobile, my_profile = run_in_transaction(trans, xg=True)
    channel.send_message(mobile.user, u'com.mobicage.registration.finished')

    registration = get_registration_by_mobile(mobile)
    if registration and registration.installation:
        save_successful_registration(registration, mobile, my_profile)

        if registration.installation.service_identity_user and (registration.installation.qr_url or registration.installation.oauth_state):
            service_identity_user = registration.installation.service_identity_user
            service_user, service_identity = get_service_identity_tuple(service_identity_user)
            svc_profile = get_service_profile(service_user)
            user_details = [UserDetailsTO.fromUserProfile(my_profile)]
            user_app_id = get_app_id_from_app_user(mobile.user)

            # auto_connected_services
            services_to_connect = set()
            if registration.installation.service_callback_result == ACCEPT_AND_CONNECT_ID:
                def trans_update_app_id():
                    si = get_service_identity(service_identity_user)
                    bizz_check(si, "ServiceIdentity %s not found" % service_identity_user)
                    if user_app_id not in si.appIds:
                        si.appIds.append(user_app_id)
                        put_and_invalidate_cache(si)
                run_in_transaction(trans_update_app_id)
                services_to_connect.add(service_identity_user)

            for autoconnect_service_email in registration.installation.auto_connected_services:
                if "/" in autoconnect_service_email:
                    autoconnect_service_identity_user = users.User(autoconnect_service_email)
                else:
                    autoconnect_service_identity_user = create_service_identity_user(
                        users.User(autoconnect_service_email))

                if autoconnect_service_identity_user in services_to_connect:
                    continue
                si = get_service_identity(autoconnect_service_identity_user)
                if si and user_app_id in si.appIds:
                    services_to_connect.add(autoconnect_service_identity_user)

            for service_to_connect in services_to_connect:
                try_or_defer(makeFriends, mobile.user, service_to_connect, original_invitee=None, servicetag=None,
                             origin=None, notify_invitee=False, notify_invitor=False, user_data=None)

            # roles
            if registration.installation.roles:
                roles_to_add = defaultdict(set)
                for r in parse_complex_value(RegistrationResultRolesTO, json.loads(registration.installation.roles), True):
                    for role_id in r.ids:
                        roles_to_add[create_service_identity_user(
                            users.User(r.service), r.identity or ServiceIdentity.DEFAULT)].add(role_id)

                for service_identity_email, role_ids in roles_to_add.iteritems():
                    service_user, identity = get_service_identity_tuple(users.User(service_identity_email))
                    grant_service_roles(service_user, identity, mobile.user, list(role_ids))

            # callback
            if registration.installation.qr_url:
                service_api_friends.register_result(register_result_response_receiver, logServiceError, svc_profile,
                                                    service_identity=service_identity,
                                                    user_details=user_details,
                                                    origin=REGISTRATION_ORIGIN_QR)
            elif registration.installation.oauth_state:
                service_api_friends.register_result(register_result_response_receiver, logServiceError, svc_profile,
                                                    service_identity=service_identity,
                                                    user_details=user_details,
                                                    origin=REGISTRATION_ORIGIN_OAUTH)

        else:
            app = get_app_by_id(get_app_id_from_app_user(mobile.user))
            if app.admin_services:
                service_profiles = filter(None, db.get((get_profile_key(users.User(e)) for e in app.admin_services)))
                if service_profiles:
                    user_details = [UserDetailsTO.fromUserProfile(my_profile)]
                    for service_profile in service_profiles:
                        service_api_friends.register_result(register_result_response_receiver,
                                                            logServiceError,
                                                            service_profile,
                                                            service_identity=ServiceIdentity.DEFAULT,
                                                            user_details=user_details,
                                                            origin=REGISTRATION_ORIGIN_DEFAULT)

    if anonymous_account:
        deferred.defer(migrate_anonymous_account, anonymous_account, mobile.user)

    return mobile
예제 #35
0
    def post(self):
        if not self.set_user():
            self.abort(401)
            return

        connect_rpc = None
        try:
            authorization_code = self.request.POST['authorization_code']
            state = self.request.POST['state']
            scopes = self.request.POST['scope'].split(' ')
            logging.debug('POST params: %s', dict(self.request.POST))

            app_user = users.get_current_user()
            app_id = users.get_current_app_id()
            app = get_app_by_id(app_id)
            azzert(app and app.supports_mdp)

            mdp_state = MyDigiPassState.get(MyDigiPassState.create_key(app_user))
            azzert(mdp_state.state == state)
            db.delete_async(mdp_state)

            mdp_result, connect_rpc = self.authorize_mdp(app_user, app, authorization_code, scopes)
            # mdp_result: dict with following keys: uuid, access_token, scope
            mdp_profile_pointer = MyDigiPassProfilePointer.create(app_user, mdp_result['uuid'])
            mdp_profile_pointer.put()

            endpoints = { self.SCOPE_TO_ENDPOINT_MAPPING[s] for s in scopes }
            rpcs = {endpoint: self.get_mdp_data_async(mdp_result['access_token'], endpoint)
                    for endpoint in endpoints}

            result = MyDigiPassWidgetResultTO(initialize=True)
            for endpoint, rpc in rpcs.iteritems():
                response = rpc.get_result()
                if response.status_code != 200:
                    if endpoint in (MdpEndpoint.EID_DATA, MdpEndpoint.EID_PHOTO):
                        try:
                            error_dict = json.loads(response.content)
                        except:
                            pass
                        else:
                            if error_dict.get('error') == 'insufficient_permissions':
                                raise BusinessException(localize(self.language(), u'mdp_missing_eid_data'))

                    raise Exception('Failed to get %s data for MDP user %s: %s' % (endpoint, app_user.email(), response.content))

                if endpoint == MdpEndpoint.EID_PHOTO:
                    logging.debug('Got MDP %s for %s', endpoint, app_user.email())
                    photo = response.content
                    if not photo:
                        raise BusinessException(localize(self.language(), u'mdp_missing_eid_data'))
                    result.eid_photo = base64.b64encode(photo).decode('utf-8')

                elif endpoint == MdpEndpoint.EID_DATA:
                    response_dict = json.loads(response.content)
                    logging.debug('Got MDP %s for %s:\n%s', endpoint, app_user.email(), response_dict)
                    if not response_dict:
                        raise BusinessException(localize(self.language(), u'mdp_missing_eid_data'))

                    if MdpScope.EID_PROFILE in scopes:
                        result.eid_profile = parse_complex_value(MyDigiPassEidProfile, response_dict, False)
                    if MdpScope.EID_ADDRESS in scopes:
                        result.eid_address = parse_complex_value(MyDigiPassEidAddress, response_dict, False)

                elif endpoint == MdpEndpoint.USER_DATA:
                    response_dict = json.loads(response.content)
                    logging.debug('Got MDP %s for %s:\n%s', endpoint, app_user.email(), response_dict)

                    if MdpScope.EMAIL in scopes:
                        result.email = response_dict['email']
                        if not result.email:
                            raise BusinessException(localize(self.language(), u'mdp_missing_email'))

                    if MdpScope.PHONE in scopes:
                        result.phone = response_dict['phone_number']
                        if not result.phone:
                            raise BusinessException(localize(self.language(), u'mdp_missing_phone'))

                    if MdpScope.ADDRESS in scopes:
                        result.address = parse_complex_value(MyDigiPassAddress, response_dict, False)
                        if not all((result.address.address_1, result.address.zip, result.address.country)):
                            raise BusinessException(localize(self.language(), u'mdp_missing_address'))

                    if MdpScope.PROFILE in scopes:
                        result.profile = parse_complex_value(MyDigiPassProfile, response_dict, False)
                        if not all((result.profile.first_name, result.profile.last_name)):
                            raise BusinessException(localize(self.language(), u'mdp_missing_profile'))

                else:
                    azzert(False, 'Unexpected endpoint: %s' % endpoint)

            result_dict = serialize_complex_value(result, MyDigiPassWidgetResultTO, False, skip_missing=True)
        except BusinessException, e:
            result_dict = dict(error=e.message,
                               mdp_update_required=isinstance(e, MissingScopesException))
예제 #36
0
 def from_model(cls, model, reference_model=None):
     # type: (NdbModel, NdbModel) -> AuditLogDetailsTO
     props = model.to_dict()
     props['reference'] = reference_model.to_dict(
     ) if reference_model else None
     return parse_complex_value(cls, props, False)
예제 #37
0
    def post(self):
        success = False
        app_id = self.request.POST.get("app_id", None)
        name = self.request.POST.get("name", None)
        app_type = self.request.POST.get("app_type", None)
        fb_app_id = self.request.POST.get("fb_app_id", None)
        ios_app_id = self.request.POST.get("ios_app_id", None)
        android_app_id = self.request.POST.get("android_app_id", None)
        dashboard_email_address = self.request.POST.get('dashboard_email_address', None)
        contact_email_address = self.request.POST.get("contact_email_address", None)
        user_regex = self.request.POST.get("user_regex", None)
        qr_templates_count = int(self.request.POST.get("qr_templates_count", 0))
        default_qr_template_index = int(self.request.POST.get("default_qr_template_index", 0))
        auto_connected_services_string = self.request.POST.get("auto_connected_services", "[]")
        logging.debug("auto_connected_services = %s", auto_connected_services_string)
        beacon_major_str = self.request.POST.get("beacon_major", 0)
        beacon_major = int(beacon_major_str) if beacon_major_str else 0
        demo = bool(self.request.POST.get("demo", ''))
        beta = bool(self.request.POST.get("beta", ''))
        mdp_client_id = self.request.POST.get('mdp_client_id', None)
        mdp_client_secret = self.request.POST.get('mdp_client_secret', None)
        orderable_apps = self.request.get_all('orderable_apps')
        auto_connected_services = parse_complex_value(AutoConnectedService,
                                                      json.loads(auto_connected_services_string),
                                                      True)
        admin_services = json.loads(self.request.POST.get('admin_services', '[]'))
        beacon_regions = json.loads(self.request.POST.get("beacon_regions", "[]"))

        try:
            app_type = None if not app_type else int(app_type)
        except Exception:
            app_type = None

        try:
            fb_app_id = None if not fb_app_id else int(fb_app_id)
        except Exception:
            fb_app_id = None

        if not app_id:
            result = "Failed to create new app (app_id was empty)!"
        elif [c for c in app_id if c not in '-abcdefghijklmnopqrstuvwxyz0123456789']:
            result = "App ids should only contain (-, lower case alphabet characters and numbers)"
        elif not name:
            result = "Failed to create new app (name was empty)!"
        elif app_type is None:
            result = "Failed to create new app (app_type was empty)!"
        elif not ios_app_id:
            result = "Failed to create new app (ios_app_id was empty)!"
        elif not android_app_id:
            result = "Failed to create new app (android_app_id was empty)!"
        elif not dashboard_email_address:
            result = "Failed to create new app (dashboard_email_address was empty)!"
        else:
            try:
                if user_regex:
                    validate_user_regex(user_regex)

                zip_stream = self.request.POST.get('core_branding').file
                zip_stream.seek(0)
                try:
                    zip_ = ZipFile(zip_stream)
                except BadZipfile, e:
                    raise BrandingValidationException(e.message)

                branding = store_branding_zip(None, zip_, u"Core branding of %s" % app_id)

                app = App(key=App.create_key(app_id))
                to_be_put = []
                app.qrtemplate_keys = []
                for i in xrange(qr_templates_count):
                    file_ = self.request.POST.get('qr_template_%s' % i)
                    description = self.request.POST.get("qr_template_description_%s" % i)
                    color = self.request.POST.get("qr_template_color_%s" % i)
                    file_ = file_.file.getvalue() if isinstance(file_, FieldStorage) else None
                    key_name = create_qr_template_key_name(app_id, description)
                    store_template(None, file_, description, color, key_name)
                    if default_qr_template_index == i:
                        app.qrtemplate_keys.insert(0, key_name)
                    else:
                        app.qrtemplate_keys.append(key_name)

                app.name = name
                app.type = app_type
                app.core_branding_hash = branding.hash
                app.facebook_app_id = fb_app_id
                app.ios_app_id = ios_app_id
                app.android_app_id = android_app_id
                app.dashboard_email_address = dashboard_email_address
                app.contact_email_address = contact_email_address
                app.user_regex = user_regex
                app.creation_time = now()
                app.is_default = get_default_app_key() is None
                app.demo = demo
                app.beta = beta
                app.mdp_client_id = mdp_client_id or None
                app.mdp_client_secret = mdp_client_secret or None

                app.auto_connected_services = AutoConnectedServices()
                for acs in auto_connected_services:
                    service_identity_user = add_slash_default(users.User(acs.service_identity_email))
                    si = get_service_identity(service_identity_user)
                    bizz_check(si, "ServiceIdentity %s not found" % service_identity_user)
                    if app_id not in si.appIds:
                        si.appIds.append(app_id)
                        to_be_put.append(si)

                    acs.service_identity_email = service_identity_user.email()
                    app.auto_connected_services.add(acs)

                admin_profiles = db.get([get_profile_key(u) for u in map(users.User, admin_services)])
                non_existing = list()
                for admin_email, admin_profile in zip(admin_services, admin_profiles):
                    if not admin_profile:
                        non_existing.append(admin_email)
                bizz_check(not non_existing, "Non existing services specified: %s" % non_existing)
                app.admin_services = admin_services
                app.beacon_major = beacon_major
                app.beacon_last_minor = 0
                put_and_invalidate_cache(*to_be_put)

                to_be_put = []
                for beacon_region in beacon_regions:
                    uuid = beacon_region.get("uuid")
                    major = beacon_region.get("major")
                    minor = beacon_region.get("minor")
                    br = BeaconRegion(key=BeaconRegion.create_key(app.key(), uuid, major, minor))
                    br.uuid = uuid.lower()
                    br.major = major
                    br.minor = minor
                    br.creation_time = now()
                    to_be_put.append(br)

                app.orderable_app_ids = list(orderable_apps)
                apps = db.get(map(App.create_key, app.orderable_app_ids))
                for a in apps:
                    a.orderable_app_ids.append(app_id)
                    to_be_put.append(a)
                to_be_put.append(app)
                put_and_invalidate_cache(*to_be_put)

                for acs in app.auto_connected_services:
                    logging.info("There is a new auto-connected service: %s", acs.service_identity_email)
                    run_job(get_user_profile_keys_by_app_id, [app_id],
                            hookup_with_default_services.run_for_auto_connected_service, [acs, None])

                result = "Created new app!"
                success = True
            except BusinessException, e:
                logging.info("BusinessException: %s", e, exc_info=1)
                result = e.message
예제 #38
0
def messaging_flow_member_result(sik, id_, steps, user_details, tag, **kwargs):
    if tag == SUSPECT_TAG:
        try_or_defer(add_new_prospect_from_discovery, parse_complex_value(UserDetailsTO, user_details, True)[0], steps)
    return None
예제 #39
0
 def urls(self):
     from solutions.common.to import UrlTO
     return parse_complex_value(UrlTO, json.loads(self.json_urls), True)
 def _put_identity_json(self, json_dict):
     to = parse_complex_value(ServiceIdentityDetailsTO, json_dict, False)
     return put_identity(to)