def setUp(self):
        ServerTestCase.setUp(self)
        DatabaseTestCase.setUp(self)

        self.log = logging.getLogger(__name__)
        self.influx = InfluxDBClient(
            host=current_app.config['INFLUX_HOST'],
            port=current_app.config['INFLUX_PORT'],
            database=current_app.config['INFLUX_DB_NAME'],
        )

        self.influx.query('''create database %s''' % current_app.config['INFLUX_DB_NAME'])

        self.logstore = init_influx_connection(self.log, {
            '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'],
        })

        user = db_user.get_or_create(1, 'iliekcomputers')
        self.user = User.from_dbrow(user)

        weirduser = db_user.get_or_create(2, 'weird\\user name')
        self.weirduser = User.from_dbrow(weirduser)
Example #2
0
    def setUp(self):
        ServerTestCase.setUp(self)
        DatabaseTestCase.setUp(self)

        self.log = logging.getLogger(__name__)
        self.influx = InfluxDBClient(
            host=current_app.config['INFLUX_HOST'],
            port=current_app.config['INFLUX_PORT'],
            database=current_app.config['INFLUX_DB_NAME'],
        )

        self.influx.query('''create database %s''' %
                          current_app.config['INFLUX_DB_NAME'])

        self.logstore = init_influx_connection(
            self.log, {
                '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'],
            })

        user = db_user.get_or_create(1, 'iliekcomputers')
        db_user.agree_to_gdpr(user['musicbrainz_id'])
        self.user = User.from_dbrow(user)

        weirduser = db_user.get_or_create(2, 'weird\\user name')
        self.weirduser = User.from_dbrow(weirduser)
Example #3
0
    def setUp(self):
        super(UserViewsTestCase, self).setUp()

        self.log = logging.getLogger(__name__)
        self.logstore = timescale_connection._ts

        user = db_user.get_or_create(1, 'iliekcomputers')
        db_user.agree_to_gdpr(user['musicbrainz_id'])
        self.user = User.from_dbrow(user)

        weirduser = db_user.get_or_create(2, 'weird\\user name')
        self.weirduser = User.from_dbrow(weirduser)

        abuser = db_user.get_or_create(3, 'abuser')
        self.abuser = User.from_dbrow(abuser)
Example #4
0
def get_user():
    """Function should fetch user data from database, or, if necessary, create it, and return it."""
    s = _musicbrainz.get_auth_session(
        data={
            'code': _fetch_data('code'),
            'grant_type': 'authorization_code',
            'redirect_uri': url_for('login.musicbrainz_post', _external=True)
        },
        decoder=lambda b: ujson.loads(b.decode("utf-8")))
    data = s.get('oauth2/userinfo').json()
    musicbrainz_id = data.get('sub')
    musicbrainz_row_id = data.get('metabrainz_user_id')
    user = db_user.get_or_create(musicbrainz_row_id, musicbrainz_id)
    if user:
        if not user['musicbrainz_row_id']:
            db_user.update_musicbrainz_row_id(musicbrainz_id,
                                              data['metabrainz_user_id'])

        # if the musicbrainz_id of the user from MusicBrainz is different, we need
        # to update it here too
        if user['musicbrainz_id'] != musicbrainz_id:
            db_user.update_musicbrainz_id(user['id'], musicbrainz_id)

        return User.from_dbrow(user)
    else:
        return None
Example #5
0
    def test_ts_filters(self, timescale):
        """Check that max_ts and min_ts are passed to timescale """
        user = User.from_dbrow(db_user.get(1)).to_dict()
        timescale.return_value = ([], 0, 0)

        # If no parameter is given, use current time as the to_ts
        self.client.get(url_for('user.profile', user_name='iliekcomputers'))
        req_call = mock.call(user, limit=25, from_ts=None)
        timescale.assert_has_calls([req_call])
        timescale.reset_mock()

        # max_ts query param -> to_ts timescale param
        self.client.get(url_for('user.profile', user_name='iliekcomputers'),
                        query_string={'max_ts': 1520946000})
        req_call = mock.call(user, limit=25, to_ts=1520946000)
        timescale.assert_has_calls([req_call])
        timescale.reset_mock()

        # min_ts query param -> from_ts timescale param
        self.client.get(url_for('user.profile', user_name='iliekcomputers'),
                        query_string={'min_ts': 1520941000})
        req_call = mock.call(user, limit=25, from_ts=1520941000)
        timescale.assert_has_calls([req_call])
        timescale.reset_mock()

        # If max_ts and min_ts set, only max_ts is used
        self.client.get(url_for('user.profile', user_name='iliekcomputers'),
                        query_string={
                            'min_ts': 1520941000,
                            'max_ts': 1520946000
                        })
        req_call = mock.call(user, limit=25, to_ts=1520946000)
        timescale.assert_has_calls([req_call])
