Esempio n. 1
0
 def _get_response(self, **kwargs):
     if current_user.is_anonymous():
         cuid = session.get('customer_id')
     else:
         cuid = current_user.customer.id
     response = {
         'id': session['id'],
         'is_anonymous': current_user.is_anonymous(),
         'uid': session.get('user_id'),
         'cuid': cuid,
         'locale': g.locale
     }
     response.update(kwargs)
     return response
Esempio n. 2
0
 def _get_response(self, **kwargs):
     if current_user.is_anonymous():
         cuid = session.get('customer_id')
     else:
         cuid = current_user.customer.id
     response = {
         'id': session['id'],
         'is_anonymous': current_user.is_anonymous(),
         'uid': session.get('user_id'),
         'cuid': cuid,
         'locale': g.locale
     }
     response.update(kwargs)
     return response
Esempio n. 3
0
 def before_index(self, page=1):
     """ Used to mark a visit of index page and remove welcome screen
         TODO: Optimize by running this only when necessary (is that possible?)
     """
     if current_user.is_anonymous() and not session.get(
             'visited_index', False):
         session['visited_index'] = True
Esempio n. 4
0
def before_request():
    if current_user.is_authenticated():
        current_user.ping()
    if not current_user.is_anonymous():
        g.user = current_user
    else:
        g.user = None
Esempio n. 5
0
    def post(self):
        status = http.CREATED
        data = request.json or abort(http.BAD_REQUEST)
        validation = self.validation.make_optional('concrete_product_id')

        # condition to ensure that we have a customer when item added to cart
        if current_user.is_anonymous():
            if session.get('customer_id'):
                customer = Customer.query.get_or_404(session['customer_id'])
            else:
                customer = Customer.create()
        else:
            customer = current_user.customer
        session['customer_id'] = customer.id
        data['customer_id'] = customer.id
        try:
            data = validation.check(data)
            product = mongo.db.products.find_one({'_id': data['product_id']})
            if product is None:
                raise t.DataError({'product_id': _('Product not fount')})

            cart = product.add_to_cart(customer=customer,
                                       amount=data['amount'],
                                       price_option_id=data['price_option_id'],
                                       service=data.get('service'))

            response = cart.as_dict()
        except t.DataError as e:
            status, response = http.BAD_REQUEST, e.as_dict()

        return jsonify_status_code(response, status)
Esempio n. 6
0
def perosnal():
    if current_user.is_anonymous():
        return []
    else:
        ms = db.session.query(Movie).filter(
            Movie.user_id == current_user.id).all()
        return json.dumps([o.to_json for o in ms])
Esempio n. 7
0
    def get_objects(self, **kwargs):
        """ Method for extraction object list query
        """
        if current_user.is_anonymous() or not current_user.is_superuser():
            kwargs['customer_id'] = self._customer.id

        return super(AddressResource, self).get_objects(**kwargs)
Esempio n. 8
0
    def get_objects(self, **kwargs):
        """ Method for extraction object list query
        """
        if current_user.is_anonymous() or not current_user.is_superuser():
            kwargs['customer_id'] = self._customer.id

        return super(AddressResource, self).get_objects(**kwargs)
Esempio n. 9
0
def before_request():
    if current_user.is_authenticated():
        current_user.ping()
    if not current_user.is_anonymous():
        g.user = current_user
    else:
        g.user = None
Esempio n. 10
0
 def _get_response(self, **kwargs):
     response = {
         'id': session['id'],
         'is_anonymous': current_user.is_anonymous(),
         'uid': session.get('user_id')
     }
     response.update(kwargs)
     return response
Esempio n. 11
0
def flatpage(slug):
    page = FlatPage.objects.get_or_404(slug=slug)
    if page.login_required and current_user.is_anonymous():
        return render_template('404.html'), http.NOT_FOUND

    template = page.template or 'flatpage.html'

    return render_template(template, page=page)
Esempio n. 12
0
    def serialize(self, instance, include=None):
        exclude = ['email']

        if not (current_user.is_anonymous() or instance.is_anonymous()):
            if current_user.id == instance.id or current_user.is_superuser():
                exclude = []

        return instance.as_dict(include, exclude)
