Exemplo n.º 1
0
    def test_get_user_by_name_or_mail(self):
        """ Checks user retrieval from the database """
        user_one = User.get_user_by_name_or_mail(self.name1)
        user_two = User.get_user_by_name_or_mail(self.email1)

        self.assertEqual(user_one, user_two)
        self.assertEqual(user_one, self.user1)
Exemplo n.º 2
0
 def test_get_users(self):
     """ Checks user retrieval with limits """
     self.assertEqual(len(User.get_users()), 2)
     self.assertEqual(len(User.get_users(limit=0)), 0)
     User("goat", "*****@*****.**", "1234").create()
     self.assertEqual(len(User.get_users()), 3)
     self.assertEqual(len(User.get_users(limit=1)), 1)
Exemplo n.º 3
0
def _get_slack_data(days):
    settings = Settings.query().get()
    try:
        api_key = settings.api_key
    except AttributeError:
        api_key = os.environ.get('SLACK_API_KEY')
        if api_key is None:
            raise Exception('please set environment variable SLACK_API_KEY')
        else:
            Settings(api_key=api_key).put()

    sd = SlackDumper(api_key)
    ents = set(dir(User))
    for user_data in sd.get_user_list():
        user_id = user_data['id']
        user_data = {k: v for k, v in user_data.items() if k in ents}
        user = User.query(User.id == user_id).get()
        if user is None:
            User(**user_data).put()
        else:
            for k, v in user_data.items():
                setattr(user, k, v)
            user.put()

    ents = set(dir(Channel))
    for channel_data in sd.get_channel_list():
        channel_id = channel_data['id']
        channel_data = {k: v for k, v in channel_data.items() if k in ents}
        channel = Channel.query(Channel.id == channel_id).get()
        if channel is None:
            Channel(**channel_data).put()
        else:
            for k, v in channel_data.items():
                setattr(channel, k, v)
            channel.put()

    ents = set(dir(Message))
    for channel_id, messages in sd.get_channels_histoey(days=days).items():
        for message in messages:
            message['channel_id'] = channel_id
            user = message.get('user', '')
            ts_raw = message['ts']
            ts = float(ts_raw)
            message['ts'] = float(ts_raw)
            message['ts_raw'] = ts_raw

            message = {k: v for k, v in message.items() if k in ents}
            if not ROBUST_IMPORTING_MODE:
                msg = Message.query().filter(Message.channel_id == channel_id, Message.user == user, Message.ts == ts).get()
            else:
                msg = Message.query().filter(Message.channel_id == channel_id, Message.user ==
                                             user, Message.ts > ts - 1, Message.ts < ts + 1).get()
            if msg is None:
                Message(**message).put()
            else:
                for k, v in message.items():
                    setattr(msg, k, v)
                msg.put()
Exemplo n.º 4
0
    def test_no_email_and_username_same_on_two_users(self):
        """
        Checks that a username cannot be the same as the email as another user. This is a requirement for our login
        """
        with self.assertRaises(lib.exceptions.DataManipulationException):
            User("*****@*****.**", "*****@*****.**", "hello").create()

        User("*****@*****.**", "*****@*****.**", "hello").create()
        with self.assertRaises(lib.exceptions.DataManipulationException):
            User("goat", "*****@*****.**", "no").create()
