예제 #1
0
    def test_cannot_get_or_update_another_users_logs(self):
        user = User.query.first()
        user2 = User(username="******",\
            email="*****@*****.**", password="******")

        db.session.add(user2)
        db.session.commit()

        log = Log(user=user2, event_name="testlog")
        db.session.add(log)
        db.session.commit()

        #test cannot update
        res = self.open_with_auth(url=API_PREFIX + '/log/' + str(log.id),
                                  method='PUT',
                                  username=user.username,
                                  password="******",
                                  data=json.dumps(dict(event_name="test2")))

        assert (res.status_code == 401)

        #test cannot get
        res = self.open_with_auth(url=API_PREFIX + '/logs',
                                  method='GET',
                                  username=user.username,
                                  password="******",
                                  data=None)
        resJson = json.loads(res.data.decode('utf-8'))

        assert (len(resJson['logs']) == 0)
예제 #2
0
    def test_update_log(self):
        user = User.query.first()
        log = Log(user=user, event_name="testlog")
        db.session.add(log)
        db.session.commit()

        assert (Log.query.first().event_name == "testlog")

        res = self.open_with_auth(url=API_PREFIX + '/log/' + str(log.id),
                                  method='PUT',
                                  username=user.username,
                                  password="******",
                                  data=json.dumps(
                                      dict(event_name="test2",
                                           event_tags=['a', 'b'],
                                           event_json={"text": "cooltext"},
                                           namespace="custom2")))

        log = Log.query.first()

        assert (log.event_name == "test2")
        assert ('a' in log.event_tags)
        assert ('b' in log.event_tags)
        assert (log.event_json['text'] == "cooltext")
        assert (log.namespace == 'custom2')
예제 #3
0
def post_log_with_api_key():
    """
    POST:
        Posts a new event.
        Accepts JSON body _OR_ URL parameters:
            timestamp :: Integer -- Unix/POSIX time, milliseconds
            namespace :: String
            event_name :: String
            event_tags :: comma-separated String
            event_text :: String --> results in event_json: {text: <event_text>}
        URL parameters are OVERWRITTEN by body of request.
    """

    json = request.get_json(force=True, silent=True)
    args = request.args.to_dict()

    try:
        uuid.UUID(args['api_key'], version=4)
        user = User.query.filter(User.api_key == args['api_key']).first()
    except:
        return jsonify({'error': 'Invalid API Key.'}), 401

    del args['api_key']

    if not json:
        json = {}

    if 'event_text' in args:
        if 'event_json' in json:
            if not 'text' in json['event_json']:
                json['event_json']['text'] = args['event_text']
        else:
            json['event_json'] = {'text': args['event_text']}
        del args['event_text']

    if 'event_tags' in args:
        args['event_tags'] = args['event_tags'].split(',')

    json = {**args, **json}

    json['user'] = user

    try:
        newEventSchema(json)
    except Exception as e:
        return jsonify(
            {'error':
             'Improper request. Check documentation and try again.'}), 400

    try:
        log = Log(**json)
        db.session.add(log)
        db.session.commit()
        return '', 200
    except Exception as e:
        return jsonify({'error': 'unknown error'}), 400
예제 #4
0
    def test_delete_log(self):
        user = User.query.first()
        log = Log(user=user, event_name="testlog")
        db.session.add(log)
        db.session.commit()

        assert (len(Log.query.all()) == 1)

        res = self.open_with_auth(url=API_PREFIX + '/log/' + str(log.id),
                                  method='DELETE',
                                  username=user.username,
                                  password="******",
                                  data=None)

        assert (len(Log.query.all()) == 0)