Esempio n. 13
0
    def serialize(self, instance, include=None):
        exclude = ['email']

        if not (current_user.is_anonymous() or instance.is_anonymous()):
            if current_user.id == instance.id or current_user.is_superuser():
                exclude = []

        return instance.as_dict(include, exclude)
Esempio n. 14
0
    def before_request():
        """ Get our footer pages. 
            TODO: This should be done once in before_first but that wasn't working

            We check if user is anonymous and first time visitor to show a "welcome" message
        """
        g.pages = get_pages()
        if current_user.is_anonymous() and session.get('visited_index', False):
            session['return_anon'] = True
Esempio n. 15
0
    def serialize(self, instance, include=None):
        exclude = []
        if current_user.is_anonymous() or instance.is_anonymous():
            return instance.as_dict(include)

        if current_user.id != instance.id or not current_user.is_superuser():
            exclude.append('email')

        return instance.as_dict(include, exclude)
Esempio n. 16
0
def zupc():
    if request.method == "GET":
        if request_wants_json():
            return zupc_search()
        roles_accepted = set(['admin', 'mairie', 'prefecture', 'operateur'])
        if not current_user.is_anonymous() and\
                len(roles_accepted.intersection(current_user.roles)) > 0:
            return zupc_list()
    abort(405, message="method now allowed")
Esempio n. 17
0
def user():
    """ Info on the currently logged in user. """
    if current_user.is_anonymous():
        raise ApiException(401, "not authenticated")

    user = serializers.to_dict(current_user)
    user['authentication_token'] = current_user.get_auth_token()

    return send_api_response({'current_user': user})
Esempio n. 18
0
    def get(self):
        if current_user.is_anonymous():
            return success(dict(is_anonymous=True))

        return success({
            "avatar_url": current_user.get_avatar_url(),
            "name": current_user.fullname,
            "is_anonymous": False
        })
Esempio n. 19
0
def user():
    """ Info on the currently logged in user. """
    if current_user.is_anonymous():
        raise ApiException(401, "not authenticated")

    user = serializers.to_dict(current_user)
    user['authentication_token'] = current_user.get_auth_token()

    return send_api_response({'current_user': user})
Esempio n. 20
0
    def _customer(self):
        if current_user.is_anonymous():
            customer_id = session.get('customer_id')
            if customer_id is None:
                abort(http.BAD_REQUEST)
            customer = Customer.query.get_or_404(customer_id)
        else:
            customer = current_user.customer

        return customer
Esempio n. 21
0
    def _customer(self):
        if current_user.is_anonymous():
            customer_id = session.get('customer_id')
            if customer_id is None:
                abort(http.FORBIDDEN)
            customer = Customer.query.get_or_404(customer_id)
        else:
            customer = current_user.customer

        return customer
Esempio n. 22
0
    def get_objects(self, **kwargs):
        """ Method for extraction object list query
        """
        if current_user.is_anonymous():
            kwargs['customer_id'] = session['customer_id']
        elif not current_user.is_superuser():
            kwargs['customer_id'] = current_user.customer.id
        # TODO: process product owners

        self.model is None and abort(http.BAD_REQUEST)
        return self.model.query.filter_by(**kwargs)
Esempio n. 23
0
 def get_objects(self, **kwargs):
     """ Method for extraction object list query
     """
     query = super(ImageResource, self).get_objects(**kwargs)
     if current_user.is_anonymous():
         return query.filter_by(is_public=True)
     elif current_user.is_superuser:
         return query
     else:
         return query.filter(or_(self.model.author_id == current_user.id,
                                    self.model.is_public is True))