Exemplo n.º 5
0
def _import_zip_log(io_buffer):
    logger.debug('start')

    szd = SlackZipDumpedLog(zipfile.ZipFile(BytesIO(io_buffer.read())))

    ents = set(dir(User))
    for user_data in szd.users_data:
        user_id = user_data['id']
        user_data = {k: v for k, v in user_data.items() if k in ents}
        user = User.query(User.id == user_id).get()
        if user is None:
            User(**user_data).put()
        else:
            for k, v in user_data.items():
                setattr(user, k, v)
            user.put()
    logger.debug('user end')

    ents = set(dir(Channel))
    for channel_data in szd.channels_data:
        channel_id = channel_data['id']
        channel_data['created'] = int(channel_data['created'])

        channel_data = {k: v for k, v in channel_data.items() if k in ents}
        channel = Channel.query(Channel.id == channel_id).get()
        if channel is None:
            Channel(**channel_data).put()
        else:
            for k, v in channel_data.items():
                setattr(channel, k, v)
            channel.put()

    logger.debug('channel end')
    ents = set(dir(Message))
    for channel_id, messages in szd.map_message_data.items():
        for message in messages.values():
            message['channel_id'] = channel_id
            user = message.get('user', '')
            ts_raw = str(message['ts'])
            ts = float(ts_raw)
            message['ts'] = ts
            message['ts_raw'] = ts_raw

            message = {k: v for k, v in message.items() if k in ents}
            msg = Message.query().filter(Message.channel_id == channel_id,
                                         Message.user == user,
                                         Message.ts == ts).get()
            if msg is None:
                Message(**message).put()
            else:
                for k, v in message.items():
                    setattr(msg, k, v)
                msg.put()
    logger.debug('exit')
Exemplo n.º 6
0
    def setUp(self):
        """ Creates two base users to reason about in our tests"""
        super().setUp()
        self.name1 = "goatsy"
        self.email1 = "*****@*****.**"
        self.password1 = "verysecure"
        self.user1 = User(self.name1, self.email1, self.password1).create()

        self.name2 = "Impersonator"
        self.email2 = "bob"
        self.password2 = "notVeryInventive"
        self.user2 = User(self.name2, self.email2, self.password2).create()
Exemplo n.º 7
0
    def test_set_admin(self):
        """ Checks the user admin works """
        self.assertFalse(self.user1.is_admin)

        self.user1.set_admin()
        self.assertTrue(self.user1.is_admin)
        self.assertTrue(User.get_user_by_id(self.user1.get_id()).is_admin)
        self.assertFalse(User.get_user_by_id(self.user2.get_id()).is_admin)

        self.user1.set_admin(False)
        self.assertFalse(self.user1.is_admin)
        self.assertFalse(User.get_user_by_id(self.user1.get_id()).is_admin)
        self.assertFalse(User.get_user_by_id(self.user2.get_id()).is_admin)
Exemplo n.º 8
0
def user_orders():
    user_id = request.json.get("user_id")
    new_user = User.get_or_create(name="hamza3",
                                  mail='*****@*****.**',
                                  password='******',
                                  organization_id='client3')
    print(new_user.id)
    user = User.get_by_id(user_id)
    orders = user.get_my_priced_orders_jsonified()
    return jsonify({
        "message": "orders successfully returned",
        "results": orders
    }), 200
Exemplo n.º 9
0
def login_index():
    form = LoginForm()
    if request.method == 'POST' and form.validate_on_submit():
        user_name = form.username.data
        password = form.password.data
        remember_me = form.remember_me.data
        user = query_user(user_name)

        if user is not None and password == user['password']:
            curr_user = User()
            curr_user.id = user_name
            login_user(curr_user, remember=True)
            return redirect(request.args.get('next') or url_for('index'))

        flash('用户名或密码错误!')
    return render_template('login/login.html', title="Sign In", form=form)
Exemplo n.º 10
0
def load_user(user_id: int) -> User:
    """
    Loads the user from the database

    :param user_id: id of the user to load
    :return: a User instance
    """
    return User.get_user_by_id(user_id)
Exemplo n.º 11
0
def user_orders():
    user_id = request.json.get("user_id")
    user = User.get_by_id(user_id)
    orders = user.get_my_priced_orders_jsonified()

    return jsonify({
      "message": "orders successfully returned",
      "results": orders
    }), 200
Exemplo n.º 12
0
def regist_user():
    name = request.form['name']
    if User.query.filter(User.name == name).first():
        return render_template('register.thml',
                               message='username already exist')
    if request.form['password'] == request.form['passwd_confirmation']:
        password = request.form['password']
    user = User(name=name, password=password)
    db.session.add(user)
    db.session.commit()
    return index()
