def create_new(self, cancel=False, **data): """ Create new user with data submitted from UI. """ if cancel: raise cherrypy.HTTPRedirect('/user/usermanagement') template_specification = dict(mainContent="create_new", title="Create New", data=data) redirect = False if cherrypy.request.method == 'POST': try: data[KEY_COMMENT] = "Created by administrator." # User is created by administrator, should be validated automatically, and credentials # should be sent to user by email. email_msg = """A TVB account was just created for you by an administrator. Your credentials are username=%s, password=%s.""" % ( data[KEY_USERNAME], data[KEY_PASSWORD]) self._create_user(email_msg=email_msg, validated=True, **data) basecontroller.set_info_message( "New user created successfully.") redirect = True except formencode.Invalid, excep: template_specification[ basecontroller.KEY_ERRORS] = excep.unpack_errors() except Exception, excep: self.logger.exceptrion(excep) basecontroller.set_error_message( "We are very sorry, but we could not create your " + "user. Most probably is because it was impossible" + " to sent emails. Please try again later...")
def settings(self, save_settings=False, **data): """Main settings page submit and get""" template_specification = dict( mainContent="../settings/system_settings", title="System Settings") if save_settings: try: form = SettingsForm() data = form.to_python(data) isrestart, isreset = self.settingsservice.save_settings(**data) if isrestart: thread = threading.Thread(target=self._restart_services, kwargs={'should_reset': isreset}) thread.start() bc.add2session(bc.KEY_IS_RESTART, True) bc.set_info_message( 'Please wait until TVB is restarted properly!') raise cherrypy.HTTPRedirect('/tvb') # Here we will leave the same settings page to be displayed. # It will continue reloading when CherryPy restarts. except formencode.Invalid, excep: template_specification[bc.KEY_ERRORS] = excep.unpack_errors() except InvalidSettingsException, excep: self.logger.error( 'Invalid settings! Exception %s was raised' % (str(excep))) bc.set_error_message(excep.message)
def recoverpassword(self, cancel=False, **data): """ This form should reset a password for a given userName/email and send a notification message to that email. """ template_specification = dict(mainContent="recover_password", title="Recover password", data=data) redirect = False if cherrypy.request.method == 'POST': if cancel: raise cherrypy.HTTPRedirect('/user') form = RecoveryForm() try: data = form.to_python(data) okmessage = self.user_service.reset_password(**data) basecontroller.set_info_message(okmessage) redirect = True except formencode.Invalid, excep: template_specification[ basecontroller.KEY_ERRORS] = excep.unpack_errors() redirect = False except UsernameException, excep1: self.logger.error("Could not reset password!") self.logger.exception(excep1) basecontroller.set_error_message(excep1.message) redirect = False
def invokeadaptermethod(self, adapter_id, method_name, **data): """ Public web method, to be used when invoking specific methods from external Adapters/Algorithms. """ algo_group = self.flow_service.get_algo_group_by_identifier(adapter_id) try: adapter_instance = self.flow_service.build_adapter_instance( algo_group) result = self.flow_service.fire_operation( adapter_instance, base.get_logged_user(), base.get_current_project().id, method_name, **data) base.set_info_message("Submit OK!") if isinstance(adapter_instance, ABCDisplayer) and isinstance( result, dict): base.remove_from_session(base.KEY_MESSAGE) result[ABCDisplayer.KEY_IS_ADAPTER] = True result[base.KEY_DISPLAY_MENU] = True result[base.KEY_OPERATION_ID] = adapter_instance.operation_id result[base.KEY_ADAPTER] = adapter_id if KEY_CONTROLLS not in result: result[KEY_CONTROLLS] = None return self.fill_default_attributes(result, algo_group) except OperationException, excep: base.set_warning_message('Problem when submitting data!') self.logger.error( "Invalid method, or wrong parameters when invoking external method on post!" ) self.logger.exception(excep)
def register(self, cancel=False, **data): """ This register form send an e-mail to the user and to the site admin. """ template_specification = dict(mainContent="register", title="Register", data=data) redirect = False if cherrypy.request.method == 'POST': if cancel: raise cherrypy.HTTPRedirect('/user') try: okmessage = self._create_user(**data) basecontroller.set_info_message(okmessage) redirect = True except formencode.Invalid, excep: template_specification[ basecontroller.KEY_ERRORS] = excep.unpack_errors() redirect = False except Exception, excep1: self.logger.error("Could not create user:"******"username"]) self.logger.exception(excep1) basecontroller.set_error_message( "We are very sorry, but we could not create your " + "user. Most probably is because it was impossible" + " to sent emails. Please try again later...") redirect = False
def index(self, **data): """ Login page (with or without messages). """ template_specification = dict(mainContent="login", title="Login", data=data) if cherrypy.request.method == 'POST': form = LoginForm() try: data = form.to_python(data) username = data[KEY_USERNAME] password = data[KEY_PASSWORD] user = self.user_service.check_login(username, password) if user is not None: basecontroller.add2session(basecontroller.KEY_USER, user) basecontroller.set_info_message('Welcome ' + username) self.logger.debug("User " + username + " has just logged in!") if user.selected_project is not None: prj = user.selected_project prj = ProjectService().find_project(prj) self._mark_selected(prj) raise cherrypy.HTTPRedirect('/user/profile') else: basecontroller.set_error_message( 'Wrong username/password, or user not yet validated...' ) self.logger.debug("Wrong username " + username + " !!!") except formencode.Invalid, excep: template_specification[ basecontroller.KEY_ERRORS] = excep.unpack_errors()
def logout(self): """ Logging out user and clean session """ user = basecontroller.remove_from_session(basecontroller.KEY_USER) if user is not None: self.logger.debug("User " + user.username + " is just logging out!") basecontroller.remove_from_session(basecontroller.KEY_PROJECT) basecontroller.remove_from_session(basecontroller.KEY_BURST_CONFIG) basecontroller.set_info_message( "Thank you for using The Virtual Brain!") raise cherrypy.HTTPRedirect("/user")
def _update_figure(self, figure_id, **data): """ Updates the figure details to the given data. """ try: data = EditPreview().to_python(data) self.figure_service.edit_result_figure(figure_id, **data) base.set_info_message('Figure details updated successfully.') return True except formencode.Invalid, excep: self.logger.debug(excep) base.set_error_message(excep.message) return False
def validate(self, name): """ A link to this page will be sent to the administrator to validate the registration of each user. """ success = self.user_service.validate_user(name) if not success: basecontroller.set_error_message("Problem validating user:"******"!! Please check logs.") self.logger.error("Problem validating user " + name) else: basecontroller.set_info_message( "User Validated successfully and notification email sent!") raise cherrypy.HTTPRedirect('/tvb')
def create_stimulus(self): """ Creates a stimulus from the given data. """ try: context = base.get_from_session(KEY_SURFACE_CONTEXT) surface_stimulus_creator = self.get_creator_and_interface(SURFACE_STIMULUS_CREATOR_MODULE, SURFACE_STIMULUS_CREATOR_CLASS, StimuliSurface())[0] self.flow_service.fire_operation(surface_stimulus_creator, base.get_logged_user(), base.get_current_project().id, **context.equation_kwargs) base.set_info_message("The operation for creating the stimulus was successfully launched.") context.selected_stimulus = None except (NameError, ValueError, SyntaxError), _: base.set_error_message("The operation failed due to invalid parameter input.") return False
def do_step(self, step_idx, from_step=None): """ Go to the step given by :param step_idx. In case the next step is the create one (3), we want to remain on the same step as before so that is handled differently depending on the :param from_step. """ if int(step_idx) == 1: return self.step_1() if int(step_idx) == 2: return self.step_2() if int(step_idx) == 3: if self.create_stimulus(): base.set_info_message("Successfully created a new stimulus.") if from_step == 2: return self.step_2() return self.step_1()
def get_template_from_context(self): """ Return the parameters for the local connectivity in case one is stored in context. Load the entity and use it to populate the defaults from the interface accordingly. """ context = base.get_from_session(KEY_LCONN_CONTEXT) selected_local_conn = ABCAdapter.load_entity_by_gid( context.selected_entity) cutoff = selected_local_conn.cutoff equation = selected_local_conn.equation surface = selected_local_conn.surface default_dict = {'surface': surface.gid, 'cutoff': cutoff} if equation is not None: equation_type = equation.__class__.__name__ default_dict['equation'] = equation_type for param in equation.parameters: prepared_name = 'equation_parameters_option_' + str( equation_type) prepared_name = prepared_name + '_parameters_parameters_' + str( param) default_dict[prepared_name] = equation.parameters[param] else: msg = "There is no equation specified for this local connectivity. " msg += "The default equation is displayed into the spatial field." self.logger.warning(msg) base.set_info_message(msg) default_dict[ DataTypeMetaData.KEY_TAG_1] = selected_local_conn.user_tag_1 input_list = self.get_creator_and_interface(LOCAL_CONN_CREATOR_MODULE, LOCAL_CONN_CREATOR_CLASS, LocalConnectivity(), lock_midpoint_for_eq=[1 ])[1] input_list = self._add_extra_fields_to_interface(input_list) input_list = ABCAdapter.fill_defaults(input_list, default_dict) template_specification = { 'inputList': input_list, base.KEY_PARAMETERS_CONFIG: False, 'equationViewerUrl': '/spatial/localconnectivity/get_equation_chart', 'equationsPrefixes': json.dumps(self.plotted_equations_prefixes) } return template_specification
def create_local_connectivity(self, **kwargs): """ Used for creating and storing a local connectivity. """ context = base.get_from_session(KEY_LCONN_CONTEXT) local_connectivity_creator = self.get_creator_and_interface( LOCAL_CONN_CREATOR_MODULE, LOCAL_CONN_CREATOR_CLASS, LocalConnectivity())[0] self.flow_service.fire_operation(local_connectivity_creator, base.get_logged_user(), base.get_current_project().id, **kwargs) base.set_info_message( "The operation for creating the local connectivity was successfully launched." ) context.reset() return self.step_1()
def create_stimulus(self): """ Creates a stimulus from the given data. """ context = base.get_from_session(KEY_REGION_CONTEXT) local_connectivity_creator = self.get_creator_and_interface( REGION_STIMULUS_CREATOR_MODULE, REGION_STIMULUS_CREATOR_CLASS, StimuliRegion())[0] context.equation_kwargs.update( {'weight': json.dumps(context.get_weights())}) self.flow_service.fire_operation(local_connectivity_creator, base.get_logged_user(), base.get_current_project().id, **context.equation_kwargs) base.set_info_message( "The operation for creating the stimulus was successfully launched." )
def execute_post(self, project_id, submit_url, success_url, step_key, algo_group, method_name=None, **data): """ Execute HTTP POST on a generic step.""" errors = None adapter_instance = self.flow_service.build_adapter_instance(algo_group) try: if method_name is not None: data['method_name'] = method_name result = self.flow_service.fire_operation(adapter_instance, base.get_logged_user(), project_id, **data) # Store input data in session, for informing user of it. step = self.flow_service.get_category_by_id(step_key) if not step.rawinput: self.context.add_adapter_to_session(None, None, copy.deepcopy(data)) if isinstance(adapter_instance, ABCDisplayer): if isinstance(result, dict): result[ base.KEY_OPERATION_ID] = adapter_instance.operation_id return result else: base.set_error_message( "Invalid result returned from Displayer! Dictionary is expected!" ) else: base.set_info_message(str(result)) raise cherrypy.HTTPRedirect(success_url) except formencode.Invalid, excep: errors = excep.unpack_errors()
def profile(self, logout=False, save=False, **data): """ Display current user's profile page. On POST: logout, or save password/email. """ if cherrypy.request.method == 'POST' and logout: raise cherrypy.HTTPRedirect('/user/logout') template_specification = dict(mainContent="profile", title="User Profile") if cherrypy.request.method == 'POST' and save: try: form = EditUserForm() data = form.to_python(data) user = basecontroller.get_logged_user() if KEY_PASSWORD in data and data[KEY_PASSWORD]: user.password = md5(data[KEY_PASSWORD]).hexdigest() if KEY_EMAIL in data and data[KEY_EMAIL]: user.email = data[KEY_EMAIL] old_password = None if 'old_password' in data and data['old_password']: old_password = md5(data['old_password']).hexdigest() self.user_service.edit_user(user, old_password) if old_password: basecontroller.set_info_message("Changes Submitted!") else: basecontroller.set_info_message( "Submitted! No password changed.") except formencode.Invalid, excep: template_specification[ basecontroller.KEY_ERRORS] = excep.unpack_errors() except UsernameException, excep: self.logger.exception(excep) user = basecontroller.get_logged_user() basecontroller.add2session( basecontroller.KEY_USER, self.user_service.get_user_by_id(user.id)) basecontroller.set_error_message( "Could not save changes. Probably wrong old password!!")
def start_dti_pipeline(self, cancel=False, start=False, **data): """ Prepare DTI Pipeline run. """ project_id = basecontroller.get_current_project().id if cherrypy.request.method == 'POST' and cancel: raise cherrypy.HTTPRedirect("/project/editstructure/" + str(project_id)) template_specification = dict( title="Import Connectivity", data=data, section_name='project', subsection_name='pipeline', mainContent="pipeline/get_connectivity", includedResources='project/included_resources') if cherrypy.request.method == 'POST' and start: form = ImportForm() try: data = form.to_python(data) service = DTIPipelineService(data['server_ip'], data['username']) current_project = basecontroller.get_current_project() current_user = basecontroller.get_logged_user() service.fire_pipeline(data['dti_scans'], current_project, current_user, data['threads_number']) okmessage = "Import Started! You will see results after few hours on Data Structure Page!" basecontroller.set_info_message(okmessage) raise cherrypy.HTTPRedirect("/project/editstructure/" + str(project_id)) except formencode.Invalid, excep: basecontroller.set_error_message( "Some parameters are invalid!") template_specification[ basecontroller.KEY_ERRORS] = excep.unpack_errors()
def editresultfigures(self, remove_figure=False, rename_session=False, remove_session=False, **data): """ This method knows how to handle the following actions: remove figure, update figure, remove session and update session. """ project = base.get_current_project() user = base.get_logged_user() redirect_url = '/project/figure/displayresultfigures' if "selected_session" in data and data[ "selected_session"] is not None and len( data["selected_session"]): redirect_url += '/' + data["selected_session"] del data["selected_session"] figure_id = None if "figure_id" in data: figure_id = data["figure_id"] del data["figure_id"] if cherrypy.request.method == 'POST' and rename_session: successfully_updated = True if "old_session_name" in data and "new_session_name" in data: figures_dict, _ = self.figure_service.retrieve_result_figures( project, user, data["old_session_name"]) for _key, value in figures_dict.iteritems(): for figure in value: new_data = { "name": figure.name, "session_name": data["new_session_name"] } success = self._update_figure(figure.id, **new_data) if not success: successfully_updated = False if successfully_updated: base.set_info_message( "The session was successfully updated!") else: base.set_error_message( "The session was not successfully updated! " "There could be some figures that still refer to the old session." ) elif cherrypy.request.method == 'POST' and remove_session: successfully_removed = True if "old_session_name" in data: figures_dict, _ = self.figure_service.retrieve_result_figures( project, user, data["old_session_name"]) for _key, value in figures_dict.iteritems(): for figure in value: success = self.figure_service.remove_result_figure( figure.id) if not success: successfully_removed = False if successfully_removed: base.set_info_message( "The session was removed successfully!") else: base.set_error_message( "The session was not entirely removed!") elif cherrypy.request.method == 'POST' and remove_figure and figure_id is not None: success = self.figure_service.remove_result_figure(figure_id) if success: base.set_info_message("Figure removed successfully!") else: base.set_error_message("Figure could not be removed!") elif figure_id is not None: self._update_figure(figure_id, **data) raise cherrypy.HTTPRedirect(redirect_url)