Esempio n. 24
0
def zupc():
    if request.method != "GET":
        abort(405, message="method now allowed")
    if request_wants_json():
        abort(400, message="bad format")
    roles_accepted = set(['admin', 'mairie', 'prefecture', 'operateur'])
    if  current_user.is_anonymous() or\
            len(roles_accepted.intersection(current_user.roles)) == 0:
        abort(403)
    page = int(request.args.get('page')) if 'page' in request.args else 1
    return render_template('lists/zupc.html',
        zupc_list=administrative_models.ZUPC.query.paginate(page))
    def get(self, **kwargs):
        metric = request.args.get('metric')
        if current_user.is_anonymous():
            error = dumps({'error':'The user is not logged in.'})
            resp = Response(response=error,status=400,mimetype="application/json")
            return resp

        twitter = TwitterDAO()
        if not twitter.user_twitter:
            error = dumps({'error':'No Twitter account is associated with this user.'})
            resp = Response(response=error,status=400,mimetype="application/json")
            return resp
        else:
            cohorts = current_user.roles
            tracked_words = twitter.user_twitter.words
            counts = [x.as_dict() for x in tracked_words]
            date_count = {}

            for word in counts:
                counts_list = word['counts']
                for count in counts_list:
                    date = count['date']
                    count_at_date = count['count']
                    try:
                            date_count[date] = date_count[date] + count_at_date
                    except:
                            date_count[date] = count_at_date

            values = []

            for key in date_count:
                values.append([key,date_count[key]])

            if not values:
                
                values = [[time.mktime(datetime.datetime.timetuple(datetime.datetime.now())) * 100, 0]]

    	    if not cohorts:
                return make_response(dumps([{'values':values, key:"Tweets"}]))
    	    else:
        		cohort_objs = []
        		for cohort in cohorts:
        		    cohort_name = cohort.name
        		    cohort_tweet_counts = CohortTweetCountModel.query.filter_by(cohort_name=cohort_name).all()
        		    cohort_values = [x.as_count() for x in cohort_tweet_counts]
                            if not cohort_values:
                                cohort_values = [[time.mktime(datetime.datetime.timetuple(datetime.datetime.now())) * 100, 0] for i in range(len(values))]

        		    cohort_obj = {'values':cohort_values, 'key': cohort_name+'\'s average tweets'}
        		    cohort_objs.append(cohort_obj)

        		cohort_objs.append({'values':values, 'key':"Your Tweets"})
        		return make_response(dumps(cohort_objs))
Esempio n. 26
0
 def get_objects(self, **kwargs):
     """ Method for extraction object list query
     """
     query = super(ImageResource, self).get_objects(**kwargs)
     if current_user.is_anonymous():
         return query.filter_by(is_public=True)
     elif current_user.is_superuser:
         return query
     else:
         return query.filter(
             or_(self.model.author_id == current_user.id,
                 self.model.is_public is True))
Esempio n. 27
0
    def get(self, **kwargs):
        """
        TODO: get old data to render in form as default
        """
        #check= request.args.get('check')
        if current_user.is_anonymous():
            return jsonify(status=400)
        scale = Scale_DAO()
        if scale.user_scale:
            return make_response(dumps(scale.user_scale.as_dict()))

        else:
            return jsonify(scale_authed=False)
Esempio n. 28
0
def api_resource(resource_id, base_query):
    try:
        resource = base_query.filter_by(id=resource_id).one()
    except NoResultFound:
        raise ApiException(404, "Not found")

    status_code = 200
    if resource == "committee-meeting":
        if not resource.check_permission():
            if current_user.is_anonymous():
                status_code = 401  # Unauthorized, i.e. authentication is required
            else:
                status_code = 403  # Forbidden, i.e. the user is not subscribed

    return send_api_response(serializers.queryset_to_json(resource), status_code=status_code)
Esempio n. 29
0
def api_resource(resource_id, base_query):
    try:
        resource = base_query.filter_by(id=resource_id).one()
    except NoResultFound:
        raise ApiException(404, "Not found")

    status_code = 200
    if resource == "committee-meeting":
        if not resource.check_permission():
            if current_user.is_anonymous():
                status_code = 401  # Unauthorized, i.e. authentication is required
            else:
                status_code = 403  # Forbidden, i.e. the user is not subscribed

    return send_api_response(serializers.queryset_to_json(resource), status_code=status_code)
