def _parse_filters(): request_data = _get_request_data() params = Parameters( Param('accounts', (basestring, type(None), list), Param.UNCHECKED, None), Param('names', (basestring, type(None), list), Param.UNCHECKED, None), Param('status', (basestring, type(None), list), Param.UNCHECKED, None), Param('from', (basestring, long, float, type(None)), Param.UNCHECKED, None), Param('to', (basestring, long, float, type(None)), Param.UNCHECKED, None), Param('limit', (basestring, int, type(None)), Param.UNCHECKED, 20), Param('offset', (basestring, int, type(None)), Param.UNCHECKED, 0), ) params.update(request_data) params.check() def postprocess_params(data): filters = {} if data['accounts']: filters['account__in'] = to_list( data['accounts'], lambda x: Account.objects.get(x).id) if data['names']: filters['name__in'] = to_list(data['names']) if data['status']: filters['status__in'] = to_list(data['status']) if data['from']: filters['created_at__gte'] = parse_datetime(data['from']) if data['to']: filters['created_at__lte'] = parse_datetime(data['to']) return filters, get_paging_params(data) return postprocess_params(params.as_dict())
def import_gallery(user): data = _get_request_data() try: dashboard_type = DashboardType.objects.get(type=data['type']) gallery = Gallery.objects.get(dashboard_type=dashboard_type.id) except Exception, err: return jsonify(ok=False, error=str(err))
def clear_matches(user): data = _get_request_data() channel_id = data['channel_id'] if get_var('ON_TEST'): reset_channel_data.sync(channel_id) else: reset_channel_data.ignore(channel_id) return jsonify(ok=True, message="Task for channel reset was started.")
def search_match(user): data = _get_request_data() BenchmarkQuestion.objects.create(received_data=data) # For internal book-keeping post_content = data['post_content'] channel_id = data['channel_id'] post = factory_by_user(user, content=post_content, channel=channel_id) return jsonify(ok=True, items=sorted([{'creative': _d['creative'], 'relevance': _d['relevance'], 'id': _d['id']} for _d in post._get_matchable_dicts()[0]], key=lambda x: -x['relevance']))
def _get_items(id_=None): request_data = _get_request_data() ids = request_data.get('ids', request_data.get('id')) if ids is None: ids = [] if not isinstance(ids, list): ids = [ids] if id_: ids.append(id_) return JobModel.objects.find(id__in=ids)
def get_parameters(self): data = _get_request_data() params = {} for key, value in data.iteritems(): if key in self.valid_parameters: if key == 'dashboard_id': key = 'dashboard' value = Dashboard.objects.get_by_user(self.user, id=value) params[key] = value return params
def get_adapted_form(doc, form=None): """ Return dict with data come from request and adpated to using inside .objects.create() """ if form is None: form = _get_request_data() result = {} for key, value in form.items(): if key in ('token', 'fields'): continue field = getattr(doc, str(key), None) if isinstance(value, basestring) and isinstance(field, fields.ListField) and ',' in value: value = value.split(',') result[str(key)] = value return result
def wrapper(*args, **kwargs): #LOGGER.debug("API Request Args: {} | Params: {}".format(args, kwargs)) assert args assert isinstance(args[0], BaseAPIView) view = args[0] # Method decorator try: args = args[1:] except IndexError: args = () params = _get_request_data() params.update(kwargs) # Pass URL variables to the view function start_execution = datetime.utcnow() # Execute API method try: # Assert authentication LOGGER.debug("Started executing API call: %s.%s(%s, %s) " % ( view.__class__.__name__, func.__name__, args, kwargs)) if allow_basic_auth is True: user = _get_user() if user is None: user = authenticate_api_user(params) if user is None: raise api_exc.AuthorizationError("User is not authenticated. Parameters for call: " + str(params)) else: user = authenticate_api_user(params) # Set user in thread local storage set_user(user) resp = func(view, user, *args, **params) elapsed = datetime.utcnow() - start_execution if elapsed.total_seconds() >= 2: log = LOGGER.info else: log = LOGGER.debug log("API call: %s.%s(%s,%s) finished after %s Parameters: %s" % (view.__class__.__name__, func.__name__, str(args)[:500], str(kwargs)[:500], elapsed, str(params)[:500])) # auth token expiration and other auth errors except api_exc.AuthorizationError, exc: LOGGER.info(exc) return view.format_api_error_response(exc, msg=str(exc), description=exc.description)
def get_parameters(self): data = _get_request_data() params = {} for key, value in data.iteritems(): if hasattr(Gallery, key) and key in self.valid_parameters: field = getattr(Gallery, key) if isinstance(field, fields.ObjectIdField): value = fields.ObjectId(value) elif isinstance(field, fields.ListField) and isinstance( field.field, fields.ObjectIdField): value = map(fields.ObjectId, value) params[key] = value return params
def customer_journeys(user): data = _get_request_data() customer_id = data['customer_id'] from_ = data['from'] to_ = data['to'] from_dt, to_dt = parse_date_interval(from_, to_) F = CustomerJourney.F CustomerProfile = user.account.get_customer_profile_class() try: profile = CustomerProfile.objects.get(customer_id) except CustomerProfile.DoesNotExist: profile_schema = user.account.customer_profile._get() profile = profile_schema.get_data_class().objects.get(customer_id) journeys = CustomerJourney.objects.coll.find( { F.customer_id: profile.id, #F.start_date: {'$gte': from_dt, '$lte': to_dt} }, { F.id: 1, F.journey_type_id: 1, F.first_event_date: 1, F.last_event_date: 1 }) journeys_info = [] for j in journeys: journeys_info.append({ 'id': str(j[F.id]), 'journey_type': JourneyType.objects.get(j[F.journey_type_id]).display_name, 'start_date': j[F.first_event_date].isoformat(), 'end_date': j[F.last_event_date].isoformat(), 'typeId': str(j[F.journey_type_id]) }) return jsonify(ok=True, journeys=journeys_info)
def get_parameters(self): data = _get_request_data() params = { 'owner': self.user, # for storing } for key, value in data.iteritems(): if hasattr(Dashboard, key) and key in self.valid_parameters: field = getattr(Dashboard, key) if isinstance(field, fields.ObjectIdField): value = fields.ObjectId(value) elif isinstance(field, fields.ListField) and isinstance( field.field, fields.ObjectIdField): value = map(fields.ObjectId, value) params[key] = value return params
def get_parameters(self): data = _get_request_data() params = {} # since funnels are account specific and not user specific if request.method == 'POST': params['owner'] = self.user for key, value in data.iteritems(): if hasattr(Funnel, key) and key in self.valid_parameters: field = getattr(Funnel, key) if isinstance(field, fields.ObjectIdField): value = fields.ObjectId(value) elif isinstance(field, fields.ListField) and isinstance( field.field, fields.ObjectIdField): value = map(fields.ObjectId, value) params[key] = value return params
def process_journey_tags(user, journey_id): data = _get_request_data() try: journey = CustomerJourney.objects.get(journey_id) except CustomerJourney.DoesNotExist: return jsonify(ok=True, error="No journey with id=%s was found" % journey_id) if request.method == 'POST': journey.handle_add_tag(data.get('tag_id')) return jsonify(ok=True) elif request.method == 'DELETE': journey.handle_remove_tag(data.get('tag_id')) return jsonify(ok=True) elif request.method == 'GET': return jsonify( ok=True, list=[ tag.to_dict() for tag in SmartTagChannel.objects(id__in=journey.smart_tags) ]) return jsonify(ok=False, error="Unsupported method " + str(request.method))
def _get_user(): from ..db.api_auth import AuthToken from ..db.user import User, AuthError user = None # If this accepts token based auth, try for that first data = _get_request_data() if 'token' in data: try: token = data.get('token') user = AuthToken.objects.get_user(token) except User.DoesNotExist: pass # Still default to user based auth if not user: try: user = User.objects.get_current() except AuthError: pass return user
def get_parameters(self): data = _get_request_data() params = {} account = parse_account(self.user, data) if account: params['account_id'] = account.id for param_name, param_value in data.iteritems(): if hasattr(self.model, param_name) and param_name in self.valid_parameters: field = getattr(self.model, param_name) if isinstance(field, fields.ObjectIdField): param_value = fields.ObjectId(param_value) elif isinstance(field, fields.ListField) and isinstance( field.field, fields.ObjectIdField): param_value = map(fields.ObjectId, param_value) params[param_name] = param_value if request.method == 'GET': params.update(get_paging_params(data)) return params
def get_all_languages(user): request_data = _get_request_data() language_set = request_data.get('languageSet', 'all') force_fetch = request_data.get('forceFetch', False) if language_set == 'twitter': twitter_langs_key = '/languages/all/json?languageSet=twitter' from solariat_bottle.utils.cache import MongoDBCache cache = MongoDBCache() langs = cache.get(twitter_langs_key) if langs is None or force_fetch: langs = get_twitter_supported_languages() langs = sorted(map( lang_to_ui, set([get_lang_code(lang['code']) for lang in langs])), key=operator.itemgetter('title')) one_week = 60 * 60 * 24 * 7 cache.set(twitter_langs_key, langs, timeout=one_week) return jsonify(ok=True, list=langs) else: # list all currently supported langs languages = get_all_detected_langs() return jsonify(ok=True, list=languages)
def post(self, *args, **kwargs): """ Create a user token entity. Returns a token object in case authentication is successful Sample request: curl http://staging.socialoptimizr.com/api/v2.0/authenticate POST Parameters: :param api_key: <Required> - A valid api key :param username: <Required> - The username of the GSA user :param password: <Required> - The password of the GSA user Output: A dictionary in the form {'ok': true, 'token': <auth token>} Sample valid response { "token": "dc879e52b70b16c3935b8db99f666fdf8eebaa05", "ok": true } Missing app_key parameter: { "code": 13, "error": "An extra parameter 'api_key' is required for users in order to get a user token." } Wrong user email { "code": 13, "error": "User with given email or username does not exist" } Wrong user password { "code": 13, "error": "Provided password wrong is not a match for user [email protected]" } """ required_post_params = ['username', 'password'] params = _get_request_data() for req_param in required_post_params: if req_param not in params: exc = InvalidParameterConfiguration return self.format_api_error_response(exc, msg="Required parameter missing: {}".format(req_param)) try: if get_var('ENFORCE_API_HTTPS') and not request.url.startswith('https://'): # Unsercure request, invalidate token # This is not recoverable by user alone, so remove for now until we have a better way # where we offer user possibility to recover by some other means # try: # user = User.objects.get(email=params['username']) # user.set_password(os.urandom(10).encode('base64')[:-3]) # user.save() # except User.DoesNotExist: # raise AuthorizationError("No user with email=%s found in the system." % params['username']) # if not user.is_superuser: # app_key = ApplicationToken.objects.verify_application_key(params['api_key']) # app_key.invalidate() description = "You have made an unsecured request over HTTP. Please use HTTPS for any subsequent calls." description += " Your current api token has automatically been invalidated and your password reset. " description += "Please contact GSA administrator to get fresh credentials." raise AuthorizationError(msg="Unsecure request done over HTTP. Your credentials have been invalidated.", description=description) token = self.model.objects.create(**params) except AppException, exc: return self.format_api_error_response(exc, msg=str(exc), description=exc.description)
def _wrapper(*args, **kw): data = _get_request_data() data.update(kw) return view_func(*args, **data)
def get_parameters(self): data = _get_request_data() return data
def journey_stage_events(user, journey_id, stage_id): def _get_platform(event): platform = event._t[0] if platform.endswith('Post') and platform != 'Post': platform = platform[:-len('Post')] return platform data = _get_request_data() current_page = data.get('page', 0) current_page_size = data.get('page_size', DEFAULT_PAGE_SIZE) journey = CustomerJourney.objects.get(journey_id) CustomerProfile = user.account.get_customer_profile_class() customer = CustomerProfile.objects.get(journey.customer_id) if stage_id in journey.stage_information: end_date = journey.stage_information[stage_id]['end_date'] start_date = journey.stage_information[stage_id]['start_date'] else: end_date = datetime.datetime.utcnow() start_date = journey.first_event_date events = list( Event.objects.range_query(start_date, end_date, customer, skip=current_page * current_page_size, limit=current_page_size)) if len(events) < current_page_size: # Reached the end next_page = -1 else: next_page = current_page + 1 events_info = [] grouper = itertools.groupby(events, _get_platform) for platform, platform_events in grouper: _events = list(platform_events) agents = [] channels = [] content = [] for event in _events: if event.is_inbound is False: agents.append(event.actor) channels.extend([ chan.title for chan in Channel.objects(id__in=event.channels) ]) filters = {} if isinstance(event, ChatPost): filters['include_summary'] = False base_dict = event.to_dict(**filters) base_dict['computed_tags'] = event.json_computed_tags base_dict['journey_tags'] = event.journey_tags base_dict.pop('_computed_tags') base_dict.pop('actor', None) base_dict.pop('_reply_context', None) content.append(base_dict) events_info.append( dict(stageId=str(stage_id), platform=platform, messagesCount=len(_events), agents=[a.agent_full_name for a in set(agents)], channels=list(set(channels)), content=content)) return jsonify_response(ok=True, item=dict(nextPage=next_page, pageSize=current_page_size, events=events_info))