예제 #5
0
def receive_sms():
    # Sender's phone numer
    from_number = int(request.values.get('From'))
    # Receiver's phone number - Plivo number
    to_number = int(request.values.get('To'))
    # The text which was received
    text = str(request.values.get('Text'))

    # Find user
    user = User.query.filter_by(sms_number=from_number).first()
    if not user:
        return "Invalid user", 400

    if not user.sms_verified:
        if text.strip().lower() == user.username.lower():
            user.sms_verified = True
            user.sms_verified_on = datetime.now()
            db.session.commit()
            send_sms(
                to_number,
                "Congrats your number is verified! Anything you text to this number will now be logged."
            )

        #do not log anything
        return '', 200

    text = text.split("@@")
    event_name = text[0].strip()
    event_text = ""
    if len(text) > 1:
        event_text = "".join(text[1:]).strip()

    log = Log(user, event_name, event_json={'text': event_text})
    db.session.add(log)
    db.session.commit()

    return '', 200
예제 #6
0
def log_by_email():
    if not verify_mailgun(request.values.get('token'),
                          request.values.get('timestamp'),
                          request.values.get('signature')):
        return 'Unauthorized', 401

    email = str(request.values.get('from'))
    email = email[email.find("<") + 1:email.find(">")]

    # Find user
    user = User.query.filter_by(email=email).first()
    if not user:
        return "Invalid user", 400

    if not user.email_verified:
        #do not log anything
        return 'Not verified', 400

    log = Log(user,
              request.values.get('subject'),
              event_json={'text': request.values.get('stripped-text')})
    db.session.add(log)
    db.session.commit()
    return '', 200
예제 #7
0
def logs():
    """
    POST:
        Posts a new event.
        Accepts JSON body _OR_ URL parameters:
            timestamp :: Integer -- Unix/POSIX time, milliseconds
            namespace :: String
            event_name :: String
            event_tags :: comma-separated String
            event_text :: String --> results in event_json: {text: <event_text>}
        URL parameters are OVERWRITTEN by body of request.

    GET:
        Retrieves events.
        Accepts URL parameters:
            namespace
            event_name
            event_tags
            timestart :: Integer
            timestop :: Integer
            max_events :: Integer
            offset: Integer
    """

    if request.method == 'POST':
        json = request.get_json(force=True, silent=True)
        args = request.args.to_dict()

        if not json:
            json = {}

        if 'event_text' in args:
            if 'event_json' in json:
                if not 'text' in json['event_json']:
                    json['event_json']['text'] = args['event_text']
            else:
                json['event_json'] = {'text': args['event_text']}
            del args['event_text']

        if 'event_tags' in args:
            args['event_tags'] = args['event_tags'].split(',')

        json = {**args, **json}

        json['user'] = g.user

        try:
            newEventSchema(json)
        except Exception as e:
            return jsonify({
                'error':
                'Improper request. Check documentation and try again.'
            }), 400

        try:
            log = Log(**json)
            db.session.add(log)
            db.session.commit()
            return '', 200
        except Exception as e:
            return jsonify({'error': 'unknown error'}), 400

    elif request.method == 'GET':
        args = request.args.to_dict()

        if args.get('timestart'):
            args['timestart'] = int(args['timestart'])
        if args.get('timestop'):
            args['timestop'] = int(args['timestop'])
        if args.get('max_events'):
            args['max_events'] = int(args['max_events'])
        if args.get('offset') is not None:
            args['offset'] = int(args['offset'])

        if len(args):
            try:
                getEventsSchema(args)
            except Exception:
                return jsonify({
                    'error':
                    'Improper request. Check documentation and try again.'
                }), 400

        query = Log.query.filter_by(user_id = g.user.id).\
            order_by(Log.timestamp.desc())

        if args.get('timestart'):
            query = query.filter(Log.timestamp > args['timestart'])
        if args.get('timestop'):
            query = query.filter(Log.timestamp < args['timestop'])
        if args.get('namespace'):
            query = query.filter(Log.namespace == args['namespace'])
        if args.get('event_name'):
            query = query.filter(Log.event_name == args['event_name'])
        if args.get('event_tags'):
            query = query.filter(Log.event_tags.contains(args['event_tags']))
        if args.get('max_events'):
            query = query.limit(args['max_events'])
        else:
            query = query.limit(100)
        if args.get('offset') is not None:
            query = query.offset(args['offset'])

        cols = Log.__table__.columns
        res = [row_to_json(row, cols) for row in query.all()]

        return jsonify({'logs': res}), 200