Esempio n. 30
0
def return_label():
    '''
    Retrun label
    '''

    rm = resources.model
    fill_selects()
    weather = get_weather()
    if weather:
        track = db.session.query(rm.Track).filter_by(id=weather.track).first()
        g.session = weather.session
    else:
        track = False
    if not track:
        name = u"Трек не выбран"
    else:
        name = track.name
    form = ReturnLabel()
    if current_user.is_anonymous():
        g.anonymous = 1
        user_info = None
    else:
        g.anonymous = 0
        user_info = db.session.query(rm.UserInfo).filter_by(id=current_user.user_info).first()
    if form.validate_on_submit():
        rf = request.form
        if rf.getlist('btn_user_ok'):
            login_user(form.user, remember=False)
            if current_user.is_active():
                g.anonymous = 0
                user_info = db.session.query(rm.UserInfo).filter_by(id=current_user.user_info).first()
        if rf.getlist('btn_ok'):
            label=re.sub(r'(\.)+',r'',rf.getlist('label_id')[0])
            label_id = db.session.query(rm.Label).filter_by(label_id=label).first()
            if label_id == None:
                g.label_id = 'None'
                return render_template('return_label.html', form=form, weather=weather, track=name, user_info=user_info)
            if label_id != None and label_id.user_id == 0:
                g.label_id = 0
                return render_template('return_label.html', form=form, weather=weather, track=name, user_info=user_info)
            if label_id != None and label_id.user_id > 0:
                # g.label_id = label_id.label_id
                db.session.query(rm.Label).filter_by(label_id=label).update({'user_id':0})
                db.session.commit()
                return render_template('return_label.html', form=form, weather=weather, track=name, user_info=user_info)
        if rf.getlist('btn_cancel'):
            return redirect('/admin')
    return render_template('return_label.html', form=form, weather=weather, track=name, user_info=user_info)
Esempio n. 31
0
def view(category, uuid, slug=None):
    post_id = decode_id(uuid)
    post = Post.query.get_or_404(post_id)
    categories = Category.query.all()
    user_string_id = 'ANONYMOUS'
    if current_user.is_authenticated():
        user_string_id = current_user.string_id

    # Aggressive redirect if the URL does not have a slug
    if not slug:
        return redirect(url_for('posts.view',
            category=category,
            uuid=uuid,
            slug=post.slug))
    #post.comments.sort(key=lambda comment: comment.confidence, reverse=True)

    oembed = None
    # If the content is a link, we try to pass it through micawber to do
    # some nice embedding
    if post.post_type_id == 1:
        try:
            oembed = registry.request(post.content)
            # Keep in mind that oembed can be of different types:
            # - photo
            # - video
            # - link
            # - etc
        except (ProviderNotFoundException, ProviderException):
            # If the link is not an OEmbed provider, we move on
            pass
        else:
            # For any other error (e.g. video was unpublished) we also pass
            pass

    form = CommentForm()
    if current_user.is_anonymous():
        current_user.is_owner = False
    elif current_user.is_authenticated() and post.user.id == current_user.id:
        current_user.is_owner = True
    return render_template('posts/view.html',
        title='view',
        post=post,
        oembed=oembed,
        form=form,
        categories=categories,
        user_string_id=user_string_id,
        picture=post.thumbnail('m'))
Esempio n. 32
0
    def validate(self):

        if current_user.is_anonymous():
            if self.user_phone.data.strip() == '':
                return False

            self.user = find_user(user_phone=self.user_phone.data)

            if self.user is None:
                g.user_unexists = 1
                return False

        if current_user.is_active():
            if self.label_id.data.strip() == '':
                return False

        return True