Exemplo n.º 13
0
def send_reset_email(email):
    try:
        user = User.get(User.email == email)
    except User.DoesNotExist:
        raise falcon.HTTPNotFound(description='The user does not exist.')

    token = token_serializer.dumps((user.id, str(user.reset_key)))

    message = MIMEText(token, 'plain')
    message['Subject'] = 'Reset your password'

    send_message(email, message)
Exemplo n.º 14
0
def send_confirm_email(email):
    try:
        user = User.get(User.email == email)
    except User.DoesNotExist:
        raise falcon.HTTPNotFound(description='The user does not exist.')

    token = token_serializer.dumps(user.id)

    message = MIMEText(token, 'plain')
    message['Subject'] = 'Confirm your email address'

    send_message(email, message)
Exemplo n.º 15
0
    def setUp(self):
        self.app = create_app(**test_config)
        self.client = self.app.test_client()
        self.db = db

        self._ctx = self.app.test_request_context()
        self._ctx.push()

        with self.app.app_context():
            self.db.create_all()

        # create test model
        self.model_name = 'test_model'
        self.model = Model(self.model_name)

        # create test user
        self.user = User(email='*****@*****.**', password='******', name='sup')
        self.model.register(self.user)
        self.db.session.add(self.user)
        self.db.session.add(self.model)
        self.db.session.commit()
Exemplo n.º 16
0
    def validate(self, **extras) -> bool:
        """
        Validates that the user authenticated correctly

        :param extras: additional arguments
        :return: whether the login succeeded or not
        """
        if not super().validate():
            return False

        user = User.get_user_by_name_or_mail(self.username.data)

        if user is None:
            self.username.errors.append("Unknown username")
            return False

        if not user.check_password(self.password.data):
            self.password.errors.append("Invalid Password")
            return False

        self.user = user
        return True
Exemplo n.º 17
0
def authenticate(email, password):
    try:
        user = User.get(User.email == email)
    except User.DoesNotExist:
        raise falcon.HTTPNotFound(description='The user does not exist.')

    if user.confirmed_at is None:
        raise falcon.HTTPBadRequest(
            description='The user has not been confirmed.')

    if not bcrypt.checkpw(password.encode(), user.hash):
        raise falcon.HTTPUnauthorized(
            description='The user could not be authenticated.')

    claims = {
        'exp': time.time() + 60 * 60 * 24,
        'iat': time.time(),
        'user_id': user.id
    }

    safe_user = model_to_dict(user, recurse=False, exclude=[User.hash])
    return (safe_user, jwt.encode(claims, 'secret', algorithm='HS256'))
Exemplo n.º 18
0
def create_user(email, password):
    try:
        hash = bcrypt.hashpw(password.encode(), bcrypt.gensalt())
        return User.create(email=email, hash=hash)
    except peewee.IntegrityError:
        raise falcon.HTTPConflict(description='The user already exists.')
