def test_random_response(): api.add_user(USER1_UID, USER1_NAME) exercise_json = api.get_exercise(USER1_UID) eid = exercise_json['eid'] #exercise = exercise_json['exercise'] random_response_json = api.get_random_response(eid, USER1_UID) print("Random response:\n{}".format(json.dumps(random_response_json, indent=3)))
def reactToAMQPMessage(message, send_back): """ React to given (AMQP) message. `message` is expected to be :py:func:`collections.namedtuple` structure from :mod:`.structures` filled with all necessary data. Args: message (object): One of the request objects defined in :mod:`.structures`. send_back (fn reference): Reference to function for responding. This is useful for progress monitoring for example. Function takes one parameter, which may be response structure/namedtuple, or string or whatever would be normally returned. Returns: object: Response class from :mod:`structures`. Raises: ValueError: if bad type of `message` structure is given. """ if _instanceof(message, structures.AddUser): api.add_user( username=message.username, password=message.password ) return True elif _instanceof(message, structures.RemoveUser): api.remove_user(message.username) return True elif _instanceof(message, structures.ChangePassword): api.change_password( username=message.username, new_password=message.new_password ) return True elif _instanceof(message, structures.ListRegisteredUsers): return structures.Userlist(api.list_users()) elif _instanceof(message, structures.SetUserSettings): username = message.username # convert namedtuple to dict (python rocks) conf_dict = dict(message._asdict()) del conf_dict["username"] passwd_reader.save_user_config( username, conf_dict ) conf_dict = passwd_reader.read_user_config(username) conf_dict["username"] = username return structures.UserSettings(**conf_dict) elif _instanceof(message, structures.GetUserSettings): conf_dict = passwd_reader.read_user_config(message.username) conf_dict["username"] = message.username return structures.UserSettings(**conf_dict) raise ValueError( "Unknown type of request: '" + str(type(message)) + "'!" )
def test_valid_answer(): api.add_user(USER1_UID, USER1_NAME) valid_answer = EID_1_VALID_ANSWERS[0] json_response = api.store_response(EID_1, USER1_UID, valid_answer) assert json_response["points"] > 0, '{} <=0 {}'.format(json_response["points"], 0) json_response = api.store_response(EID_1, USER1_UID, valid_answer) assert_equality(json_response["points"], 0)
def adduser(): if request.method == "GET": return render_template("adduser.html") if request.method == "POST": name = request.form['username'] name_cn = request.form['username_cn'] passwd = request.form['password'] re_passwd = request.form['re_password'] email = request.form['email'] mobile = request.form['mobile'] role = request.form['role'] statu = request.form['statu'] uesr_list = get_userlist(["name"]) if len(name) == 0 or len(name_cn) == 0 or len(passwd) == 0 or len( email) == 0 or len(mobile) == 0: msg = u"输入框不能为空" return render_template("adduser.html", msg=msg) if name in map(lambda x: x["name"], uesr_list): msg = u"用户已存在" return render_template("adduser.html", msg=msg) if passwd != re_passwd: msg = u"2次输入密码不同" return render_template("adduser.html", msg=msg) userinfo = [name, name_cn, passwd, email, mobile, role, statu] add_user(userinfo) return redirect("/")
def test_random_answers(): api.add_user(USER1_UID, USER1_NAME) new_answer = random_string_generator(15) json_response = api.store_response(EID_1, USER1_UID, new_answer) assert_equality(json_response["userid"], USER1_UID) assert_equality(int(json_response["eid"]), EID_1) assert_equality(json_response["response"], new_answer) assert_equality(json_response["points"], None)
def add_user(): username = request.get_cookie("username", settings.cookie_secret) password = request.get_cookie("password", settings.cookie_secret) ok = api.check(username, password) if ok: username = request.params.get("username") password = request.params.get("password") api.add_user(username, password) redirect("/start?message=ok") redirect("/start?message=permission+denied")
def add_user(): try: user_id = flask.request.headers['UserID'] first_name = flask.request.headers['FirstName'] last_name = flask.request.headers['LastName'] api.add_user(user_id, first_name, last_name) return '', 200, API_RESPONSE_HEADER except (ValueError, KeyError) as input_error: return server._generate_error_response(input_error), 400, API_RESPONSE_HEADER except Exception as exception: return server._generate_error_response(exception), 500, API_RESPONSE_HEADER
def test_notifications(): api.add_user(USER1_UID, USER1_NAME) response_json = api.get_user_info(USER1_UID) print(json.dumps(response_json, indent=3)) api.add_user(USER2_UID, USER2_NAME) response_json = api.get_user_info(USER2_UID) print(json.dumps(response_json, indent=3)) new_agreed_answer = "new agreed answer" print("Agreed answer: {}\n".format(new_agreed_answer)) api.store_response(EID_1, USER1_UID, new_agreed_answer) api.store_response(EID_1, USER2_UID, new_agreed_answer) api.store_response(EID_1, USER1_UID, random_string_generator(15)) api.store_response(EID_1, USER1_UID, random_string_generator(15)) api.store_response(EID_1, USER1_UID, random_string_generator(15)) api.store_response(EID_1, USER1_UID, random_string_generator(15))
def add_new(): form = UserForm(request.form) if request.method == "POST" and form.validate(): if mongo_init().users.find_one({"email": form.data.get("email")}): flash("User with email {} already exist".format( form.data.get("email")), "alert-error") return render_template("add_new.html", form=form) user = add_user(**form.data) history = { "registrationid": user["registrationid"], "passed_by": None, "cancelled_by": None, "created_by": g.user["username"], "when": datetime.datetime.now(), "query": None} mongo_init().history.insert(history) flash(u"User {name} ({email}) successfully registered".format( **user)) return redirect("{}?query={}".format( url_for("registration_deck"), user["registrationid"] )) return render_template( "add_new.html", form=form)
def add_new(): form = UserForm(request.form) if request.method == "POST" and form.validate(): if mongo_init().users.find_one({"email": form.data.get("email")}): flash( "User with email {} already exist".format( form.data.get("email")), "alert-error") return render_template("add_new.html", form=form) user = add_user(**form.data) history = { "registrationid": user["registrationid"], "passed_by": None, "cancelled_by": None, "created_by": g.user["username"], "when": datetime.datetime.now(), "query": None } mongo_init().history.insert(history) flash(u"User {name} ({email}) successfully registered".format(**user)) return redirect("{}?query={}".format(url_for("registration_deck"), user["registrationid"])) return render_template("add_new.html", form=form)
def deal_with_request(request_json): # retrieve the message in JSON and then transform it to Telegram object update_obj = telegram.Update.de_json(request_json, BOT) # if update_obj.callback_query: # deal_with_callback_query(update_obj.callback_query) # return message_obj = update_obj.message user_obj = message_obj.from_user chat_id = user_obj.id username = user_obj.username last_name = user_obj.last_name if user_obj.last_name else '' name = (user_obj.first_name + ' ' + last_name).strip() # language = user_obj.language_code p = ndb_person.get_person_by_id(user_obj.id) user_name = 'telegram_{}'.format(chat_id) if not api.is_user_registered(user_name): api.add_user(user_name, name) if p == None: p = ndb_person.add_person(chat_id, name, last_name, username) tell_admin('New user: {}'.format(p.get_name_last_name_username())) else: p.update_user(name, last_name, username) if message_obj.forward_from and not p.is_manager(): send_message(p, p.bot_ux().MSG_NO_FORWARDING_ALLOWED) return text = message_obj.text if text: text_input = message_obj.text logging.debug('Message from @{} in state {} with text {}'.format(chat_id, p.state, text_input)) if WORK_IN_PROGRESS and not p.is_manager(): send_message(p, p.bot_ux().MSG_WORK_IN_PROGRESS) return if deal_with_admin_commands(p, message_obj): return if deal_with_universal_command(p, message_obj): return if deal_with_manager_commands(p, message_obj): return logging.debug("Sending {} to state {} with input message_obj {}".format(p.get_name_last_name_username(), p.state, message_obj)) repeat_state(p, message_obj=message_obj)
def test_user_info(): response_json = api.get_user_info('invalid_user') print(json.dumps(response_json, indent=3)) assert len(response_json)==0 response_json = api.add_user(USER1_UID, USER1_NAME) print("Add user response:\n{}".format(json.dumps(response_json, indent=3))) response_json = api.get_user_info(USER1_UID) print(json.dumps(response_json, indent=3)) assert len(response_json)>0
def test_add_user_and_try_to_fetch_non_existing_user(self): res = self.loop.run_until_complete(api.add_user( "Pera", "Peric", 70000)) self.assertTrue('id' in res) id_user = '******' self.assertEqual({ 'status': 'error', 'message': 'not-found' }, self.loop.run_until_complete(api.get_user_by_id(id_user)))
def test_add_user_and_fetch_user_by_id(self): res = self.loop.run_until_complete(api.add_user( "Pera", "Peric", 70000)) self.assertTrue('id' in res) id_user = res['id'] self.assertEqual( { "balance": 70000.0, "first_name": "Pera", "last_name": "Peric" }, self.loop.run_until_complete(api.get_user_by_id(id_user)))
def register_handler(self): username = self.username.text() password = self.password.text() r = api.add_user(username, password) print(r, r.content) if api.check_status('POST', r): print('registerd successfuly.') QMessageBox.about(self, 'Add User', 'User added successfuly.') else: # some problem occured in user adding self.error_message.setText(str(r))
def test_api(): # Create self user api.add_user() # create foo group for self api.create_group('foo') # create someone else's user api.add_user('*****@*****.**') # add someone else to self's group api.add_member_to_group('foo') # delete them from the group api.delete_member_from_group('foo', '*****@*****.**') # make them an admin api.add_admin_to_group('foo', '*****@*****.**') with pytest.raises(Exception) as e_info: api.create_group('foo') with pytest.raises(Exception) as e_info: api.add_user('*****@*****.**') # Delete doesn't fail if that group isn't in that record api.delete_member_from_group('foo', '*****@*****.**') # the auth'd user can only see their own record assert len(api._get('permissions/')['_items']) == 1
def add_user(self): username = self.new_user_ui.username.text() password = self.new_user_ui.password.text() pass_conf = self.new_user_ui.password_confirm.text() if password == pass_conf: r = api.add_user(username, password) if api.check_status('POST', r): self.error_message.setStyleSheet('color: #00ff00') self.error_message.setText(f'{r.status_code} User Successfuly Added.') self.new_user_ui.username.setText('') self.new_user_ui.password.setText('') self.new_user_ui.password_confirm.setText('') else: self.error_message.setText(str(r)) else: self.error_message.setText('Wrong password!')
def test_add_user_and_trosak_try_to_get_trosak(self): res = self.loop.run_until_complete( (api.add_user("Predrag", "Trajkovic", 8000))) self.assertTrue('id' in res) id_user = res['id'] self.assertEqual( { 'balance': 8000.0, "first_name": "Predrag", "last_name": "Trajkovic" }, self.loop.run_until_complete(api.get_user_by_id(id_user))) spenses = [{ 'name': 'Krompir', 'price': 300 }, { 'name': 'Paprika', 'price': 100 }, { 'name': 'Zena', 'price': 500 }] id_user_nepostojeci = '00000000-0000-0000-0000-000000000001' self.assertEqual({'status': 'ok'}, self.loop.run_until_complete( api.add_spenses_for_user(id_user, spenses))) self.assertEqual({'message': 'not-found', 'status': 'error'}, self.loop.run_until_complete(api.add_spenses_for_user(id_user_nepostojeci, spenses)))\ self.assertEqual( { 'balance': 5000.0, "first_name": "Pera", "last_name": "Peric" }, self.loop.run_until_complete(api.get_user_by_id(id_user)))
def test_add_user_invalid_id(self, mock_user): with self.assertRaises(ValueError): api.add_user('user', 'foo', 'bar')
def test_add_user_id_already_exists(self, mock_user): with self.assertRaises(ValueError): api.add_user('exists', 'foo', 'bar')
def sync(): logging.info(config_file.keys()) ldap_connector = ldap.initialize(f"{config_file['HostName']}") ldap_connector.set_option(ldap.OPT_REFERRALS, 0) ldap_connector.simple_bind_s(config_file['BindUser'], config_file['BindPassword']) ldap_results = ldap_connector.search_s( config_file['BaseDN'], ldap.SCOPE_SUBTREE, '(objectClass=gosaMailAccount)', [ config_file['Username'], config_file['Fullname'], config_file['Active User'] ]) logging.info(ldap_results) ldap_results = map( lambda x: (x[1][config_file['Username']][0].decode(), x[1][config_file[ 'Fullname']][0].decode(), False if int(x[1][config_file[ 'Active User']][0].decode()) & 0b10 else True), ldap_results) filedb.session_time = datetime.datetime.now() for (email, ldap_name, ldap_active) in ldap_results: (db_user_exists, db_user_active) = filedb.check_user(email) (api_user_exists, api_user_active, api_name) = api.check_user(email) unchanged = True if not db_user_exists: filedb.add_user(email, ldap_active) (db_user_exists, db_user_active) = (True, ldap_active) logging.info(f"Added filedb user: {email} (Active: {ldap_active})") unchanged = False if not api_user_exists: api.add_user(email, ldap_name, ldap_active) (api_user_exists, api_user_active, api_name) = (True, ldap_active, ldap_name) logging.info( f"Added Mailcow user: {email} (Active: {ldap_active})") unchanged = False if db_user_active != ldap_active: filedb.user_set_active_to(email, ldap_active) logging.info( f"{'Activated' if ldap_active else 'Deactived'} {email} in filedb" ) unchanged = False if api_user_active != ldap_active: api.edit_user(email, active=ldap_active) logging.info( f"{'Activated' if ldap_active else 'Deactived'} {email} in Mailcow" ) unchanged = False if api_name != ldap_name: api.edit_user(email, name=ldap_name) logging.info(f"Changed name of {email} in Mailcow to {ldap_name}") unchanged = False if unchanged: logging.info(f"Checked user {email}, unchanged") for email in filedb.get_unchecked_active_users(): (api_user_exists, api_user_active, _) = api.check_user(email) if (api_user_active and api_user_active): api.edit_user(email, active=False) logging.info( f"Deactivated user {email} in Mailcow, not found in LDAP") filedb.user_set_active_to(email, False) logging.info(f"Deactivated user {email} in filedb, not found in LDAP")
def sync(): ldap_connector = ldap.initialize(f"{config['LDAP_URI']}") ldap_connector.set_option(ldap.OPT_REFERRALS, 0) ldap_connector.simple_bind_s(config['LDAP_BIND_DN'], config['LDAP_BIND_DN_PASSWORD']) ldap_results = ldap_connector.search_s( config['LDAP_BASE_DN'], ldap.SCOPE_SUBTREE, config['LDAP_FILTER'], [config['USER_ATTR'], 'cn', 'userAccountControl']) ldap_results = map( lambda x: (x[1][config['USER_ATTR']][0].decode(), x[1]['cn'][0].decode(), False if int(x[1]['userAccountControl'][0].decode()) & 0b10 else True), ldap_results) filedb.session_time = datetime.datetime.now() if 'REPLACE_DOMAIN' in config: replaceDomain = config['REPLACE_DOMAIN'] else: replaceDomain = None for (email, ldap_name, ldap_active) in ldap_results: (db_user_exists, db_user_active) = filedb.check_user(email) (api_user_exists, api_user_active, api_name) = api.check_user(email, replaceDomain) unchanged = True if not db_user_exists: filedb.add_user(email, ldap_active) (db_user_exists, db_user_active) = (True, ldap_active) logging.info(f"Added filedb user: {email} (Active: {ldap_active})") unchanged = False if not api_user_exists: api.add_user(email, ldap_name, ldap_active, replaceDomain) (api_user_exists, api_user_active, api_name) = (True, ldap_active, ldap_name) logging.info( f"Added Mailcow user: {email} (Active: {ldap_active})") unchanged = False if db_user_active != ldap_active: filedb.user_set_active_to(email, ldap_active) logging.info( f"{'Activated' if ldap_active else 'Deactived'} {email} in filedb" ) unchanged = False if api_user_active != ldap_active: api.edit_user(email, replaceDomain, active=ldap_active) logging.info( f"{'Activated' if ldap_active else 'Deactived'} {email} in Mailcow" ) unchanged = False if api_name != ldap_name: api.edit_user(email, replaceDomain, name=ldap_name) logging.info(f"Changed name of {email} in Mailcow to {ldap_name}") unchanged = False if unchanged: logging.info(f"Checked user {email}, unchanged") for email in filedb.get_unchecked_active_users(): (api_user_exists, api_user_active, _) = api.check_user(email, replaceDomain) if (api_user_active and api_user_active): api.edit_user(email, replaceDomain, active=False) logging.info( f"Deactivated user {email} in Mailcow, not found in LDAP") filedb.user_set_active_to(email, False) logging.info(f"Deactivated user {email} in filedb, not found in LDAP")
def sync(): ldap_connector = ldap.initialize(f"{config['LDAP_HOST']}") ldap_connector.set_option(ldap.OPT_REFERRALS, 0) ldap_connector.simple_bind_s(config['LDAP_BIND_DN'], config['LDAP_BIND_DN_PASSWORD']) #ldap_results = ldap_connector.search_s(config['LDAP_BASE_DN'], ldap.SCOPE_SUBTREE, # '(&(objectClass=user)(objectCategory=person))', # ['userPrincipalName', 'cn', 'userAccountControl']) ldap_results = ldap_connector.search_s( config['LDAP_BASE_DN'], ldap.SCOPE_SUBTREE, config['LDAP_FILTER'], [config['LDAP_FIELDS_MAIL'], config['LDAP_FIELDS_NAME'], 'True']) ldap_results = map( lambda x: ( [i.decode() for i in x[1][config['LDAP_FIELDS_MAIL']]], x[1][config['LDAP_FIELDS_NAME']][0].decode(), #False if int(x[1]['userAccountControl'][0].decode()) & 0b10 else True), ldap_results) True), ldap_results) filedb.session_time = datetime.datetime.now() for (ldap_email, ldap_name, ldap_active) in ldap_results: for email in ldap_email: if email.split('@')[1] not in config['EMAIL_DOMAINS']: continue (db_user_exists, db_user_active) = filedb.check_user(email) (api_user_exists, api_user_active, api_name) = api.check_user(email) unchanged = True if not db_user_exists: filedb.add_user(email, ldap_active) (db_user_exists, db_user_active) = (True, ldap_active) logging.info( f"Added filedb user: {email} (Active: {ldap_active})") unchanged = False if not api_user_exists: api.add_user(email, ldap_name, ldap_active) (api_user_exists, api_user_active, api_name) = (True, ldap_active, ldap_name) logging.info( f"Added Mailcow user: {email} (Active: {ldap_active})") unchanged = False if db_user_active != ldap_active: filedb.user_set_active_to(email, ldap_active) logging.info( f"{'Activated' if ldap_active else 'Deactived'} {email} in filedb" ) unchanged = False if api_user_active != ldap_active: api.edit_user(email, active=ldap_active) logging.info( f"{'Activated' if ldap_active else 'Deactived'} {email} in Mailcow" ) unchanged = False if api_name != ldap_name: api.edit_user(email, name=ldap_name) logging.info( f"Changed name of {email} in Mailcow to {ldap_name}") unchanged = False if unchanged: logging.info(f"Checked user {email}, unchanged") for email in filedb.get_unchecked_active_users(): (api_user_exists, api_user_active, _) = api.check_user(email) if (api_user_active and api_user_active): api.edit_user(email, active=False) logging.info( f"Deactivated user {email} in Mailcow, not found in LDAP") filedb.user_set_active_to(email, False) logging.info(f"Deactivated user {email} in filedb, not found in LDAP")
#! /usr/bin/env python import api import sys try: username = sys.argv[1] except IndexError: print "Usage: ./useradd foo bar" try: password = sys.argv[2] except IndexError: password = None print api.add_user(username, password)
def test_add_user_invalid_name(self, mock_user): with self.assertRaises(ValueError): api.add_user('useruser', '', '')
def test_add_user_and_a_few_spenes(self): res = self.loop.run_until_complete(api.add_user("Pera", "Peric", 5000)) self.assertTrue('id' in res) id_user = res['id'] self.assertEqual( { 'balance': 5000.0, "first_name": "Pera", "last_name": "Peric" }, self.loop.run_until_complete(api.get_user_by_id(id_user))) extra_spenses = [{ 'name': 'struja', 'price': 300 }, { 'name': 'voda', 'price': 100 }, { 'name': 'kurve', 'price': 4500 }, { 'name': 'grejanje', 'price': 500 }] spenses = [{ 'name': 'struja', 'price': 300 }, { 'name': 'voda', 'price': 100 }, { 'name': 'grejanje', 'price': 500 }] self.assertEqual({'status': 'ok'}, self.loop.run_until_complete( api.add_spenses_for_user(id_user, spenses))) self.assertEqual( { 'status': 'ok', 'spenses': [{ 'name': 'struja', 'price': 300.0 }, { 'name': 'voda', 'price': 100.0 }, { 'name': 'grejanje', 'price': 500.0 }] }, self.loop.run_until_complete(api.all_spenses_for_user(id_user))) self.assertEqual( { 'balance': 5000 - 300 - 100 - 500, "first_name": "Pera", "last_name": "Peric" }, self.loop.run_until_complete(api.get_user_by_id(id_user))) with self.assertRaises(NameError): self.loop.run_until_complete( api.add_spenses_for_user(id_user, extra_spenses))
def test_add_user_happy_case(self, mock_user): api.add_user('useruser', 'foo', 'bar')
def test_get_exercise(): api.add_user(USER1_UID, USER1_NAME) exercise_json = api.get_exercise(USER1_UID) #elevel='A1', etype='LocatedAt' print("Exercise response:\n{}".format(json.dumps(exercise_json, indent=3)))
def add_user(): return api.add_user(request.json)
def test_choose_exercise(): api.add_user(USER1_UID, USER1_NAME) response_json = api.choose_exercise(USER1_UID) print("Exercise response:\n{}".format(json.dumps(response_json, indent=3)))
def test_get_close_exercise(): api.add_user(USER1_UID, USER1_NAME) exercise_json = api.get_close_exercise(USER1_UID) #, elevel='A1', etype='RelatedTo' #RelatedTo, LocatedAt print("Exercise response:\n{}".format(json.dumps(exercise_json, indent=3))) store_response_json = api.store_close_response(exercise_json['eid'], USER1_UID, 2) print("Exercise store response:\n{}".format(json.dumps(store_response_json, indent=3)))
def sync(): ldap_connector = ldap.initialize(f"{config['LDAP_URI']}") ldap_connector.set_option(ldap.OPT_REFERRALS, 0) ldap_connector.simple_bind_s(config['LDAP_BIND_DN'], config['LDAP_BIND_DN_PASSWORD']) ldap_results = ldap_connector.search_s( config['LDAP_BASE_DN'], ldap.SCOPE_SUBTREE, config['LDAP_FILTER'], ['mail', 'displayName', 'userAccountControl']) filedb.session_time = datetime.datetime.now() for x in ldap_results: try: logging.info("Working on " + x[1]['sAMAccountName']) email = x[1]['mail'][0].decode() ldap_name = x[1]['displayName'][0].decode() ldap_active = False if int( x[1]['userAccountControl'][0].decode()) & 0b10 else True (db_user_exists, db_user_active) = filedb.check_user(email) (api_user_exists, api_user_active, api_name) = api.check_user(email) unchanged = True if not db_user_exists: filedb.add_user(email, ldap_active) (db_user_exists, db_user_active) = (True, ldap_active) logging.info( f"Added filedb user: {email} (Active: {ldap_active})") unchanged = False if not api_user_exists: api.add_user(email, ldap_name, ldap_active, 256) (api_user_exists, api_user_active, api_name) = (True, ldap_active, ldap_name) logging.info( f"Added Mailcow user: {email} (Active: {ldap_active})") unchanged = False if db_user_active != ldap_active: filedb.user_set_active_to(email, ldap_active) logging.info( f"{'Activated' if ldap_active else 'Deactived'} {email} in filedb" ) unchanged = False if api_user_active != ldap_active: api.edit_user(email, active=ldap_active) logging.info( f"{'Activated' if ldap_active else 'Deactived'} {email} in Mailcow" ) unchanged = False if api_name != ldap_name: api.edit_user(email, name=ldap_name) logging.info( f"Changed name of {email} in Mailcow to {ldap_name}") unchanged = False if unchanged: logging.info(f"Checked user {email}, unchanged") except Exception: logging.info(f"Exception during something. See above") pass for email in filedb.get_unchecked_active_users(): (api_user_exists, api_user_active, _) = api.check_user(email) if (api_user_active and api_user_active): api.edit_user(email, active=False) logging.info( f"Deactivated user {email} in Mailcow, not found in LDAP") filedb.user_set_active_to(email, False) logging.info(f"Deactivated user {email} in filedb, not found in LDAP")