Esempio n. 33
0
 def post(self):
     """
     TODO: add update instead of just creating whole new record
     """
     if current_user.is_anonymous():
         return jsonify(msg="You are no longer logged in",status=400)
     try:
         data = request.json
         cb_url = data.get('crunchbase_url')
         al_url = data.get('angellist_url')
         description = data.get('description')
         new_data = StartupDataModel(username=current_user.email, crunchbase_url=cb_url, angellist_url=al_url, description=description)
         db.session.add(new_data)
         db.session.commit()
         return jsonify(status=200,msg="Data added successfully!")
     except:
         jsonify(msg="Error adding your data.")
 def get(self, **kwargs):
     print 'getting qb'
     args = request.args
     if current_user.is_anonymous():
         print 'anon user'
         return jsonify(qb_authed=False)
     qb = Quickbooks_DAO()
    # if qb.user_qb:
     # get sum of balance for every day
     base_query = db.session.query(
         QuickbooksDailyAccountBalance.date,
             func.sum(QuickbooksDailyAccountBalance.balance).label('total')
        # ).filter(QuickbooksDailyAccountBalance.quickbooks_user_id == current_user.id).group_by(QuickbooksDailyAccountBalance.date)
     ).filter(QuickbooksDailyAccountBalance.quickbooks_user_id == 1).group_by(QuickbooksDailyAccountBalance.date)
     balances =  [(time.mktime(datetime.datetime.timetuple(x[0]))*1000,x[1]) for x in base_query.all()]
     d3_data = [{"key":"Runway", "values":balances, "username":current_user.email}]
     return make_response(dumps(d3_data))
Esempio n. 35
0
def view(category, uuid, slug=None):
    post_id = decode_id(uuid)
    post = Post.query.get_or_404(post_id)
    post.check_permissions()
    categories = Category.query.all()
    user_string_id = 'ANONYMOUS'
    if current_user.is_authenticated():
        user_string_id = current_user.string_id

    # Aggressive redirect if the URL does not have a slug
    if not slug:
        return redirect(
            url_for('posts.view', category=category, uuid=uuid,
                    slug=post.slug))

    oembed = None
    # If the content is a link, we try to pass it through micawber to do
    # some nice embedding
    if post.post_type_id == 1:
        try:
            oembed = registry.request(post.content)
            # Keep in mind that oembed can be of different types:
            # - photo
            # - video
            # - link
            # - etc
        except (ProviderNotFoundException, ProviderException):
            # If the link is not an OEmbed provider, we move on
            pass
        else:
            # For any other error (e.g. video was unpublished) we also pass
            pass

    form = CommentForm()
    if current_user.is_anonymous():
        current_user.is_owner = False
    elif current_user.is_authenticated() and post.user.id == current_user.id:
        current_user.is_owner = True
    return render_template('posts/view.html',
                           title='view',
                           post=post,
                           oembed=oembed,
                           form=form,
                           categories=categories,
                           user_string_id=user_string_id,
                           picture=post.thumbnail('m'))
Esempio n. 36
0
def index():
    """Get notifications for the current user.

    Optional url args:
    - limit: limits the number of notifications
    - format: html or JSON
    """
    if current_user.is_anonymous():
        return jsonify(status="fail", data=dict(message="Please register to " "access notifications"))
    limit = request.args.get("limit", 20)
    user_notifications = (
        Notification.query.filter(Notification.user_id == current_user.id).order_by(Notification.id.desc()).limit(limit)
    )
    items = []
    for notification in user_notifications:
        items.append(notification_parse(notification))

    return jsonify(items=items)
Esempio n. 37
0
 def send_static_file(self, filename):
     protected_templates = [
         'partials/dashboard2.html', 'partials/onboarding/stick.html',
         'partials/onboarding/scale.html',
         'partials/onboarding/virality.html', 'partials/measurements.html',
         'partials/measurements2.html', 'partials/onboarding/wufoo.html',
         'partials/onboarding/pay.html', 'partials/scale.html',
         'partials/onboarding/welcome.html',
         'partials/dashboard/optimization.html',
         'partials/dashboard/baseline.html'
         'partials/dashboard/operations.html',
         'partials/dashboard/done.html'
     ]
     # Get user from session
     if not current_user.is_anonymous(
     ) or filename not in protected_templates:
         return super(SecuredStaticFlask, self).send_static_file(filename)
     else:
         return redirect('/static/partials/signin.html')