Example #6
0
    def setUp(self):
        ServerTestCase.setUp(self)
        DatabaseTestCase.setUp(self)

        self.log = logging.getLogger(__name__)
        self.logstore = init_timescale_connection(self.log, {
            'REDIS_HOST': current_app.config['REDIS_HOST'],
            'REDIS_PORT': current_app.config['REDIS_PORT'],
            'REDIS_NAMESPACE': current_app.config['REDIS_NAMESPACE'],
            'SQLALCHEMY_TIMESCALE_URI': self.app.config['SQLALCHEMY_TIMESCALE_URI']
        })

        user = db_user.get_or_create(1, 'iliekcomputers')
        db_user.agree_to_gdpr(user['musicbrainz_id'])
        self.user = User.from_dbrow(user)

        weirduser = db_user.get_or_create(2, 'weird\\user name')
        self.weirduser = User.from_dbrow(weirduser)
Example #7
0
def _get_user(user_name):
    """ Get current username """
    if current_user.is_authenticated() and \
       current_user.musicbrainz_id == user_name:
        return current_user
    else:
        user = db_user.get_by_mb_id(user_name)
        if user is None:
            raise NotFound("Cannot find user: %s" % user_name)
        return User.from_dbrow(user)
Example #8
0
def _get_user(user_name):
    """ Get current username """
    if current_user.is_authenticated and \
       current_user.musicbrainz_id == user_name:
        return current_user
    else:
        user = db_user.get_by_mb_id(user_name)
        if user is None:
            raise NotFound("Cannot find user: %s" % user_name)
        return User.from_dbrow(user)
Example #9
0
def get_user():
    """Function should fetch user data from database, or, if necessary, create it, and return it."""
    s = _musicbrainz.get_auth_session(
        data={
            'code': _fetch_data('code'),
            'grant_type': 'authorization_code',
            'redirect_uri': url_for('login.musicbrainz_post', _external=True)
        },
        decoder=lambda b: ujson.loads(b.decode("utf-8")))
    data = s.get('oauth2/userinfo').json()
    user = db_user.get_or_create(data.get('sub'))
    if user:
        return User.from_dbrow(user)
    else:
        return None
def get_user():
    """Function should fetch user data from database, or, if necessary, create it, and return it."""
    s = _musicbrainz.get_auth_session(data={
        'code': _fetch_data('code'),
        'grant_type': 'authorization_code',
        'redirect_uri': url_for('login.musicbrainz_post', _external=True)
    }, decoder=lambda b: ujson.loads(b.decode("utf-8")))
    data = s.get('oauth2/userinfo').json()
    musicbrainz_id = data.get('sub')
    musicbrainz_row_id = data.get('metabrainz_user_id')
    user = db_user.get_or_create(musicbrainz_row_id, musicbrainz_id)
    if user:
        if not user['musicbrainz_row_id']:
            db_user.update_musicbrainz_row_id(musicbrainz_id, data['metabrainz_user_id'])
        return User.from_dbrow(user)
    else:
        return None
Example #11
0
def get_user():
    """Function should fetch user data from database, or, if necessary, create it, and return it."""
    s = _musicbrainz.get_auth_session(data={
        'code': _fetch_data('code'),
        'grant_type': 'authorization_code',
        'redirect_uri': url_for('login.musicbrainz_post', _external=True)
    }, decoder=lambda b: ujson.loads(b.decode("utf-8")))
    data = s.get('oauth2/userinfo').json()
    musicbrainz_id = data.get('sub')
    musicbrainz_row_id = data.get('metabrainz_user_id')
    user_exists_check = db_user.get_by_mb_id(musicbrainz_id)
    user = db_user.get_or_create(musicbrainz_row_id, musicbrainz_id)
    if user:
        if user_exists_check is None:
            ts.set_empty_cache_values_for_user(musicbrainz_id)
        if not user['musicbrainz_row_id']:
            db_user.update_musicbrainz_row_id(musicbrainz_id, data['metabrainz_user_id'])
        return User.from_dbrow(user)
    else:
        return None
Example #12
0
def musicbrainz_post():
    """Callback endpoint."""

    no_email_warning = Markup(
        'You have not provided an email address. Please provide an '
        '<a href="https://musicbrainz.org/account/edit">email address</a> ')
    blog_link = Markup(
        'Read this <a href="https://blog.metabrainz.org/?p=8915">blog post</a> '
        'to understand why we need your email.')

    if provider.validate_post_login():
        try:
            user = provider.get_user()
            if current_app.config[
                    "REJECT_NEW_USERS_WITHOUT_EMAIL"] and not user["email"]:
                # existing user without email, show a warning
                flash.warning(
                    no_email_warning +
                    'before 1 November 2021, or you will be unable to submit '
                    'listens. ' + blog_link)

            db_user.update_last_login(user["musicbrainz_id"])
            login_user(User.from_dbrow(user),
                       remember=True,
                       duration=datetime.timedelta(
                           current_app.config['SESSION_REMEMBER_ME_DURATION']))
            next = session.get('next')
            if next:
                return redirect(next)
        except MusicBrainzAuthSessionError:
            flash.error("Login failed.")
        except MusicBrainzAuthNoEmailError:
            # new user without email tried to create an account
            flash.error(no_email_warning +
                        'before creating a ListenBrainz account. ' + blog_link)
    else:
        flash.error("Login failed.")
    return redirect(url_for('index.index'))