def test_validate_email_false(self, mock_u): """ test: email does already exist in database. """ from xmppchat.CustomValidatonError import CustomValidationError mock_u.query.filter_by.return_value.first.return_value = User( "testuser", "*****@*****.**", "hallo123", "topic-id1") with pytest.raises(CustomValidationError): Validator.validate_email("*****@*****.**")
def register(): """ registers a user on platform ejabberd and kafka and inserts the user into the user database """ if current_user.is_authenticated: return get_url_chatpage(current_user.user_id) if request.method == "POST": req_content = request.get_json() if not req_content: return make_response(jsonify({'feedback': 'invalid post data.', 'category': 'danger'}), 404) res, exit_code = {'feedback': 'registration successfull.', 'category': 'success'}, 200 topic_id = str(uuid.uuid4()) try: Validator.validate_username(req_content["username"]) Validator.validate_email(req_content["eMail"]) user_reg_obj = UserManagement(config['ejabberd_ip'], config['ejabberd_ssh_user'], priv_key=config['ejabberd_ssh_private_key'], sudo_passwd=config['ejabberd_ssh_sudo_password']) return_code = user_reg_obj.create_user_remotely(req_content["username"], req_content["password"], config["ejabberd_domain"]) if return_code != 0: raise CustomValidationError("Error. User was not created. Please try again.") kafka_admin_client = KafkaAdminClient(bootstrap_servers=f'{config["apache_kafka_ip"]}:{config["apache_kafka_port"]}') topic_list = [NewTopic(name=topic_id, num_partitions=1, replication_factor=1)] kafka_admin_client.create_topics(new_topics=topic_list, validate_only=False) user = User(req_content["username"], req_content["eMail"], req_content["password"], topic_id) db.session.add(user) db.session.commit() except KeyError as e: loggger.error(str(e)) res, exit_code = {'feedback': 'invalid credentials.', 'category': 'danger'}, 401 except CustomValidationError as cve: logger.error(str(cve)) res, exit_code = {'feedback': str(cve), 'category': 'danger'}, 401 except Exception as e: db.session.rollback() return_code = user_reg_obj.delete_user_remotely(req_content["username"], config["ejabberd_domain"]) if return_code != 0: res, exit_code = {'feedback': 'User could not be created. Another error occurred while handling an internal error.', 'category': 'danger'}, 500 else: res, exit_code = {'feedback': 'Users could not be created due to an internal error.', 'category': 'danger'}, 500 logger.error(e) return make_response(jsonify(res), exit_code) else: return render_template('register.html', navs=navs, currentNav="Go Chat!")
def test_contains_invalid_characters_true(self): """ test: username is None """ username = None result = Validator.contains_invalid_characters(username) self.assertTrue(result)
def test_contains_invalid_characters_true(self): """ test: username contains invalid characters e.g. .-/ or starts with digits. -> behaviour defined as regex """ result = [ Validator.contains_invalid_characters(name) for name in self.invalid_strings ] self.assertTrue(all(result))
def test_contains_invalid_characters_false(self): """ test: username contains valid characters. """ result = [ Validator.contains_invalid_characters(name) for name in self.valid_strings ] self.assertFalse(all(result))
def add_contact(): """ Adds a contact to a user's contact list, chooses the right client depending on the platform selected """ global session_dict if not current_user.is_authenticated: return make_response(jsonify({"feedback": "not authorized."}), 401) try: JSON_Data = request.get_json() if not JSON_Data or not all(key in JSON_Data for key in ("username", "requested_platform")): return make_response(jsonify({"feedback": "invalid post data."}), 404) user_name = JSON_Data.get("username") if Validator.contains_invalid_characters(user_name): return make_response(jsonify({"feedback": "invalid username."}), 403) result = User.query.filter_by(username=user_name).first() if not result: return make_response(jsonify({"feedback": "username does not exist."}), 404) if result.user_id == current_user.user_id: return make_response(jsonify({"feedback": "invalid username. You cannot write with yourself."}), 403) if JSON_Data.get("requested_platform") == "xmpp": session_dict[current_user.user_id]["xmpp_object"].update_roster(f'{user_name}@{config["ejabberd_domain"]}', name=user_name, subscription='both') return make_response(jsonify({"feedback": "added contact successfully."}), 200) elif JSON_Data.get("requested_platform") == "kafka": try: sql = 'INSERT INTO contacts VALUES((SELECT user_id FROM user_auth WHERE username=:username),:user_id), (:user_id, (SELECT user_id FROM user_auth WHERE username=:username));' db.session.execute(sql, {'user_id': current_user.user_id, 'username': user_name}) db.session.commit() return make_response(jsonify({"feedback": "added contact successfully."}), 200) except exc.IntegrityError as e: return make_response(jsonify({"feedback": "Contact relationship does already exist."}), 404) return make_response(jsonify({"feedback": "error wrong platform."}), 404) except Exception as e: logger.error(str(e)) return make_response(jsonify({"feedback": "contact has not been added due to an internal failure."}), 500)
def test_validate_email_true(self, mock_u): """ test: email does not already exist in database. """ mock_u.query.filter_by.return_value.first.return_value = None self.assertIsNone(Validator.validate_email("*****@*****.**"))
def test_validate_username_true(self, mock_u): """ test: username does not already exist in database. """ mock_u.query.filter_by.return_value.first.return_value = None self.assertIsNone(Validator.validate_username("testuserunkown"))