Esempio n. 38
0
def index():
    """Get notifications for the current user.

    Optional url args:
    - limit: limits the number of notifications
    - format: html or JSON
    """
    if current_user.is_anonymous():
        return jsonify(status='fail',
                       data=dict(message='Please register to '
                                 'access notifications'))
    limit = request.args.get('limit', 20)
    user_notifications = Notification.query\
        .filter(Notification.user_id == current_user.id)\
        .order_by(Notification.id.desc())\
        .limit(limit)
    items = []
    for notification in user_notifications:
        items.append(notification_parse(notification))

    return jsonify(items=items)
Esempio n. 39
0
    def post(self):
        status = http.CREATED
        data = request.json or abort(http.BAD_REQUEST)

        try:
            data = self.validation.check(data)
            address_type = data.pop("type")
            address = self.model.create(**data)
            if current_user.is_anonymous():
                session.get("customer_id") or abort(http.NOT_FOUND)
                customer = Customer.query.get_or_404(session["customer_id"])
            else:
                customer = current_user.customer

            customer.set_address(address_type, address)
            customer.save()

            response = self.serialize(address)
        except t.DataError as e:
            status, response = http.BAD_REQUEST, e.as_dict()

        return jsonify_status_code(response, status)
Esempio n. 40
0
def doc_index():
    if not current_user.is_anonymous():
        apikeys_operator = set()
        apikeys_moteur = set()
        if 'operateur' in current_user.roles:
            apikeys_operator.add(('your token', current_user.apikey))
        if 'moteur' in current_user.roles:
            apikeys_moteur.add(('your token', current_user.apikey))
        apikeys_operator.add(('neotaxi', user_datastore.find_user(email='neotaxi').apikey))
        apikeys_moteur.add(('neomap', user_datastore.find_user(email='neomap').apikey))
        taxis = Taxi.query.filter(Taxi.added_by==user_datastore.\
                    find_user(email='neotaxi').id).all()
    else:
        apikeys_operator = [('anonymous', 'token')]
        apikeys_moteur = [('anonymous', 'token')]
        taxis = []

    url_for = partial(base_url_for, _external=True)
    return render_template('documentation/examples.html',
                 apikeys_operator=apikeys_operator,
                 apikeys_moteur=apikeys_moteur,
                 taxis=taxis,
                 url_for=url_for)
Esempio n. 41
0
 def get(self, **kwargs):
     print 'getting qb'
     args = request.args
     if current_user.is_anonymous():
         print 'anon user'
         return jsonify(qb_authed=False)
     qb = Quickbooks_DAO()
     # if qb.user_qb:
     # get sum of balance for every day
     base_query = db.session.query(
         QuickbooksDailyAccountBalance.date,
         func.sum(QuickbooksDailyAccountBalance.balance).label('total')
         # ).filter(QuickbooksDailyAccountBalance.quickbooks_user_id == current_user.id).group_by(QuickbooksDailyAccountBalance.date)
     ).filter(
         QuickbooksDailyAccountBalance.quickbooks_user_id == 1).group_by(
             QuickbooksDailyAccountBalance.date)
     balances = [(time.mktime(datetime.datetime.timetuple(x[0])) * 1000,
                  x[1]) for x in base_query.all()]
     d3_data = [{
         "key": "Runway",
         "values": balances,
         "username": current_user.email
     }]
     return make_response(dumps(d3_data))