Exemplo n.º 19
0
class APITest(unittest.TestCase):
    def setUp(self):
        self.app = create_app(**test_config)
        self.client = self.app.test_client()
        self.db = db

        self._ctx = self.app.test_request_context()
        self._ctx.push()

        with self.app.app_context():
            self.db.create_all()

        # create test model
        self.model_name = 'test_model'
        self.model = Model(self.model_name)

        # create test user
        self.user = User(email='*****@*****.**', password='******', name='sup')
        self.model.register(self.user)
        self.db.session.add(self.user)
        self.db.session.add(self.model)
        self.db.session.commit()

    def tearDown(self):
        for dir in [test_config['REPO_DIR'], test_config['ARCHIVE_DIR']]:
            shutil.rmtree(dir)

        if self._ctx is not None:
            self._ctx.pop()

        with self.app.app_context():
            self.db.session.remove()
            self.db.drop_all()

        del self.app
        del self.client
        del self._ctx


    def _make_user(self):
        user = User(email='*****@*****.**', password='******', name='sup2')
        self.db.session.add(user)
        self.db.session.commit()
        return user

    def _publish_model(self, version):
        meta = {'version': version}
        model = {'params': [1,1,1]}
        self.model.publish(meta, model, version)
        self.model.make_archive(version)
        return meta, model

    def _extract_tar(self, data):
        # extract files to disk
        tar = tarfile.open(fileobj=io.BytesIO(data))
        tar.extractall('/tmp/')
        with open('/tmp/meta.json', 'r') as f:
            meta = json.load(f)
        with open('/tmp/model.json', 'r') as f:
            model = json.load(f)
        return meta, model

    def _request(self, method, endpoint, auth=None, data=None):
        kwargs = {
            'headers': [('Content-Type', 'application/json')]
        }
        if auth is not None:
            kwargs['headers'].append(('Authentication-Token', auth))
        if data is not None:
            kwargs['data'] = json.dumps(data)
        return getattr(self.client, method.lower())(endpoint, **kwargs)

    def test_get_model_without_archives(self):
        resp = self._request('GET', '/models/{}'.format(self.model_name))
        self.assertEquals(resp.status_code, 404)

    def test_get_nonexistent_model(self):
        resp = self._request('GET', '/models/sup')
        self.assertEquals(resp.status_code, 404)

    def test_publish_model(self):
        meta = {'version': '1.0.0'}
        model = {'params': [1,1,1]}
        resp = self._request('POST', '/models/{}'.format(self.model_name),
                             auth=self.user.get_auth_token(),
                             data={'meta': meta, 'model': model})
        self.assertEquals(resp.status_code, 200)
        self.assertEquals(self.model.latest, '1.0.0')

        # check that all files are there and proper
        repo_path = os.path.join(test_config['REPO_DIR'], self.model_name)
        archive_path = os.path.join(test_config['ARCHIVE_DIR'], self.model_name, '1.0.0.tar')
        meta_path = os.path.join(repo_path, 'meta.json')
        model_path = os.path.join(repo_path, 'model.json')
        for path in [archive_path, repo_path, meta_path, model_path]:
            self.assertTrue(os.path.exists(path))
        self.assertEquals(json.load(open(meta_path, 'r')), meta)
        self.assertEquals(json.load(open(model_path, 'r')), model)

    def test_publish_model_not_owner(self):
        meta = {'version': '1.0.0'}
        model = {'params': [1,1,1]}
        resp = self._request('POST', '/models/{}'.format(self.model_name),
                             auth='sup',
                             data={'meta': meta, 'model': model})
        self.assertEquals(resp.status_code, 401)

    def test_publish_model_invalid_version(self):
        self._publish_model('1.0.0')
        meta = {'version': '0.0.5'}
        model = {'params': [1,1,1]}
        resp = self._request('POST', '/models/{}'.format(self.model_name),
                             auth=self.user.get_auth_token(),
                             data={'meta': meta, 'model': model})
        self.assertEquals(resp.status_code, 400)
        self.assertEquals(self.model.latest, '1.0.0')

    def test_get_model(self):
        meta, model = self._publish_model('1.0.0')

        resp = self._request('GET', '/models/{}'.format(self.model_name))
        self.assertEquals(resp.status_code, 200)
        meta_, model_ = self._extract_tar(resp.data)
        self.assertEquals(meta, meta_)
        self.assertEquals(model, model_)

    def test_get_model_specific_version(self):
        meta_old, model_old = self._publish_model('1.0.0')
        meta_new, model_new = self._publish_model('2.0.0')

        # get latest
        resp = self._request('GET', '/models/{}'.format(self.model_name))
        self.assertEquals(resp.status_code, 200)
        meta_, model_ = self._extract_tar(resp.data)
        self.assertEquals(meta_new, meta_)
        self.assertEquals(model_new, model_)

        # get specific version
        resp = self._request('GET', '/models/{}/1.0.0'.format(self.model_name))
        self.assertEquals(resp.status_code, 200)
        meta_, model_ = self._extract_tar(resp.data)
        self.assertEquals(meta_old, meta_)
        self.assertEquals(model_old, model_)

    def test_get_model_meta(self):
        meta, model = self._publish_model('1.0.0')
        resp = self._request('GET', '/models/{}.json'.format(self.model_name))
        self.assertEquals(resp.status_code, 200)
        resp_json = json.loads(resp.data.decode('utf-8'))
        self.assertEquals(resp_json, meta)

    def test_delete_version_not_owner(self):
        meta, model = self._publish_model('1.0.0')
        resp = self._request('DELETE', '/models/{}/1.0.0'.format(self.model_name),
                             auth='sup')
        self.assertEquals(resp.status_code, 401)

    def test_delete_nonexistent_version(self):
        meta, model = self._publish_model('1.0.0')
        resp = self._request('DELETE', '/models/{}/2.0.0'.format(self.model_name),
                             auth=self.user.get_auth_token())
        self.assertEquals(resp.status_code, 404)

    def test_delete_version(self):
        self._publish_model('1.0.0')
        self._publish_model('2.0.0')
        resp = self._request('DELETE', '/models/{}/1.0.0'.format(self.model_name),
                             auth=self.user.get_auth_token())
        self.assertEquals(resp.status_code, 200)

        # check that archive is gone
        archive_path = os.path.join(test_config['ARCHIVE_DIR'], self.model_name, '1.0.0.tar')
        self.assertFalse(os.path.exists(archive_path))

    def test_remove_model(self):
        self._publish_model('1.0.0')
        resp = self._request('DELETE', '/models/{}'.format(self.model_name),
                             auth=self.user.get_auth_token())
        self.assertEquals(resp.status_code, 200)

        # check that everything is gone
        archive_path = os.path.join(test_config['ARCHIVE_DIR'], self.model_name)
        repo_path = os.path.join(test_config['REPO_DIR'], self.model_name)
        self.assertFalse(os.path.exists(archive_path))
        self.assertFalse(os.path.exists(repo_path))

    def test_change_ownership(self):
        self._publish_model('1.0.0')
        user = self._make_user()
        resp = self._request('PUT', '/models/{}'.format(self.model_name),
                             auth=self.user.get_auth_token(),
                             data={'user': user.name})
        self.assertEquals(resp.status_code, 200)
        self.assertEquals(self.model.owner, user)

    def test_change_ownership_nonexistent_user(self):
        self._publish_model('1.0.0')
        resp = self._request('PUT', '/models/{}'.format(self.model_name),
                             auth=self.user.get_auth_token(),
                             data={'user': '******'})
        self.assertEquals(resp.status_code, 404)

    def test_register_model(self):
        resp = self._request('POST', '/models/register',
                             auth=self.user.get_auth_token(),
                             data={'user': self.user.name, 'name': 'new_model'})
        self.assertEquals(resp.status_code, 200)

    def test_register_existing_model(self):
        resp = self._request('POST', '/models/register',
                             auth=self.user.get_auth_token(),
                             data={'user': self.user.name, 'name': self.model.name})
        self.assertEquals(resp.status_code, 409)

    def test_register_unauthenticated(self):
        resp = self._request('POST', '/models/register',
                             data={'user': self.user.name, 'name': self.model.name})
        self.assertEquals(resp.status_code, 401)
