def add_organization_user(authn, organization_uuid): # pylint: disable=too-many-return-statements """Add user to organization.""" try: post_data = request.get_json() organization = Organization.from_uuid(UUID(organization_uuid)) admin = User.from_uuid(authn.sub) except TypeError: raise ParseError('Missing membership payload.') except ValueError: raise ParseError('Invalid organization UUID.') except NoResultFound: raise NotFound('Organization does not exist') try: user = User.from_uuid(post_data['user_uuid']) except KeyError: raise ParseError('Invalid membership payload.') except NoResultFound: raise NotFound('User does not exist') if admin.uuid in organization.admin_uuids(): if user.uuid in organization.reader_uuids(): raise InvalidRequest('User is already part of organization.') role = post_data.get('role', 'read') try: organization.add_user(user, role_in_org=role) result = {'message': f'${user.username} added to ${organization.name}'} return result, 200 except IntegrityError as integrity_error: current_app.logger.exception('IntegrityError encountered.') raise InternalError(str(integrity_error)) raise PermissionDenied('You do not have permission to add a user to that organization.')
def test_get_user_by_id(self): user1, user2 = init_users(2) db.session.add_all([user1, user2]) db.session.commit() self.assertEqual(User.get_user_by_id(1), user1) self.assertEqual(User.get_user_by_id(2), user2) with self.assertRaises(UserNotFoundByIndexError): User.get_user_by_id(3)
def test_bad_signature_password_token(self): user, = init_users(1) db.session.add(user) db.session.commit() token = user.get_reset_password_token() token = token[:10] with self.assertRaises(BadSignature): User.get_user_by_reset_password_token(token)
def test_expired_password_token(self): user, = init_users(1) db.session.add(user) db.session.commit() token = user.get_reset_password_token(1) time.sleep(2) with self.assertRaises(SignatureExpired): User.get_user_by_reset_password_token(token)
def test_reset_password_token(self): user1, user2 = init_users(2) db.session.add_all([user1, user2]) db.session.commit() token1 = user1.get_reset_password_token() token2 = user2.get_reset_password_token() self.assertEqual(user1, User.get_user_by_reset_password_token(token1)) self.assertEqual(user2, User.get_user_by_reset_password_token(token2))
def add_user(username, email, password, created_at=datetime.datetime.utcnow()): """Wrap functionality for adding user.""" user = User( username=username, email=email, created_at=created_at, ) user.password_authentication = PasswordAuthentication(password=password) return user.save()
def test_authentication_token(self): user, = init_users(1) db.session.add(user) db.session.commit() token = user.get_authentication_token() self.assertEqual(user, User.get_user_by_authentication_token(token)) token_modified = token + 'blabla' with self.assertRaises(BadSignature): User.get_user_by_authentication_token(token_modified) token_expired = user.get_authentication_token(expires_in=1) time.sleep(2) with self.assertRaises(SignatureExpired): User.get_user_by_authentication_token(token_expired)
def test_add_user_duplicate_email(self): """Ensure duplicate email addresses are not allowed.""" add_user('justatest', '*****@*****.**', 'password') duplicate_user = User( username='******', email='*****@*****.**', ) self.assertRaises(IntegrityError, duplicate_user.save)
def init_users(number) -> List[User]: """Returns given number of users with sequent emails and usernames""" users = [] for i in range(1, number + 1): users.append( User(email=f'user{i}@gmail.com', username=f'user{i}', name=f'name{i}', password_hash='123')) return users
def get_organization_users(authn, organization_uuid): """Get single organization's users.""" org = Organization.from_uuid(organization_uuid) authn_user = User.from_uuid(authn.sub) if authn else None if (authn_user and authn_user.uuid in org.reader_uuids()) or org.is_public: result = { 'users': [user.serializable() for user in org.users], } return result, 200 raise PermissionDenied('You do not have permission to see that group.')
def register_user(): """Register user.""" try: post_data = request.get_json() username = post_data['username'] email = post_data['email'] password = post_data['password'] except TypeError: raise ParseError('Missing registration payload.') except KeyError: raise ParseError('Invalid registration payload.') # Check for existing user user = User.query.filter(or_(User.username == username, User.email == email)).first() if user is not None: raise InvalidRequest('Sorry. That user already exists.') try: # Add new user to db new_user = User( username=username, email=email, ) new_user.password_authentication = PasswordAuthentication(password=password) db.session.add(new_user) db.session.commit() except IntegrityError as integrity_error: current_app.logger.exception('There was a problem with registration.') db.session.rollback() raise InternalError(str(integrity_error)) # Generate auth token auth_token = encode_auth_token(new_user) result = {'auth_token': auth_token.decode()} return result, 201
def add_organization(authn): """Add organization.""" try: post_data = request.get_json() org_name = post_data['name'] primary_admin = User.from_uuid(authn.sub) is_public = post_data.get('is_public', True) except NoResultFound: raise NotFound('User does not exist') except TypeError: raise ParseError('Missing organization payload.') except KeyError: raise ParseError('Invalid organization payload.') try: org = Organization.from_user(primary_admin, org_name, is_public=is_public) return org.serializable(), 201 except IntegrityError: current_app.logger.exception('There was a problem adding an organization.') raise InternalError(str(integrity_error))
def test_get_chat_id_by_users_ids(self): db.session.add_all(init_users(3)) db.session.commit() with self.assertRaises(ChatNotFoundByIndexesError): User.get_chat_id_by_users_ids(1, 2) with self.assertRaises(ChatNotFoundByIndexesError): User.get_chat_id_by_users_ids(2, 1) User.create_chat(1, 2) User.create_chat(2, 3) db.session.commit() self.assertTrue( User.get_chat_id_by_users_ids(1, 2) == User.get_chat_id_by_users_ids(2, 1)) self.assertTrue( User.get_chat_id_by_users_ids(2, 3) == User.get_chat_id_by_users_ids(3, 2)) with self.assertRaises(ChatNotFoundByIndexesError): User.get_chat_id_by_users_ids(1, 3) User.delete_chat(two_users_ids=[3, 2]) User.delete_chat(two_users_ids=[2, 1]) db.session.commit() with self.assertRaises(ChatNotFoundByIndexesError): User.get_chat_id_by_users_ids(2, 3) with self.assertRaises(ChatNotFoundByIndexesError): User.get_chat_id_by_users_ids(1, 2)
def test_users_create_delete_chat(self): user1, user2 = init_users(2) db.session.add_all([ user1, user2, ]) db.session.commit() with self.assertRaises(ChatNotFoundByIndexesError): User.delete_chat(two_users_ids=[1, 2]) self.assertFalse(User.is_chat_between(1, 2)) self.assertFalse(User.is_chat_between(2, 1)) result = db.session.execute(select(chats)) self.assertEqual(len(result.all()), 0) result.close() User.create_chat(1, 2) db.session.commit() with self.assertRaises(ChatAlreadyExistsError): User.create_chat(2, 1) self.assertTrue(User.is_chat_between(1, 2)) self.assertTrue(User.is_chat_between(2, 1)) result = db.session.execute(select(chats)) self.assertEqual(result.all()[0], (1, 1, 2)) result.close() User.delete_chat(two_users_ids=[1, 2]) User.create_chat(2, 1) db.session.commit() self.assertTrue(User.is_chat_between(1, 2)) self.assertTrue(User.is_chat_between(2, 1)) result = db.session.execute(select(chats)) self.assertEqual(result.all()[0], (1, 1, 2)) result.close() User.delete_chat(chat_id=1) db.session.commit() self.assertFalse(User.is_chat_between(1, 2)) self.assertFalse(User.is_chat_between(2, 1)) result = db.session.execute(select(chats)) self.assertEqual(len(result.all()), 0) result.close()