Esempio n. 42
0
 def get_objects(self, **kwargs):
     if current_user.is_anonymous() or not current_user.is_superuser():
         kwargs['id'] = self._customer.id
     return super(CustomerResource, self).get_objects(**kwargs)
    def get(self, **kwargs):
        metric = request.args.get('metric')
        if current_user.is_anonymous():
            error = dumps({'error': 'The user is not logged in.'})
            resp = Response(response=error,
                            status=400,
                            mimetype="application/json")
            return resp

        twitter = TwitterDAO()
        if not twitter.user_twitter:
            error = dumps(
                {'error': 'No Twitter account is associated with this user.'})
            resp = Response(response=error,
                            status=400,
                            mimetype="application/json")
            return resp
        else:
            cohorts = current_user.roles
            tracked_words = twitter.user_twitter.words
            counts = [x.as_dict() for x in tracked_words]
            date_count = {}

            for word in counts:
                counts_list = word['counts']
                for count in counts_list:
                    date = count['date']
                    count_at_date = count['count']
                    try:
                        date_count[date] = date_count[date] + count_at_date
                    except:
                        date_count[date] = count_at_date

            values = []

            for key in date_count:
                values.append([key, date_count[key]])

            if not values:

                values = [[
                    time.mktime(
                        datetime.datetime.timetuple(datetime.datetime.now())) *
                    100, 0
                ]]

            if not cohorts:
                return make_response(dumps([{
                    'values': values,
                    key: "Tweets"
                }]))
            else:
                cohort_objs = []
                for cohort in cohorts:
                    cohort_name = cohort.name
                    cohort_tweet_counts = CohortTweetCountModel.query.filter_by(
                        cohort_name=cohort_name).all()
                    cohort_values = [x.as_count() for x in cohort_tweet_counts]
                    if not cohort_values:
                        cohort_values = [[
                            time.mktime(
                                datetime.datetime.timetuple(
                                    datetime.datetime.now())) * 100, 0
                        ] for i in range(len(values))]

                    cohort_obj = {
                        'values': cohort_values,
                        'key': cohort_name + '\'s average tweets'
                    }
                    cohort_objs.append(cohort_obj)

                cohort_objs.append({'values': values, 'key': "Your Tweets"})
                return make_response(dumps(cohort_objs))
Esempio n. 44
0
def search(page=0):
    """
    Display search page
    """
    filters = {}
    filters["type"] = request.args.get('filter[type]', '')
    filters["start_date"] = request.args.get('filter[start_date]', '')
    filters["end_date"] = request.args.get('filter[end_date]', '')
    filters["committee"] = request.args.get('filter[committee]', '')

    # support legacy search URLs that allowed "None" as a value
    for k, v in filters.iteritems():
        if v == "None":
            filters[k] = None
    q = request.args.get('q', '').strip()

    params = dict(filters)
    params["q"] = q
    params["page"] = page

    # do the search
    search = {}
    try:
        if q:
            search = load_from_api('search', params=params)
    except ApiException as e:
        if e.code == 422:
            # bad search, eg: "   "
            q = ""
        else:
            raise e

    years = range(1997, datetime.now().year + 1)
    years.reverse()

    bincount = {}
    yearcount = {}
    if search:
        for bin in search["bincount"]["types"]:
            bincount[bin["key"]] = bin["doc_count"]

        for year in search["bincount"]["years"]:
            yearcount[int(year["key_as_string"][:4])] = year["doc_count"]

        search['friendly_data_type'] = Search.friendly_data_types.get(filters['type'], None)

    committees = load_from_api('committee', return_everything=True)['results']

    def search_url(**kwargs):
        args = dict(filters)
        args.update(kwargs)
        args = {('filter[%s]' % k): v for k, v in args.iteritems() if v}
        return url_for('search', q=q, **args)

    saved_search = None
    if not current_user.is_anonymous():
        saved_search = SavedSearch.find(
            current_user,
            q,
            content_type=filters['type'] or None,
            committee_id=filters['committee'] or None)

    if filters['committee']:
        for committee in committees:
            if committee['id'] == int(filters['committee']):
                search['filtered_committee_name'] = committee['name']
                break

    # suggest a phrase search?
    if q and ' ' in q and '"' not in q:
        suggest_phrase = '"%s"' % q
        kwargs = {('filter[%s]' % k): v for k, v in filters.iteritems() if v}
        kwargs['q'] = suggest_phrase
        suggest_phrase_url = url_for('search', **kwargs)
    else:
        suggest_phrase = False
        suggest_phrase_url = None

    return render_template(
        'search.html',
        q=q,
        search=search,
        num_pages=search.get("pages"),
        page=search.get("page"),
        per_page=search.get("per_page"),
        search_url=search_url,
        url=url_for('search')[:-1],
        query_string=request.query_string,
        filters=filters,
        years=years,
        bincount=bincount,
        yearcount=yearcount,
        committees=committees,
        search_types=Search.friendly_data_types.items(),
        saved_search=saved_search,
        suggest_phrase=suggest_phrase,
        suggest_phrase_url=suggest_phrase_url)
