def approve(self, user):
     """ Authenticate the token. User has to be present.
     """
     with db.engine.connect() as connection:
         connection.execute(text("UPDATE api_compat.token SET user_id = :uid WHERE token=:token"),
                            {'uid': User.get_id(user), 'token': self.token})
     self.user = User.load_by_name(user)
Beispiel #2
0
 def approve(self, user):
     """ Authenticate the token. User has to be present.
     """
     with db.engine.connect() as connection:
         connection.execute(text("UPDATE api_compat.token SET user_id = :uid WHERE token=:token"),
                            {'uid': User.get_id(user), 'token': self.token})
     self.user = User.load_by_name(user)
Beispiel #3
0
def user_info(request, data):
    """ Gives information about the user specified in the parameters.
    """
    try:
        output_format = data.get('format', 'xml')
        api_key = data['api_key']
        sk = data.get('sk')
        username = data.get('user')
        if not (sk or username):
            raise KeyError

        if not Token.is_valid_api_key(api_key):
            raise InvalidAPIUsage(
                CompatError.INVALID_API_KEY,
                output_format=output_format)  # Invalid API key

        user = User.load_by_sessionkey(sk, api_key)
        if not user:
            raise InvalidAPIUsage(
                CompatError.INVALID_SESSION_KEY,
                output_format=output_format)  # Invalid Session key

        query_user = User.load_by_name(username) if (
            username and username != user.name) else user
        if not query_user:
            raise InvalidAPIUsage(
                CompatError.INVALID_RESOURCE,
                output_format=output_format)  # Invalid resource specified

    except KeyError:
        raise InvalidAPIUsage(
            CompatError.INVALID_PARAMETERS,
            output_format=output_format)  # Missing required params

    doc, tag, text = Doc().tagtext()
    with tag('lfm', status='ok'):
        with tag('user'):
            with tag('name'):
                text(query_user.name)
            with tag('realname'):
                text(query_user.name)
            with tag('url'):
                text('http://listenbrainz.org/user/' + query_user.name)
            with tag('playcount'):
                text(
                    User.get_play_count(query_user.id,
                                        timescale_connection._ts))
            with tag('registered',
                     unixtime=str(query_user.created.strftime("%s"))):
                text(str(query_user.created))

    return format_response(
        '<?xml version="1.0" encoding="utf-8"?>\n' +
        yattag.indent(doc.getvalue()), data.get('format', "xml"))
Beispiel #4
0
 def __init__(self, id, user_id, sid, api_key, timestamp):
     self.id = id
     self.sid = sid
     self.api_key = api_key
     self.timestamp = timestamp
     self.user_id = user_id
     self.user = User.load_by_id(user_id)
 def test_session_create(self):
     user = User.load_by_id(db_user.create("test"))
     token = Token.generate(user.api_key)
     token.approve(user.name)
     session = Session.create(token)
     self.assertIsInstance(session, Session)
     self.assertDictEqual(user.__dict__, session.user.__dict__)
def session_info(request, data):
    try:
        sk = data['sk']
        api_key = data['api_key']
        output_format = data.get('format', 'xml')
        username = data['username']
    except KeyError:
        raise InvalidAPIUsage(CompatError.INVALID_PARAMETERS, output_format=output_format)        # Missing Required Params

    session = Session.load(sk)
    if (not session) or User.load_by_name(username).id != session.user.id:
        raise InvalidAPIUsage(CompatError.INVALID_SESSION_KEY, output_format=output_format)       # Invalid Session KEY

    print("SESSION INFO for session %s, user %s" % (session.id, session.user.name))

    doc, tag, text = Doc().tagtext()
    with tag('lfm', status='ok'):
        with tag('application'):
            with tag('session'):
                with tag('name'):
                    text(session.user.name)
                with tag('key'):
                    text(session.id)
                with tag('subscriber'):
                    text('0')
                with tag('country'):
                    text('US')

    return format_response('<?xml version="1.0" encoding="utf-8"?>\n' + yattag.indent(doc.getvalue()),
                           output_format)
Beispiel #7
0
 def test_user_get_play_count(self):
     date = datetime(2015, 9, 3, 0, 0, 0)
     test_data = generate_data(date, 100, self.user.name)
     self.assertEqual(len(test_data), 100)
     self.logstore.insert(test_data)
     count = User.get_play_count(self.user.id, self.logstore)
     self.assertEqual(count, 100)
