def quit(): """ Stop all tasks and quit Bauble. """ import gtk import bauble.utils as utils from bauble.utils.log import error try: import bauble.task as task except Exception, e: error('bauble.quit(): %s' % utils.utf8(e))
def install(cls, import_defaults=True): import bauble.paths as paths if not import_defaults: return path = os.path.join(paths.lib_dir(), "plugins", "plants", "default") filenames = os.path.join(path, 'family.txt') from bauble.plugins.imex.csv_ import CSVImporter csv = CSVImporter() try: csv.start([filenames], metadata=db.metadata, force=True) except Exception, e: error(e) raise
def set_password(password, user=None): """ Set a user's password. If user is None then change the password of the current user. """ if not user: user = current_user() conn = db.engine.connect() trans = conn.begin() try: stmt = "alter role %s with encrypted password '%s'" % (user, password) conn.execute(stmt) except Exception, e: error('users.set_password(): %s' % utils.utf8(e)) trans.rollback()
def on_insert_menu_item_activate(self, widget, editor_cls): try: view = self.get_view() if isinstance(view, SearchView): expanded_rows = view.get_expanded_rows() editor = editor_cls() committed = editor.start() if committed is not None and isinstance(view, SearchView): view.results_view.collapse_all() view.expand_to_all_refs(expanded_rows) except Exception, e: utils.message_details_dialog(utils.xml_safe(str(e)), traceback.format_exc(), gtk.MESSAGE_ERROR) error('bauble.gui.on_insert_menu_item_activate():\n %s' \ % traceback.format_exc()) return
def _create_role(name, password=None, login=False, admin=False): """ """ conn = db.engine.connect() trans = conn.begin() try: stmt = 'create role %s INHERIT' % name if login: stmt += ' LOGIN' if admin: stmt += ' CREATEROLE' if password: stmt += ' PASSWORD %s' % password conn.execute(stmt) except Exception, e: error('users._create_role(): %s' % utils.utf8(e)) trans.rollback() raise
def create_user(name, password=None, admin=False, groups=None): """ Create a role that can login. """ if groups is None: groups = [] _create_role(name, password, login=True, admin=False) conn = db.engine.connect() trans = conn.begin() try: for group in groups: stmt = 'grant %s to %s;' % (group, name) db.engine.execute(stmt) # allow the new role to connect to the database stmt = 'grant connect on database %s to %s' % \ (bauble.db.engine.url.database, name) #debug(stmt) conn.execute(stmt) except Exception, e: error('users.create_users(): %s' % utils.utf8(e)) trans.rollback() raise
def drop(role, revoke=False): """ Drop a user from the database Arguments: - `role`: - `revoke`: If revoke is True then revoke the users permissions before dropping them """ # TODO: need to revoke all privileges first conn = db.engine.connect() trans = conn.begin() try: if revoke: # if set privilege failes then dropping the role will fail # because the role will still have dependent users set_privilege(role, None) stmt = 'drop role %s;' % role conn.execute(stmt) except Exception, e: error(e) trans.rollback() raise
def _post_loop(): gtk.gdk.threads_enter() try: if isinstance(open_exc, err.DatabaseError): msg = _('Would you like to create a new Bauble database at ' \ 'the current connection?\n\n<i>Warning: If there is '\ 'already a database at this connection any existing '\ 'data will be destroyed!</i>') if utils.yes_no_dialog(msg, yes_delay=2): try: db.create() # db.create() creates all tables registered with # the default metadata so the pluginmgr should be # loaded after the database is created so we don't # inadvertantly create tables from the plugins pluginmgr.init() # set the default connection prefs[conn_default_pref] = conn_name except Exception, e: utils.message_details_dialog(utils.xml_safe_utf8(e), traceback.format_exc(), gtk.MESSAGE_ERROR) error(e) else:
# we have commit after create after each table is imported # or Postgres will complain if two tables that are # being imported have a foreign key relationship transaction.commit() #debug('%s: %s' % (table.name, table.select().alias().count().execute().fetchone()[0])) transaction = connection.begin() #debug('creating: %s' % ', '.join([d.name for d in depends])) # TODO: need to get those tables from depends that need to # be created but weren't created already metadata.create_all(connection, depends, checkfirst=True) except GeneratorExit, e: transaction.rollback() raise except Exception, e: error(e) error(traceback.format_exc()) transaction.rollback() self.__error = True self.__error_exc = e raise else: transaction.commit() # unfortunately inserting an explicit value into a column that # has a sequence doesn't update the sequence, we shortcut this # by setting the sequence manually to the max(column)+1 col = None try: for table, filename in sorted_tables: for col in table.c:
#debug('init: %s' % plugin) try: plugin.init() except KeyError, e: # don't remove the plugin from the registry because if we # find it again the user might decide to reinstall it # which could overwrite data ordered.remove(plugin) msg = _("The %(plugin_name)s plugin is listed in the registry "\ "but isn't wasn't found in the plugin directory") \ % dict(plugin_name=plugin.__class__.__name__) warning(msg) except Exception, e: #error(e) ordered.remove(plugin) error(traceback.print_exc()) safe = utils.xml_safe_utf8 values = dict(entry_name=plugin.__class__.__name__, exception=safe(e)) utils.message_details_dialog(_("Error: Couldn't initialize "\ "%(entry_name)s\n\n" \ "%(exception)s." % values), traceback.format_exc(), gtk.MESSAGE_ERROR) # register the plugin commands seperately from the plugin initialization for plugin in ordered: if plugin.commands in (None, []): continue for cmd in plugin.commands: try:
handler_view = last_handler.get_view() old_view = gui.get_view() if type(old_view) != type(handler_view) and handler_view: # remove the accel_group from the window if the previous view # had one if hasattr(old_view, 'accel_group'): gui.window.remove_accel_group(old_view.accel_group) # add the new view and its accel_group if it has one gui.set_view(handler_view) if hasattr(handler_view, 'accel_group'): gui.window.add_accel_group(handler_view.accel_group) try: last_handler(cmd, arg) except Exception, e: msg = utils.xml_safe_utf8(e) error('bauble.command_handler(): %s' % msg) utils.message_details_dialog(msg, traceback.format_exc(), gtk.MESSAGE_ERROR) conn_default_pref = "conn.default" conn_list_pref = "conn.list" def main(uri=None): """ Run the main Bauble application. :param uri: the URI of the database to connect to. For more information about database URIs see `<http://www.sqlalchemy.org/docs/05/dbengine.html#create-engine-url-arguments>`_ :type uri: str """ # TODO: it would be nice to show a Tk dialog here saying we can't
def set_privilege(role, privilege): """Set the role's privileges. Arguments: - `role`: - `privilege`: """ check(privilege in ('read', 'write', 'admin', None), 'invalid privilege: %s' % privilege) conn = db.engine.connect() trans = conn.begin() if privilege: privs = _privileges[privilege] try: # revoke everything first for table in db.metadata.sorted_tables: stmt = 'revoke all on table %s from %s;' % (table.name, role) conn.execute(stmt) for col in table.c: if hasattr(col, 'sequence'): stmt = 'revoke all on sequence %s from %s' % \ (col.sequence.name, role) conn.execute(stmt) stmt = 'revoke all on database %s from %s' \ % (bauble.db.engine.url.database, role) conn.execute(stmt) stmt = 'alter role %s with nocreaterole' % role conn.execute(stmt) # privilege is None so all permissions are revoked if not privilege: trans.commit() conn.close() return # change privileges on the database if privilege == 'admin': stmt = 'grant all on database %s to %s' % \ (bauble.db.engine.url.database, role) if privilege == 'admin': stmt += ' with grant option' conn.execute(stmt) stmt = 'alter role %s with createuser' % role conn.execute(stmt) # grant privileges on the tables and sequences for table in bauble.db.metadata.sorted_tables: tbl_privs = filter(lambda x: x.lower() in _table_privs, privs) for priv in tbl_privs: stmt = 'grant %s on %s to %s' % (priv, table.name, role) if privilege == 'admin': stmt += ' with grant option' #debug(stmt) conn.execute(stmt) for col in table.c: seq_privs = filter(lambda x: x.lower() in __sequence_privs, privs) for priv in seq_privs: if hasattr(col, 'sequence'): stmt = 'grant %s on sequence %s to %s' % \ (priv, col.sequence.name, role) #debug(stmt) if privilege == 'admin': stmt += ' with grant option' conn.execute(stmt) except Exception, e: error('users.set_privilege(): %s' % utils.utf8(e)) trans.rollback() raise