Esempio n. 45
0
 def _get_response(self, **kwargs):
     response = {"id": session["id"], "is_anonymous": current_user.is_anonymous(), "uid": session.get("user_id")}
     response.update(kwargs)
     return response
Esempio n. 46
0
 def get_objects(self, **kwargs):
     if current_user.is_anonymous():
         kwargs["id"] = session.get("customer_id") or abort(http.NOT_FOUND)
     elif not current_user.is_superuser():
         kwargs["id"] = current_user.customer.id
     return super(CustomerResource, self).get_objects(**kwargs)
Esempio n. 47
0
    def post(self):
        """
        Get wufoo data from webhook
        """
        # potential data coming in from wufoo.com
        data = request.form
        # potential data coming in from leanworkbench.com
        if request.data:
            lwb_data = loads(request.data)
            create = lwb_data.get("create")
        else:
            create = False

        # if creating/registering survey to user
        if create:
            if current_user.is_anonymous():
                return dumps([{"status": 400}])
            else:
                url = lwb_data.get("url")
                handshake = lwb_data.get("handshake")
                if not url:
                    return jsonify(emsg="No url given")
                else:
                    print 'attempting to add survey'
                    try:
                        name = url.split('/')[-2]
                        new_survey = WufooSurveyModel(
                            username=current_user.email,
                            url=url,
                            name=name,
                            handshake=handshake)
                        db.session.add(new_survey)
                        db.session.commit()
                        return make_response(
                            dumps({
                                "status": 200,
                                "msg": "Survey successfully added"
                            }))
                    except:
                        traceback.print_exc()
                        return jsonify(status=500)
        # if webhook and not the user registering the survey for the first time
        else:
            # parse json load
            entry_id = data.get("EntryId")
            form_structure = data.get("FormStructure")
            form_structure_dict = loads(form_structure)
            created_by = form_structure_dict.get('Email')
            url = form_structure_dict.get("Url")
            field_structure = data.get("FieldStructure")
            field_structure_dict = loads(field_structure)
            fields = field_structure_dict.get("Fields")
            handshake = data.get("HandshakeKey")
            # get survey
            survey = WufooSurveyModel.query.filter_by(wufoo_email=created_by,
                                                      name=url).all()
            if not survey:
                print 'survey does not exist yet'
                # if survey doesn't exist yet, pass
                return jsonify(status="This survey does not exist yet.")
            survey = survey[-1]
            survey_handshake = survey.handshake
            if handshake == "":
                handshake = None
            if survey_handshake != handshake:
                print 'handshake not equal'
                return jsonify(status="Handshake invalid")

            # get textareas
            textareas = []
            for field in fields:
                print field
                field_type = field.get("Type")
                if field_type == "textarea":
                    textareas.append(field.get("ID"))

            alchemyapi = AlchemyAPI(os.getenv("ALCHEMYAPI_KEY"))
            for key in data:
                if key in textareas:
                    text = data[key]
                    response = alchemyapi.sentiment('text', text)
                    if response['status'] == 'OK':
                        docsentiment = response.get("docSentiment")
                        score = docsentiment.get("score")
                        sent_type = docsentiment.get("type")
                        new_sentiment = WufooTextareaSentiment(
                            score=score, sentiment_type=sent_type, text=text)
                        survey.textareas.append(new_sentiment)
                        db.session.add(survey)
                        db.session.add(new_sentiment)
                        db.session.commit()

                    else:
                        print 'alchemy failed'
Esempio n. 48
0
 def get_objects(self, **kwargs):
     if current_user.is_anonymous() or not current_user.is_superuser():
         kwargs['id'] = self._customer.id
     return super(CustomerResource, self).get_objects(**kwargs)