def api_auth_approve():
    """ Authenticate the user token provided.
    """
    user = User.load_by_name(current_user.musicbrainz_id)
    if "token" not in request.form:
        return render_template(
            "user/auth.html",
            user_id=current_user.musicbrainz_id,
            msg="Missing required parameters. Please provide correct parameters and try again."
        )
    token = Token.load(request.form['token'])
    if not token:
        return render_template(
            "user/auth.html",
            user_id=current_user.musicbrainz_id,
            msg="Either this token is already used or invalid. Please try again."
        )
    if token.user:
        return render_template(
            "user/auth.html",
            user_id=current_user.musicbrainz_id,
            msg="This token is already approved. Please check the token and try again."
        )
    if token.has_expired():
        return render_template(
            "user/auth.html",
            user_id=current_user.musicbrainz_id,
            msg="This token has expired. Please create a new token and try again."
        )
    token.approve(user.name)
    return render_template(
        "user/auth.html",
        user_id=current_user.musicbrainz_id,
        msg="Token %s approved for user %s, press continue in client." % (token.token, current_user.musicbrainz_id)
    )
 def test_session_create(self):
     user = User.load_by_id(db_user.create(1, "test"))
     token = Token.generate(user.api_key)
     token.approve(user.name)
     session = Session.create(token)
     self.assertIsInstance(session, Session)
     self.assertDictEqual(user.__dict__, session.user.__dict__)
    def setUp(self):
        super(TestAPICompatUserClass, self).setUp()
        self.log = logging.getLogger(__name__)
        self.logstore = init_influx_connection(
            self.log, {
                'INFLUX_HOST': config.INFLUX_HOST,
                'INFLUX_PORT': config.INFLUX_PORT,
                'INFLUX_DB_NAME': config.INFLUX_DB_NAME,
                'REDIS_HOST': config.REDIS_HOST,
                'REDIS_PORT': config.REDIS_PORT,
            })

        # Create a user
        uid = db_user.create("test_api_compat_user")
        self.assertIsNotNone(db_user.get(uid))
        with db.engine.connect() as connection:
            result = connection.execute(
                text("""
                SELECT *
                  FROM "user"
                 WHERE id = :id
            """), {
                    "id": uid,
                })
            row = result.fetchone()
            self.user = User(row['id'], row['created'], row['musicbrainz_id'],
                             row['auth_token'])

        # Insert some listens
        date = datetime(2015, 9, 3, 0, 0, 0)
        self.log.info("Inserting test data...")
        test_data = generate_data(date, 100, self.user.name)
        self.logstore.insert(test_data)
        self.log.info("Test data inserted")
 def test_user_get_play_count(self):
     date = datetime(2015, 9, 3, 0, 0, 0)
     test_data = generate_data(date, 100, self.user.name)
     self.assertEqual(len(test_data), 100)
     self.logstore.insert(test_data)
     count = User.get_play_count(self.user.id, self.logstore)
     self.assertEqual(count, 100)
Beispiel #12
0
    def setUp(self):
        super(TestAPICompatUserClass, self).setUp()
        self.log = logging.getLogger(__name__)
        self.logstore = init_influx_connection(
            self.log, {
                'INFLUX_HOST': config.INFLUX_HOST,
                'INFLUX_PORT': config.INFLUX_PORT,
                'INFLUX_DB_NAME': config.INFLUX_DB_NAME,
                'REDIS_HOST': config.REDIS_HOST,
                'REDIS_PORT': config.REDIS_PORT,
                'REDIS_NAMESPACE': config.REDIS_NAMESPACE,
            })

        # Create a user
        uid = db_user.create("test_api_compat_user")
        self.assertIsNotNone(db_user.get(uid))
        with db.engine.connect() as connection:
            result = connection.execute(
                text("""
                SELECT *
                  FROM "user"
                 WHERE id = :id
            """), {
                    "id": uid,
                })
            row = result.fetchone()
            self.user = User(row['id'], row['created'], row['musicbrainz_id'],
                             row['auth_token'])
Beispiel #13
0
 def setUp(self):
     super(APICompatTestCase, self).setUp()
     self.lb_user = db_user.get_or_create(1, 'apicompattestuser')
     self.lfm_user = User(
         self.lb_user['id'],
         self.lb_user['created'],
         self.lb_user['musicbrainz_id'],
         self.lb_user['auth_token'],
     )
     self.log = logging.getLogger(__name__)
     self.ls = timescale_connection._ts