Exemplo n.º 20
0
 def _make_user(self):
     user = User(email='*****@*****.**', password='******', name='sup2')
     self.db.session.add(user)
     self.db.session.commit()
     return user
Exemplo n.º 21
0
 def test_user_can_have_same_name_and_email(self):
     """ Checks that a user can have the same email and username """
     User("*****@*****.**", "*****@*****.**", "hi").create()
Exemplo n.º 22
0
class TestUser(TestCaseWithDB, unittest.TestCase):
    """
    Defines tests for our User model
    """
    @classmethod
    def table_creation_commands(cls) -> Iterable[str]:
        """ commands to execute to setup the database for our tests """
        return [User._table_creation_command()]

    @classmethod
    def tables_to_truncate(cls) -> Iterable[str]:
        """ tables to empty after each test """
        return ["user"]

    def setUp(self):
        """ Creates two base users to reason about in our tests"""
        super().setUp()
        self.name1 = "goatsy"
        self.email1 = "*****@*****.**"
        self.password1 = "verysecure"
        self.user1 = User(self.name1, self.email1, self.password1).create()

        self.name2 = "Impersonator"
        self.email2 = "bob"
        self.password2 = "notVeryInventive"
        self.user2 = User(self.name2, self.email2, self.password2).create()

    def test_check_password(self):
        """ Attest that passwords are correctly checked """
        self.assertTrue(self.user1.check_password("verysecure"))
        self.assertFalse(self.user1.check_password("NotVerySecure"))

    def test_get_user_by_name_or_mail(self):
        """ Checks user retrieval from the database """
        user_one = User.get_user_by_name_or_mail(self.name1)
        user_two = User.get_user_by_name_or_mail(self.email1)

        self.assertEqual(user_one, user_two)
        self.assertEqual(user_one, self.user1)

    def test_get_user_by_id(self):
        """ Checks that getting a user by id indeed returns the same user (also tests our __eq__ function) """
        user_id = self.user1.get_id()
        new_user = User.get_user_by_id(user_id)
        self.assertEqual(self.user1, new_user)

    def test_get_users(self):
        """ Checks user retrieval with limits """
        self.assertEqual(len(User.get_users()), 2)
        self.assertEqual(len(User.get_users(limit=0)), 0)
        User("goat", "*****@*****.**", "1234").create()
        self.assertEqual(len(User.get_users()), 3)
        self.assertEqual(len(User.get_users(limit=1)), 1)

    def test_set_admin(self):
        """ Checks the user admin works """
        self.assertFalse(self.user1.is_admin)

        self.user1.set_admin()
        self.assertTrue(self.user1.is_admin)
        self.assertTrue(User.get_user_by_id(self.user1.get_id()).is_admin)
        self.assertFalse(User.get_user_by_id(self.user2.get_id()).is_admin)

        self.user1.set_admin(False)
        self.assertFalse(self.user1.is_admin)
        self.assertFalse(User.get_user_by_id(self.user1.get_id()).is_admin)
        self.assertFalse(User.get_user_by_id(self.user2.get_id()).is_admin)

    def test_no_same_username(self):
        """ Checks that two users with the same username cannot be created """
        with self.assertRaises(lib.exceptions.DataManipulationException):
            User("goatsy", "*****@*****.**", "1234").create()

    def test_no_same_emails(self):
        """ Checks that two users with the same email cannot be created """
        with self.assertRaises(lib.exceptions.DataManipulationException):
            User("goat", "*****@*****.**", "no").create()

    def test_no_email_and_username_same_on_two_users(self):
        """
        Checks that a username cannot be the same as the email as another user. This is a requirement for our login
        """
        with self.assertRaises(lib.exceptions.DataManipulationException):
            User("*****@*****.**", "*****@*****.**", "hello").create()

        User("*****@*****.**", "*****@*****.**", "hello").create()
        with self.assertRaises(lib.exceptions.DataManipulationException):
            User("goat", "*****@*****.**", "no").create()

    def test_user_can_have_same_name_and_email(self):
        """ Checks that a user can have the same email and username """
        User("*****@*****.**", "*****@*****.**", "hi").create()
Exemplo n.º 23
0
 def test_no_same_emails(self):
     """ Checks that two users with the same email cannot be created """
     with self.assertRaises(lib.exceptions.DataManipulationException):
         User("goat", "*****@*****.**", "no").create()
Exemplo n.º 24
0
 def test_no_same_username(self):
     """ Checks that two users with the same username cannot be created """
     with self.assertRaises(lib.exceptions.DataManipulationException):
         User("goatsy", "*****@*****.**", "1234").create()
Exemplo n.º 25
0
 def table_creation_commands(cls) -> Iterable[str]:
     """ commands to execute to setup the database for our tests """
     return [User._table_creation_command()]
Exemplo n.º 26
0
 def test_get_user_by_id(self):
     """ Checks that getting a user by id indeed returns the same user (also tests our __eq__ function) """
     user_id = self.user1.get_id()
     new_user = User.get_user_by_id(user_id)
     self.assertEqual(self.user1, new_user)