def test_json_serializer(self): DatabaseManager.reset() account = Account(name=u'tester', email='*****@*****.**') dt = datetime.datetime(2010, 1, 1, 0, 0, tzinfo=pytz.utc) account.created_at = dt account.__json_public__.append('created_at') d = account.to_json() self.assertEquals(d['created_at'], 1262304000) self.assertEquals(d['name'], 'tester') self.assertEquals(d['email'], '*****@*****.**')
def login(): data = request.json account = Account.get_by(email=data['email'], single=True) if not account or not account.verify_passwd(data['passwd']): raise AppError(HTTPStatus.STATUS_CLIENT_ERROR, CustomError.ERR_WRONG_PASSWD, 'Invalid combination of email and password') ret = account.to_json() ret[Key.AUTH_TOKEN] = account.auth_token return jsonify(ret)
def setup_prerequisite(self): register_all_modules() self.account1 = Account( name=u'test', email='*****@*****.**').set_passwd('12345678').add() self.account2 = Account( name=u'test2', email='*****@*****.**').set_passwd('12345678').add() DatabaseManager.commit() self.login(self.account1) self.create_bot() self.create_broadcast(self.bot_ids[0]) self.login(self.account2) self.create_bot() self.create_broadcast(self.bot_ids[1]) # Login back as account1 self.login(self.account1)
def setup_prerequisite(self): register_all_modules() self.account1 = Account( name=u'test', email='*****@*****.**').set_passwd('12345678').add() self.account2 = Account( name=u'test2', email='*****@*****.**').set_passwd('12345678').add() DatabaseManager.commit() self.login(self.account1) self.create_bot() self.create_platform('dev/bb8.test.platform') self.login(self.account2) self.create_bot() self.create_platform('dev/bb8.test2.platform') # Login back as account1 self.login(self.account1)
def test_auth(self): DatabaseManager.reset() account = Account(name=u'Test Account 3', email='*****@*****.**').add() some_passwd = 'abcdefg' account.set_passwd(some_passwd) DatabaseManager.commit() account_ = Account.get_by(id=account.id, single=True) self.assertNotEquals(account_.passwd, some_passwd) self.assertEquals(account_.verify_passwd(some_passwd), True) self.assertEquals(account_.verify_passwd('should be wrong'), False) token = account_.auth_token account_t = Account.from_auth_token(token) self.assertEquals(account_.id, account_t.id) fake_token = jwt.encode({ 'iss': 'compose.ai', 'sub': account_.id, 'jti': str(uuid.uuid4()), 'iat': datetime.datetime.utcnow(), 'exp': datetime.datetime.utcnow() + datetime.timedelta(days=14) }, 'im fake secret') with self.assertRaises(RuntimeError): Account.from_auth_token(fake_token) outdated_token = jwt.encode({ 'iss': 'compose.ai', 'sub': account_.id, 'jti': str(uuid.uuid4()), 'iat': datetime.datetime.utcnow() - datetime.timedelta(days=30), 'exp': datetime.datetime.utcnow() - datetime.timedelta(days=15) }, config.JWT_SECRET) with self.assertRaises(RuntimeError): Account.from_auth_token(outdated_token)
def email_register(): data = request.json try: jsonschema.validate(data, REGISTER_SCHEMA) pytz.timezone(data['timezone']) except Exception: raise AppError(HTTPStatus.STATUS_CLIENT_ERROR, CustomError.ERR_FORM_VALIDATION, 'schema validation fail') account = Account.get_by(email=data['email'], single=True) if not account: account = Account(email=data['email']).set_passwd(data['passwd']).add() DatabaseManager.commit() else: raise AppError(HTTPStatus.STATUS_CLIENT_ERROR, CustomError.ERR_USER_EXISTED, 'email %s is already taken' % data['email']) ret = account.to_json() ret[Key.AUTH_TOKEN] = account.auth_token return jsonify(ret)
def test_timestamp_update(self): """Make sure the updated_at timestamp automatically updates on commit.""" account = Account(email='*****@*****.**', passwd='test_hashed').add() DatabaseManager.commit() account.refresh() self.assertEquals(account.created_at, account.updated_at) last_updated = account.updated_at time.sleep(1) account.email = '*****@*****.**' DatabaseManager.commit() account.refresh() self.assertNotEquals(last_updated, account.updated_at)
def decorated(*args, **kwargs): if Key.X_COMPOSEAI_AUTH not in request.headers: raise AppError(HTTPStatus.STATUS_CLIENT_ERROR, CustomError.ERR_UNAUTHENTICATED, 'Not loggined') auth_header = request.headers[Key.X_COMPOSEAI_AUTH] parts = auth_header.split() if parts[0] != 'Bearer': raise AppError(HTTPStatus.STATUS_CLIENT_ERROR, CustomError.ERR_UNAUTHENTICATED, 'Invalid auth token') try: token = parts[1] g.account = Account.from_auth_token(token) except RuntimeError: raise AppError(HTTPStatus.STATUS_CLIENT_ERROR, CustomError.ERR_UNAUTHENTICATED, 'The token %s is invalid' % token) return func(*args, **kwargs)
def test_schema_sanity(self): """Populate data into all tables and make sure there are no error.""" DatabaseManager.reset() account = Account(name=u'Test Account', email='*****@*****.**', passwd='test_hashed').add() bot = Bot(name=u'test', description=u'test', interaction_timeout=120, session_timeout=86400).add() account.bots.append(bot) content = ContentModule(id='test', name='Content1', description='desc', module_name='', ui_module_name='').add() parser = ParserModule(id='test', name='Parser1', description='desc', module_name='passthrough', ui_module_name='', variables={}).add() # Test for oauth schema oauth1 = OAuthInfo(provider=OAuthProviderEnum.Facebook, provider_ident='mock-facebook-id').add() oauth2 = OAuthInfo(provider=OAuthProviderEnum.Github, provider_ident='mock-github-id').add() account.oauth_infos.append(oauth1) account.oauth_infos.append(oauth2) DatabaseManager.commit() account_ = Account.get_by(id=account.id, single=True) self.assertNotEquals(account_, None) self.assertEquals(len(account_.oauth_infos), 2) oauth_ = OAuthInfo.get_by(provider_ident='mock-facebook-id', single=True) self.assertNotEquals(oauth_, None) self.assertNotEquals(oauth_.account, None) self.assertEquals(oauth_.account.id, account.id) # Test for bot account.bots.append(bot) DatabaseManager.commit() self.assertNotEquals(Account.get_by(id=account.id, single=True), None) self.assertNotEquals(Bot.get_by(id=bot.id, single=True), None) self.assertNotEquals(ContentModule.get_by(id=content.id, single=True), None) self.assertNotEquals(ParserModule.get_by(id=parser.id, single=True), None) # Check acccount_bot association table self.assertEquals(len(account.bots), 1) self.assertEquals(account.bots[0].id, bot.id) platform = Platform(name=u'Test platform', bot_id=bot.id, type_enum=PlatformTypeEnum.Facebook, provider_ident='facebook_page_id', config={}).add() DatabaseManager.commit() self.assertNotEquals(Platform.get_by(id=platform.id, single=True), None) self.assertEquals(len(bot.platforms), 1) self.assertEquals(bot.platforms[0].id, platform.id) node1 = Node(stable_id='node1', name=u'1', bot_id=bot.id, expect_input=True, content_module_id=content.id, content_config={}, parser_module_id=parser.id, parser_config={}).add() node2 = Node(stable_id='node2', name=u'2', bot_id=bot.id, expect_input=True, content_module_id=content.id, content_config={}, parser_module_id=parser.id, parser_config={}).add() node3 = Node(stable_id='node3', name=u'3', bot_id=bot.id, expect_input=True, content_module_id=content.id, content_config={}, parser_module_id=parser.id, parser_config={}).add() bot.orphan_nodes.append(node3) DatabaseManager.commit() self.assertNotEquals(Node.get_by(id=node1.id, single=True), None) self.assertNotEquals(Node.get_by(id=node2.id, single=True), None) self.assertNotEquals(Node.get_by(id=node3.id, single=True), None) # Test bot_node association table self.assertEquals(bot.orphan_nodes[0].id, node3.id) user = User(platform_id=platform.id, platform_user_ident='', last_seen=datetime.datetime.now()).add() DatabaseManager.commit() self.assertNotEquals(User.get_by(id=user.id, single=True), None) event = Event(bot_id=bot.id, user_id=user.id, event_name='event', event_value={}).add() DatabaseManager.commit() self.assertNotEquals(Event.get_by(id=event.id, single=True), None) collected_datum = CollectedDatum(user_id=user.id, key='key', value={}).add() DatabaseManager.commit() self.assertNotEquals(CollectedDatum.get_by(id=collected_datum.id, single=True), None) self.assertEquals(len(user.colleted_data), 1) self.assertEquals(user.colleted_data[0].id, collected_datum.id) conversation = Conversation(bot_id=bot.id, user_id=user.id, sender_enum=SenderEnum.Bot, msg={}).add() DatabaseManager.commit() self.assertNotEquals(Conversation.get_by(id=conversation.id, single=True), None) # Broadcast bc = Broadcast(account_id=account.id, bot_id=bot.id, name=u'New broadcast', messages=[], scheduled_time=datetime.datetime.utcnow()).add() DatabaseManager.commit() self.assertNotEquals(Broadcast.get_by(id=bc.id, single=True), None) # PublicFeed, Feed account = Account(name=u'Test Account - 1', email='*****@*****.**', passwd='test_hashed').add() feed1 = Feed(url='example.com/rss', type=FeedEnum.RSS, title=u'foo.com', image_url='foo.com/logo').add() feed2 = Feed(url='example.com/rss', type=FeedEnum.RSS, title=u'bar.com', image_url='bar.com/logo').add() feed3 = Feed(url='example.com/rss', type=FeedEnum.RSS, title=u'baz.com', image_url='baz.com/logo').add() account.feeds.append(feed1) account.feeds.append(feed2) account.feeds.append(feed3) DatabaseManager.commit() self.assertNotEquals(Feed.get_by(id=feed1.id, single=True), None) feeds = Feed.search_title('ba') self.assertEquals(len(list(feeds)), 2) pfeed = PublicFeed(url='example.com/rss', type=FeedEnum.RSS, title=u'example.com', image_url='example.com/logo').add() DatabaseManager.commit() self.assertNotEquals(PublicFeed.get_by(id=pfeed.id, single=True), None)
def setup_prerequisite(self): Account(name=u'test', email='*****@*****.**').set_passwd('12345678').add() DatabaseManager.commit()