def user_info(request, data):
    """ Gives information about the user specified in the parameters.
    """
    try:
        api_key = data['api_key']
        output_format = data.get('format', 'xml')
        sk = data.get('sk')
        username = data.get('user')
        if not (sk or username):
            raise KeyError

        if not Token.is_valid_api_key(api_key):
            raise InvalidAPIUsage(CompatError.INVALID_API_KEY, output_format=output_format)     # Invalid API key

        user = User.load_by_sessionkey(sk, api_key)
        if not user:
            raise InvalidAPIUsage(CompatError.INVALID_SESSION_KEY, output_format=output_format)  # Invalid Session key

        query_user = User.load_by_name(username) if (username and username != user.name) else user
        if not query_user:
            raise InvalidAPIUsage(CompatError.INVALID_RESOURCE, output_format=output_format)     # Invalid resource specified

    except KeyError:
        raise InvalidAPIUsage(CompatError.INVALID_PARAMETERS, output_format=output_format)       # Missing required params

    doc, tag, text = Doc().tagtext()
    with tag('lfm', status='ok'):
        with tag('user'):
            with tag('name'):
                text(query_user.name)
            with tag('realname'):
                text(query_user.name)
            with tag('url'):
                text('http://listenbrainz.org/user/' + query_user.name)
            with tag('playcount'):
                text(User.get_play_count(query_user.id, _influx))
            with tag('registered', unixtime=str(query_user.created.strftime("%s"))):
                text(str(query_user.created))

    return format_response('<?xml version="1.0" encoding="utf-8"?>\n' + yattag.indent(doc.getvalue()),
                           data.get('format', "xml"))
    def setUp(self):
        super(TestAPICompatTokenClass, self).setUp()
        self.log = logging.getLogger(__name__)

        # Create a user
        uid = db_user.create(1, "test")
        self.assertIsNotNone(db_user.get(uid))
        with db.engine.connect() as connection:
            result = connection.execute(
                text('SELECT * FROM "user" WHERE id = :id'), {"id": uid})
            row = result.fetchone()
            self.user = User(row['id'], row['created'], row['musicbrainz_id'],
                             row['auth_token'])
    def test_session_load(self):
        user = User.load_by_id(db_user.create("test"))
        token = Token.generate(user.api_key)
        token.approve(user.name)
        session = Session.create(token)
        self.assertIsInstance(session, Session)
        self.assertDictEqual(user.__dict__, session.user.__dict__)
        session.user = None

        # Load with session_key + api_key
        session2 = Session.load(session.sid, session.api_key)
        self.assertDictEqual(user.__dict__, session2.__dict__['user'].__dict__)
        session2.user = None
        self.assertDictEqual(session.__dict__, session2.__dict__)
    def test_session_load(self):
        user = User.load_by_id(db_user.create(1, "test"))
        token = Token.generate(user.api_key)
        token.approve(user.name)
        session = Session.create(token)
        self.assertIsInstance(session, Session)
        self.assertDictEqual(user.__dict__, session.user.__dict__)
        session.user = None

        # Load with session_key + api_key
        session2 = Session.load(session.sid)
        self.assertDictEqual(user.__dict__, session2.__dict__['user'].__dict__)
        session2.user = None
        self.assertDictEqual(session.__dict__, session2.__dict__)
 def setUp(self):
     super(APICompatTestCase, self).setUp()
     self.lb_user = db_user.get_or_create(1, 'apicompattestuser')
     self.lfm_user = User(
         self.lb_user['id'],
         self.lb_user['created'],
         self.lb_user['musicbrainz_id'],
         self.lb_user['auth_token'],
     )
     self.log = logging.getLogger(__name__)
     self.ls = init_timescale_connection(
         self.log, {
             'REDIS_HOST': config.REDIS_HOST,
             'REDIS_PORT': config.REDIS_PORT,
             'REDIS_NAMESPACE': config.REDIS_NAMESPACE,
             'SQLALCHEMY_TIMESCALE_URI': config.SQLALCHEMY_TIMESCALE_URI,
         })
