def delete_user(identifier: str): """ Delete a user. Args: identifier (str): The uuid of the user to modify. Returns: flask.Response: Response code. """ if not has_permission('USER_MANAGEMENT'): flask.abort(403) try: user_uuid = utils.str_to_uuid(identifier) except ValueError: flask.abort(status=404) if not flask.g.db['users'].find_one({'_id': user_uuid}): flask.abort(status=404) result = flask.g.db['users'].delete_one({'_id': user_uuid}) if not result.acknowledged: flask.current_app.logger.error('User deletion failed: %s', user_uuid) flask.Response(status=500) else: utils.make_log('user', 'delete', 'User delete', {'_id': user_uuid}) return flask.Response(status=200)
def train(args, rnn, train_loader, test_loader): global num_epochs, learning_rate optimizer = optim.Adam(rnn.parameters(), lr=learning_rate) # Beginning of main training loop for epoch in tqdm(range(num_epochs)): # Loss over entire dataset for this epoch epoch_loss = 0. for batch_idx, data in enumerate(train_loader): # Get loss optimizer.zero_grad() loss = rnn.loss(data) epoch_loss += loss # Perform update loss.backward() optimizer.step() # Log summaries and save model every 50 epochs if epoch % 50 == 0: ut.save_model(rnn, epoch, args.checkpoint_dir) test_loss = test(rnn, test_loader) ut.make_log(epoch_loss, test_loss, epoch, args.log_dir) print("Train loss for epoch " + str(epoch) + ": " + str(epoch_loss))
def update_current_user_info(): """ Update the information about the current user. Returns: flask.Response: Response code. """ user_data = flask.g.current_user try: indata = flask.json.loads(flask.request.data) except json.decoder.JSONDecodeError: flask.abort(status=400) validation = utils.basic_check_indata( indata, user_data, ('_id', 'api_key', 'api_salt', 'auth_ids', 'email', 'permissions')) if not validation[0]: flask.abort(status=validation[1]) user_data.update(indata) result = flask.g.db['users'].update_one({'_id': user_data['_id']}, {'$set': user_data}) if not result.acknowledged: flask.current_app.logger.error('User self-update failed: %s', indata) flask.Response(status=500) else: utils.make_log('user', 'edit', 'User self-updated', user_data) return flask.Response(status=200)
def gen_new_api_key(identifier: str = None): """ Generate a new API key for the provided or current user. Args: identifier (str): The user identifier. Returns: flask.Response: The new API key """ if identifier != flask.g.current_user["_id"]: perm_status = utils.req_check_permissions(["USER_MANAGEMENT"]) if perm_status != 200: flask.abort(status=perm_status) user_data = utils.req_get_entry("users", identifier) if not user_data: flask.abort(status=404) apikey = utils.gen_api_key() new_hash = utils.gen_api_key_hash(apikey.key, apikey.salt) new_values = {"api_key": new_hash, "api_salt": apikey.salt} user_data.update(new_values) result = flask.g.db["users"].update_one({"_id": identifier}, {"$set": new_values}) if not result.acknowledged: flask.current_app.logger.error("Updating API key for user %s failed", identifier) flask.Response(status=500) else: utils.make_log("user", "edit", "New API key", user_data) return utils.response_json({"key": apikey.key})
def add_new_user(user_info: dict): """ Add a new user to the database from first oidc login. First check if user with the same email exists. If so, add the auth_id to the user. Args: user_info (dict): Information about the user """ db_user = flask.g.db['users'].find_one({'email': user_info['email']}) if db_user: db_user['auth_ids'].append(user_info['auth_id']) result = flask.g.db['users'].update_one( {'email': user_info['email']}, {'$set': { 'auth_ids': db_user['auth_ids'] }}) if not result.acknowledged: flask.current_app.logger.error( 'Failed to add new auth_id to user with email %s', user_info['email']) flask.Response(status=500) else: utils.make_log('user', 'edit', 'Add OIDC entry to auth_ids', db_user, no_user=True) else: new_user = structure.user() new_user['email'] = user_info['email'] new_user['name'] = user_info['name'] new_user['auth_ids'] = [user_info['auth_id']] result = flask.g.db['users'].insert_one(new_user) if not result.acknowledged: flask.current_app.logger.error( 'Failed to add user with email %s via oidc', user_info['email']) flask.Response(status=500) else: utils.make_log('user', 'add', 'Creating new user from OAuth', new_user, no_user=True)
def add_new_user(user_info: dict): """ Add a new user to the database from first oidc login. First check if user with the same email exists. If so, add the auth_id to the user. Args: user_info (dict): Information about the user """ db_user = flask.g.db["users"].find_one({"email": user_info["email"]}) if db_user: db_user["auth_ids"].append(user_info["auth_id"]) result = flask.g.db["users"].update_one( {"email": user_info["email"]}, {"$set": { "auth_ids": db_user["auth_ids"] }}) if not result.acknowledged: flask.current_app.logger.error( "Failed to add new auth_id to user with email %s", user_info["email"]) flask.Response(status=500) else: utils.make_log("user", "edit", "Add OIDC entry to auth_ids", db_user, no_user=True) else: new_user = structure.user() new_user["email"] = user_info["email"] new_user["name"] = user_info["name"] new_user["auth_ids"] = [user_info["auth_id"]] result = flask.g.db["users"].insert_one(new_user) if not result.acknowledged: flask.current_app.logger.error( "Failed to add user with email %s via oidc", user_info["email"]) flask.Response(status=500) else: utils.make_log("user", "add", "Creating new user from OAuth", new_user, no_user=True)
def add_user(): """ Add a user. Returns: flask.Response: Information about the user as json. """ if not has_permission('USER_ADD'): flask.abort(403) new_user = structure.user() try: indata = flask.json.loads(flask.request.data) except json.decoder.JSONDecodeError: flask.abort(status=400) validation = utils.basic_check_indata( indata, new_user, ('_id', 'api_key', 'api_salt', 'auth_ids')) if not validation.result: flask.abort(status=validation.status) if 'email' not in indata: flask.current_app.logger.debug('Email must be set') flask.abort(status=400) old_user = flask.g.db['users'].find_one({'email': indata['email']}) if old_user: flask.current_app.logger.debug('User already exists') flask.abort(status=400) if not has_permission('USER_MANAGEMENT') and 'permissions' in indata: flask.current_app.logger.debug( 'USER_MANAGEMENT required for permissions') flask.abort(403) new_user.update(indata) new_user['auth_ids'] = [f'{new_user["_id"]}::local'] result = flask.g.db['users'].insert_one(new_user) if not result.acknowledged: flask.current_app.logger.error('User Addition failed: %s', new_user['email']) flask.Response(status=500) else: utils.make_log('user', 'add', 'User added by admin', new_user) return utils.response_json({'_id': result.inserted_id})
self.server = None self.log = log def __enter__(self): self.log("Starting proxy server.") self.server = subprocess.Popen(['python', 'server.py']) def __exit__(self, type, value, traceback): self.log("Terminating proxy server.") if self.server: self.server.terminate() self.server = None if __name__ == '__main__': utils.log_banner("EXECUTE") log = utils.make_log('EXECUTE') with AutoSpawnServer(log): log("Running each benchmark for each config...") benchmarks = [benchmarks.get(name) for name in options.benchmarks] for benchmark in benchmarks: try: log("now trying to run benchmark %s..." % benchmark.suite) except: pass for engine_path in engines: info = engineInfo.read_info_file(engine_path) executor = executors.make_executor(info)
if not (user_data := flask.g.db['users'].find_one({'_id': user_uuid})): # pylint: disable=superfluous-parens flask.abort(status=404) apikey = utils.gen_api_key() new_hash = utils.gen_api_key_hash(apikey.key, apikey.salt) new_values = {'api_key': new_hash, 'api_salt': apikey.salt} user_data.update(new_values) result = flask.g.db['users'].update_one({'_id': user_data['_id']}, {'$set': new_values}) if not result.acknowledged: flask.current_app.logger.error('Updating API key for user %s failed', user_data['_id']) flask.Response(status=500) else: utils.make_log('user', 'edit', 'New API key', user_data) return utils.response_json({'key': apikey.key}) @blueprint.route('/<identifier>/', methods=['GET']) @login_required def get_user_data(identifier: str): """ Get information about a user. Args: identifier (str): The uuid of the user. Returns: flask.Response: Information about the user as json.
self.log = log def __enter__(self): self.log("Starting proxy server.") self.server = subprocess.Popen(['python', 'server.py']) def __exit__(self, type, value, traceback): self.log("Terminating proxy server.") if self.server: self.server.terminate() self.server = None if __name__ == '__main__': utils.log_banner("EXECUTE") log = utils.make_log('EXECUTE') with AutoSpawnServer(log): log("Running each benchmark for each config...") benchmarks = [benchmarks.get(name) for name in options.benchmarks] for benchmark in benchmarks: try: log("now trying to run benchmark %s..." % benchmark.suite) except: pass for engine_path in engines: info = engineInfo.read_info_file(engine_path) executor = executors.make_executor(info)