Beispiel #19
0
    def setUp(self):
        super(APICompatTestCase, self).setUp()
        self.lb_user = db_user.get_or_create(1, 'apicompattestuser')
        self.lfm_user = User(
            self.lb_user['id'],
            self.lb_user['created'],
            self.lb_user['musicbrainz_id'],
            self.lb_user['auth_token'],
        )

        self.ls = InfluxListenStore(
            {
                'REDIS_HOST': current_app.config['REDIS_HOST'],
                'REDIS_PORT': current_app.config['REDIS_PORT'],
                'REDIS_NAMESPACE': current_app.config['REDIS_NAMESPACE'],
                'INFLUX_HOST': current_app.config['INFLUX_HOST'],
                'INFLUX_PORT': current_app.config['INFLUX_PORT'],
                'INFLUX_DB_NAME': current_app.config['INFLUX_DB_NAME'],
            }, self.app.logger)
Beispiel #20
0
def api_auth_approve():
    """ Authenticate the user token provided.
    """
    user = User.load_by_name(current_user.musicbrainz_id)
    if "token" not in request.form:
        return render_template(
            "user/auth.html",
            user_id=current_user.musicbrainz_id,
            msg=
            "Missing required parameters. Please provide correct parameters and try again."
        )
    token = Token.load(request.form['token'])
    if not token:
        return render_template(
            "user/auth.html",
            user_id=current_user.musicbrainz_id,
            msg=
            "Either this token is already used or invalid. Please try again.")
    if token.user:
        return render_template(
            "user/auth.html",
            user_id=current_user.musicbrainz_id,
            msg=
            "This token is already approved. Please check the token and try again."
        )
    if token.has_expired():
        return render_template(
            "user/auth.html",
            user_id=current_user.musicbrainz_id,
            msg=
            "This token has expired. Please create a new token and try again.")
    token.approve(user.name)
    return render_template(
        "user/auth.html",
        user_id=current_user.musicbrainz_id,
        msg="Token %s approved for user %s, press continue in client." %
        (token.token, current_user.musicbrainz_id))
Beispiel #21
0
def session_info(request, data):
    try:
        sk = data['sk']
        api_key = data['api_key']
        output_format = data.get('format', 'xml')
        username = data['username']
    except KeyError:
        raise InvalidAPIUsage(
            CompatError.INVALID_PARAMETERS,
            output_format=output_format)  # Missing Required Params

    session = Session.load(sk, api_key)
    if (not session) or User.load_by_name(username).id != session.user.id:
        raise InvalidAPIUsage(
            CompatError.INVALID_SESSION_KEY,
            output_format=output_format)  # Invalid Session KEY

    print("SESSION INFO for session %s, user %s" %
          (session.id, session.user.name))

    doc, tag, text = Doc().tagtext()
    with tag('lfm', status='ok'):
        with tag('application'):
            with tag('session'):
                with tag('name'):
                    text(session.user.name)
                with tag('key'):
                    text(session.id)
                with tag('subscriber'):
                    text('0')
                with tag('country'):
                    text('US')

    return format_response(
        '<?xml version="1.0" encoding="utf-8"?>\n' +
        yattag.indent(doc.getvalue()), output_format)
 def __init__(self, id, userid, token, api_key, ts):
     self.id = id
     self.token = token
     self.api_key = api_key
     self.timestamp = ts
     self.user = User.load_by_id(userid)
 def test_user_load_by_name(self):
     user = User.load_by_name(self.user.name)
     assert isinstance(user, User) == True
     self.assertDictEqual(user.__dict__, self.user.__dict__)
 def test_user_get_play_count(self):
     count = User.get_play_count(self.user.id, self.logstore)
     self.assertEqual(count, 100)
 def __init__(self, id, userid, token, api_key, ts):
     self.id = id
     self.token = token
     self.api_key = api_key
     self.timestamp = ts
     self.user = User.load_by_id(userid)
Beispiel #26
0
 def test_user_load_by_id(self):
     user = User.load_by_id(self.user.id)
     self.assertTrue(isinstance(user, User))
     self.assertDictEqual(user.__dict__, self.user.__dict__)
 def test_user_load_by_id(self):
     user = User.load_by_id(self.user.id)
     self.assertTrue(isinstance(user, User))
     self.assertDictEqual(user.__dict__, self.user.__dict__)
Beispiel #28
0
 def test_user_get_id(self):
     uid = User.get_id(self.user.name)
     self.assertEqual(uid, self.user.id)
 def test_user_get_id(self):
     uid = User.get_id(self.user.name)
     self.assertEqual(uid, self.user.id)