def _configure(self, parser): self.exc = ExceptionHandler() sub = parser.sub() active = parser.add( sub, self.active, help="Return code shows if LDAP is configured (admins-only)") list = parser.add( sub, self.list, help="List all OMERO users with DNs") list.add_style_argument() getdn = parser.add(sub, self.getdn, help="Get DN for user on stdout") setdn = parser.add( sub, self.setdn, help="""Enable LDAP login for user (admins only) Once LDAP login is enabled for a user, the password set via OMERO is ignored, and any attempt to change it will result in an error. When you disable LDAP login, the previous password will be in effect, but if the user never had a password, one will need to be set!""") for x in (getdn, setdn): self.add_user_and_group_arguments(x) setdn.add_argument("choice", action="store", help="Enable/disable LDAP login (true/false)") discover = parser.add( sub, self.discover, help="""Discover DNs for existing OMERO users or groups This command works in the context of users or groups. Specifying --groups will only discover groups, that is check which group exists in the LDAP server and OMERO and has the "ldap" flag disabled - such groups will be presented to the user. Omitting --groups will apply the same logic to users.""") discover.add_argument( "--commands", action="store_true", default=False, help="Print setdn commands on standard out") discover.add_argument("--groups", action="store_true", default=False, help="Discover LDAP groups, not users.") create = parser.add( sub, self.create, help="Create a local user based on LDAP username (admins only)" ) create.add_argument( "username", help="LDAP username of user to be created") for x in (active, list, getdn, setdn, discover, create): x.add_login_arguments()
def _configure(self, parser): self.exc = ExceptionHandler() sub = parser.sub() add = parser.add(sub, self.add, help="Add users") add.add_argument("--ignore-existing", action="store_true", default=False, help="Do not fail if user already exists") add.add_argument("-m", "--middlename", help="Middle name, if available") add.add_argument("-e", "--email") add.add_argument("-i", "--institution") # Capitalized since conflict with main values add.add_argument("-P", "--userpassword", help="Password for user") add.add_argument("-a", "--admin", action="store_true", help="Whether the user should be an admin") add.add_argument("username", help="User's login name") add.add_argument("firstname", help="User's given name") add.add_argument("lastname", help="User's surname name") add.add_argument("member_of", nargs="+", help="Groups which the user is to be a member of") list = parser.add(sub, self.list, help="List current users") password = parser.add(sub, self.password, help="Set user's password") password.add_argument("username", nargs="?", help="Username if not the current user") email = parser.add(sub, self.email, help="List users' email addresses") email.add_argument("-n", "--names", action="store_true", default=False, help="Print user names along with email addresses") email.add_argument("-1", "--one", action="store_true", default=False, help="Print one user per line") email.add_argument("-i", "--ignore", action="store_true", default=False, help="Ignore users without email addresses")
def _configure(self, parser): self.exc = ExceptionHandler() sub = parser.sub() active = parser.add( sub, self.active, help="Return code shows if LDAP is configured (admins-only)") list = parser.add( sub, self.list, help="List all OMERO users with DNs") list.add_style_argument() getdn = parser.add(sub, self.getdn, help="Get DN for user on stdout") setdn = parser.add( sub, self.setdn, help="""Set DN for user (admins only) Once the DN is set for a user, the password set via OMERO is ignored, and any attempt to change it will result in an error. When you remove the DN, the previous password will be in effect, but if the user never had a password, one will need to be set!""") for x in (getdn, setdn): x.add_argument("username", help="User's OMERO login name") setdn.add_argument( "dn", help="User's LDAP distinguished name. If empty, LDAP will" " be disabled for the user") discover = parser.add( sub, self.discover, help="Discover distinguished names for existing OMERO users") discover.add_argument( "--commands", action="store_true", default=False, help="Print setdn commands on standard out") discover.add_argument( "--urls", help="Override OMERO omero.ldap.urls setting") discover.add_argument( "--base", help="Override OMERO omero.ldap.base setting") create = parser.add( sub, self.create, help="Create a local user based on LDAP username (admins only)" ) create.add_argument( "username", help="LDAP username of user to be created") for x in (active, list, getdn, setdn, discover, create): x.add_login_arguments()
def _configure(self, parser): self.exc = ExceptionHandler() parser.add_login_arguments() parser.add_argument("--file", help=SUPPRESS) parser.add_argument("command", nargs="?", choices=("new", "update", "null", "map-get", "map-set", "get"), help="operation to be performed") parser.add_argument("Class", nargs="?", help="OMERO model object name, e.g. Project") parser.add_argument("fields", nargs="*", help="fields to be set, e.g. name=foo") parser.set_defaults(func=self.process)
def _configure(self, parser): self.exc = ExceptionHandler() sub = parser.sub() active = parser.add( sub, self.active, help="Return code shows if LDAP is configured (admins-only)") list = parser.add(sub, self.list, help="List all OMERO users with DNs") getdn = parser.add(sub, self.getdn, help="Get DN for user on stdout") setdn = parser.add(sub, self.setdn, help="""Set DN for user (admins only) Once the DN is set for a user, the password set via OMERO is ignored, and any attempt to change it will result in an error. When you remove the DN, the previous password will be in effect, but if the user never had a password, one will need to be set!""") for x in (getdn, setdn): x.add_argument("username", help="User's OMERO login name") setdn.add_argument( "dn", help="User's LDAP distinguished name. If empty, LDAP will" " be disabled for the user") discover = parser.add( sub, self.discover, help="Discover distinguished names for existing OMERO users") discover.add_argument("--commands", action="store_true", default=False, help="Print setdn commands on standard out") discover.add_argument("--urls", help="Override OMERO omero.ldap.urls setting") discover.add_argument("--base", help="Override OMERO omero.ldap.base setting") for x in (active, list, getdn, setdn, discover): x.add_login_arguments()
def _configure(self, parser): # Add an exception handler self.exc = ExceptionHandler() # Add default login arguments, prompting the user for # server login credentials parser.add_login_arguments() # Add some 'commands', i.e. operations the plugin can perform parser.add_argument( "command", nargs="?", choices=("foo", "bar"), help="Some operation to be performed") # Add an additional argument parser.add_argument( "--some_argument", help="An additional argument") parser.set_defaults(func=self.process)
def _configure(self, parser): self.exc = ExceptionHandler() parser.add_login_arguments() sub = parser.sub() add = parser.add(sub, self.add, help="Add user") add.add_argument("--ignore-existing", action="store_true", default=False, help="Do not fail if user already exists") add.add_argument("-m", "--middlename", help="Middle name, if available") add.add_argument("-e", "--email") add.add_argument("-i", "--institution") # Capitalized since conflict with main values add.add_argument("-a", "--admin", action="store_true", help="Whether the user should be an admin") add.add_argument("username", help="User's login name") add.add_argument("firstname", help="User's given name") add.add_argument("lastname", help="User's surname name") self.add_group_arguments(add, "join", "the group as an owner") password_group = add.add_mutually_exclusive_group() password_group.add_argument("-P", "--userpassword", help="Password for user") password_group.add_argument("--no-password", action="store_true", default=False, help="Create user with empty password") list = parser.add(sub, self.list, help="List current users") list.add_style_argument() printgroup = list.add_mutually_exclusive_group() printgroup.add_argument( "--long", action="store_true", default=True, help="Print comma-separated list of all groups (default)") printgroup.add_argument("--count", action="store_true", default=False, help="Print count of all groups") sortgroup = list.add_mutually_exclusive_group() sortgroup.add_argument("--sort-by-id", action="store_true", default=True, help="Sort users by ID (default)") sortgroup.add_argument("--sort-by-login", action="store_true", default=False, help="Sort users by login") sortgroup.add_argument("--sort-by-first-name", action="store_true", default=False, help="Sort users by first name") sortgroup.add_argument("--sort-by-last-name", action="store_true", default=False, help="Sort users by last name") sortgroup.add_argument("--sort-by-email", action="store_true", default=False, help="Sort users by email") password = parser.add(sub, self.password, help="Set user's password") password.add_argument("username", nargs="?", help="Username if not the current user") email = parser.add(sub, self.email, help="List users' email addresses") email.add_argument("-n", "--names", action="store_true", default=False, help="Print user names along with email addresses") email.add_argument("-1", "--one", action="store_true", default=False, help="Print one user per line") email.add_argument("-i", "--ignore", action="store_true", default=False, help="Ignore users without email addresses") email.add_argument( "--all", action="store_true", default=False, help="Include all users, including deactivated accounts") joingroup = parser.add(sub, self.joingroup, "Join one or more groups") self.add_user_arguments(joingroup) group = self.add_group_arguments(joingroup, "join") group.add_argument("--as-owner", action="store_true", default=False, help="Join the group(s) as an owner") leavegroup = parser.add(sub, self.leavegroup, "Leave one or more groups") self.add_user_arguments(leavegroup) group = self.add_group_arguments(leavegroup, "leave") group.add_argument("--as-owner", action="store_true", default=False, help="Leave the owner list of the group(s)") for x in (email, password, list, add, joingroup, leavegroup): x.add_login_arguments()
class LdapControl(UserGroupControl): def _configure(self, parser): self.exc = ExceptionHandler() sub = parser.sub() active = parser.add( sub, self.active, help="Return code shows if LDAP is configured (admins-only)") list = parser.add( sub, self.list, help="List all OMERO users with DNs") list.add_style_argument() getdn = parser.add(sub, self.getdn, help="Get DN for user on stdout") setdn = parser.add( sub, self.setdn, help="""Enable LDAP login for user (admins only) Once LDAP login is enabled for a user, the password set via OMERO is ignored, and any attempt to change it will result in an error. When you disable LDAP login, the previous password will be in effect, but if the user never had a password, one will need to be set!""") for x in (getdn, setdn): self.add_user_and_group_arguments(x) setdn.add_argument("choice", action="store", help="Enable/disable LDAP login (true/false)") discover = parser.add( sub, self.discover, help="""Discover DNs for existing OMERO users or groups This command works in the context of users or groups. Specifying --groups will only discover groups, that is check which group exists in the LDAP server and OMERO and has the "ldap" flag disabled - such groups will be presented to the user. Omitting --groups will apply the same logic to users.""") discover.add_argument( "--commands", action="store_true", default=False, help="Print setdn commands on standard out") discover.add_argument("--groups", action="store_true", default=False, help="Discover LDAP groups, not users.") create = parser.add( sub, self.create, help="Create a local user based on LDAP username (admins only)" ) create.add_argument( "username", help="LDAP username of user to be created") for x in (active, list, getdn, setdn, discover, create): x.add_login_arguments() @admin_only def active(self, args): c = self.ctx.conn(args) ildap = c.sf.getLdapService() if ildap.getSetting(): self.ctx.out("Yes") else: self.ctx.die(1, "No") @admin_only def list(self, args): c = self.ctx.conn(args) iadmin = c.sf.getAdminService() from omero.rtypes import unwrap from omero.util.text import TableBuilder list_of_dn_user_maps = unwrap(iadmin.lookupLdapAuthExperimenters()) if list_of_dn_user_maps is None: return count = 0 tb = TableBuilder("#") if args.style: tb.set_style(args.style) tb.cols(["Id", "OmeName", "DN"]) for map in list_of_dn_user_maps: for dn, id in map.items(): try: exp = iadmin.getExperimenter(id) except: self.ctx.err("Bad experimenter: %s" % id) tb.row(count, *(id, exp.omeName.val, dn)) count += 1 self.ctx.out(str(tb.build())) @admin_only def getdn(self, args): c = self.ctx.conn(args) iadmin = c.sf.getAdminService() ildap = c.sf.getLdapService() dn = None if args.user_name: [uid, u] = self.find_user_by_name(iadmin, args.user_name, fatal=True) if u and u.getLdap().val: name = u.getOmeName().val dn = name + ": " + ildap.findDN(name) elif args.user_id: [uid, u] = self.find_user_by_id(iadmin, args.user_id, fatal=True) if u and u.getLdap().val: name = u.getOmeName().val dn = name + ": " + ildap.findDN(name) elif args.group_name: [gid, g] = self.find_group_by_name(iadmin, args.group_name, fatal=True) if g and g.getLdap().val: name = g.getName().val dn = name + ": " + ildap.findGroupDN(name) elif args.group_id: [gid, g] = self.find_group_by_id(iadmin, args.group_id, fatal=True) if g and g.getLdap().val: name = g.getName().val dn = name + ": " + ildap.findGroupDN(name) if dn is not None and dn.strip(): self.ctx.out(dn) @admin_only def setdn(self, args): c = self.ctx.conn(args) iupdate = c.sf.getUpdateService() iadmin = c.sf.getAdminService() obj = None if args.user_name: [uid, obj] = self.find_user_by_name(iadmin, args.user_name, fatal=True) elif args.user_id: [uid, obj] = self.find_user_by_id(iadmin, args.user_id, fatal=True) elif args.group_name: [gid, obj] = self.find_group_by_name(iadmin, args.group_name, fatal=True) elif args.group_id: [gid, obj] = self.find_group_by_id(iadmin, args.group_id, fatal=True) if obj is not None: obj.setLdap(rbool(args.choice.lower() in ("yes", "true", "t", "1"))) iupdate.saveObject(obj) @admin_only def discover(self, args): c = self.ctx.conn(args) ildap = c.sf.getLdapService() elements = {} element_name = "users" if args.groups: element_name = "groups" elements = ildap.discoverGroups() else: elements = ildap.discover() if len(elements) > 0: self.ctx.out("Following LDAP %s are disabled in OMERO:" % element_name) for e in elements: if args.groups: if args.commands: self.ctx.out("%s ldap setdn --group-name %s true" % (sys.argv[0], e.getName().getValue())) else: self.ctx.out("Group=%s\tname=%s" % (e.getId().getValue(), e.getName().getValue())) else: if args.commands: self.ctx.out("%s ldap setdn --user-name %s true" % (sys.argv[0], e.getOmeName().getValue())) else: self.ctx.out("Experimenter=%s\tomeName=%s" % (e.getId().getValue(), e.getOmeName().getValue())) @admin_only def create(self, args): c = self.ctx.conn(args) ildap = c.sf.getLdapService() iadmin = c.sf.getAdminService() import omero import Ice try: exp = ildap.createUser(args.username) dn = iadmin.lookupLdapAuthExperimenter(exp.id.val) self.ctx.out("Added user %s (id=%s) with DN=%s" % (exp.omeName.val, exp.id.val, dn)) except omero.ValidationException as ve: self.ctx.die(132, ve.message) except Ice.RequestFailedException as rfe: self.ctx.die(133, self.exc.handle_failed_request(rfe))
def _configure(self, parser): self.exc = ExceptionHandler() PERM_TXT = """Group permissions come in several styles: * private (rw----) [DEFAULT] * read-only (rwr---) * read-annotate (rwra--) [Previously known as 'collaborative'] In private groups, only group and system administrators will be able to view someone else's data. In read-only groups, other group members can see data but not annotate or modify it. In read-annotate groups, annotation is permitted by group members. More information is available at: http://www.openmicroscopy.org/site/support/omero4/server/permissions """ sub = parser.sub() add = parser.add(sub, self.add, "Add a new group with given permissions. " + PERM_TXT) add.add_argument("--ignore-existing", action="store_true", default=False, help="Do not fail if user already exists") add.add_argument("name", help="ExperimenterGroup.name value") perms = parser.add(sub, self.perms, "Modify a group's permissions. " + PERM_TXT) perms.add_argument("id_or_name", help="ExperimenterGroup's id or name") for x in (add, perms): group = x.add_mutually_exclusive_group() group.add_argument( "--perms", help="Group permissions set as string, e.g. 'rw----' ") group.add_argument("--type", help="Group permission set symbollically", default="private", choices=("private", "read-only", "read-annotate", "collaborative")) list = parser.add(sub, self.list, "List current groups") list.add_argument( "--long", action="store_true", help="Print comma-separated list of all groups, not just counts") copy = parser.add(sub, self.copy, "Copy the members of one group to another group") copy.add_argument( "from_group", help="Source group ID or NAME whose members will be copied") copy.add_argument( "to_group", help="Target group ID or NAME which will have new members added") insert = parser.add(sub, self.insert, "Insert one or more users into a group") insert.add_argument( "GROUP", metavar="group", help="ID or NAME of the group which is to have users added") insert.add_argument("USER", metavar="user", nargs="+", help="ID or NAME of user to be inserted") remove = parser.add(sub, self.remove, "remove one or more users from a group") remove.add_argument( "GROUP", metavar="group", help="ID or NAME of the group which is to have users removed") remove.add_argument("USER", metavar="user", nargs="+", help="ID or NAME of user to be removed")
class LdapControl(UserGroupControl): def _configure(self, parser): self.exc = ExceptionHandler() sub = parser.sub() active = parser.add( sub, self.active, help="Return code shows if LDAP is configured (admins-only)") list = parser.add(sub, self.list, help="List all OMERO users with DNs") list.add_style_argument() getdn = parser.add(sub, self.getdn, help="Get DN for user on stdout") setdn = parser.add( sub, self.setdn, help="""Enable or disable LDAP login for user (admins only) Once LDAP login is enabled for a user, the password set via OMERO is ignored, and any attempt to change it will result in an error. When you disable LDAP login, the previous password will be in effect, but if the user never had a password, one will need to be set!""") for x in (getdn, setdn): self.add_user_and_group_arguments(x) setdn.add_argument("choice", action="store", help="Enable/disable LDAP login (true/false)") discover = parser.add( sub, self.discover, help="""Discover DNs for existing OMERO users or groups This command works in the context of users or groups. Specifying --groups will only discover groups, that is check which group exists in the LDAP server and OMERO and has the "ldap" flag disabled - such groups will be presented to the user. Omitting --groups will apply the same logic to users.""") discover.add_argument("--commands", action="store_true", default=False, help="Print setdn commands on standard out") discover.add_argument("--groups", action="store_true", default=False, help="Discover LDAP groups, not users.") create = parser.add( sub, self.create, help="Create a local user based on LDAP username (admins only)") create.add_argument("username", help="LDAP username of user to be created") for x in (active, list, getdn, setdn, discover, create): x.add_login_arguments() @admin_only(full_admin=False) # IConfig privilege def active(self, args): c = self.ctx.conn(args) ildap = c.sf.getLdapService() if ildap.getSetting(): self.ctx.out("Yes") else: self.ctx.die(1, "No") def list(self, args): c = self.ctx.conn(args) iadmin = c.sf.getAdminService() from omero.rtypes import unwrap from omero.util.text import TableBuilder list_of_dn_user_maps = unwrap(iadmin.lookupLdapAuthExperimenters()) if list_of_dn_user_maps is None: return count = 0 tb = TableBuilder("#") if args.style: tb.set_style(args.style) tb.cols(["Id", "OmeName", "DN"]) for map in list_of_dn_user_maps: for dn, id in list(map.items()): try: exp = iadmin.getExperimenter(id) except: self.ctx.err("Bad experimenter: %s" % id) tb.row(count, *(id, exp.omeName.val, dn)) count += 1 self.ctx.out(str(tb.build())) @admin_only(full_admin=False) # ILdap privilege def getdn(self, args): c = self.ctx.conn(args) iadmin = c.sf.getAdminService() ildap = c.sf.getLdapService() dn = None if args.user_name: [uid, u] = self.find_user_by_name(iadmin, args.user_name, fatal=True) if u and u.getLdap().val: name = u.getOmeName().val dn = name + ": " + ildap.findDN(name) elif args.user_id: [uid, u] = self.find_user_by_id(iadmin, args.user_id, fatal=True) if u and u.getLdap().val: name = u.getOmeName().val dn = name + ": " + ildap.findDN(name) elif args.group_name: [gid, g] = self.find_group_by_name(iadmin, args.group_name, fatal=True) if g and g.getLdap().val: name = g.getName().val dn = name + ": " + ildap.findGroupDN(name) elif args.group_id: [gid, g] = self.find_group_by_id(iadmin, args.group_id, fatal=True) if g and g.getLdap().val: name = g.getName().val dn = name + ": " + ildap.findGroupDN(name) if dn is not None and dn.strip(): self.ctx.out(dn) @admin_only(AdminPrivilegeModifyGroup) def update_group(self, iupdate, group): iupdate.saveObject(group) @admin_only(AdminPrivilegeModifyUser) def update_user(self, iupdate, user): iupdate.saveObject(user) @admin_only(full_admin=False) # See update_user/update_group def setdn(self, args): c = self.ctx.conn(args) iupdate = c.sf.getUpdateService() iadmin = c.sf.getAdminService() obj = None if args.user_name: [uid, obj] = self.find_user_by_name(iadmin, args.user_name, fatal=True) elif args.user_id: [uid, obj] = self.find_user_by_id(iadmin, args.user_id, fatal=True) elif args.group_name: [gid, obj] = self.find_group_by_name(iadmin, args.group_name, fatal=True) elif args.group_id: [gid, obj] = self.find_group_by_id(iadmin, args.group_id, fatal=True) if obj is not None: from omero.model import Experimenter, ExperimenterGroup obj.setLdap(rbool(args.choice.lower() in ("yes", "true", "t", "1"))) if isinstance(obj, ExperimenterGroup): self.update_group(iupdate, obj) elif isinstance(obj, Experimenter): self.update_user(iupdate, obj) @admin_only(full_admin=False) # ILdap privilege def discover(self, args): c = self.ctx.conn(args) ildap = c.sf.getLdapService() elements = {} element_name = "users" if args.groups: element_name = "groups" elements = ildap.discoverGroups() else: elements = ildap.discover() if len(elements) > 0: self.ctx.out("Following LDAP %s are disabled in OMERO:" % element_name) for e in elements: if args.groups: if args.commands: self.ctx.out("%s ldap setdn --group-name %s true" % (sys.argv[0], e.getName().getValue())) else: self.ctx.out( "Group=%s\tname=%s" % (e.getId().getValue(), e.getName().getValue())) else: if args.commands: self.ctx.out("%s ldap setdn --user-name %s true" % (sys.argv[0], e.getOmeName().getValue())) else: self.ctx.out( "Experimenter=%s\tomeName=%s" % (e.getId().getValue(), e.getOmeName().getValue())) @admin_only(AdminPrivilegeModifyUser, AdminPrivilegeModifyGroupMembership) def create(self, args): c = self.ctx.conn(args) ildap = c.sf.getLdapService() iadmin = c.sf.getAdminService() import omero import Ice try: exp = ildap.createUser(args.username) dn = iadmin.lookupLdapAuthExperimenter(exp.id.val) self.ctx.out("Added user %s (id=%s) with DN=%s" % (exp.omeName.val, exp.id.val, dn)) except omero.ValidationException as ve: self.ctx.die(132, ve.message) except Ice.RequestFailedException as rfe: self.ctx.die(133, self.exc.handle_failed_request(rfe))
def _configure(self, parser): self.exc = ExceptionHandler() PERM_TXT = """ Group permissions come in several styles: * private (rw----) [DEFAULT] * read-only (rwr---) * read-annotate (rwra--) [Previously known as 'collaborative'] In private groups, only group and system administrators will be able to view someone else's data. In read-only groups, other group members can see data but not annotate or modify it. In read-annotate groups, annotation is permitted by group members. More information is available at: https://www.openmicroscopy.org/site/support/omero4/sysadmins/server-permissions.html """ OWNER_TXT = """ Your group may have one or more owners. The group owner has some additional rights within each group than a standard group member, including the ability to add other members to the group. More information is available at: https://www.openmicroscopy.org/site/support/omero4/sysadmins/server-permissions.html """ parser.add_login_arguments() sub = parser.sub() add = parser.add(sub, self.add, "Add a new group with given permissions " + PERM_TXT) add.add_argument("--ignore-existing", action="store_true", default=False, help="Do not fail if user already exists") add.add_argument("name", help="Name of the group") self.add_permissions_arguments(add) perms = parser.add(sub, self.perms, "Modify a group's permissions " + PERM_TXT) self.add_group_arguments(perms) self.add_permissions_arguments(perms) list = parser.add(sub, self.list, "List current groups") printgroup = list.add_mutually_exclusive_group() printgroup.add_argument( "--count", action="store_true", help="Print count of all users and owners (default)", default=True) printgroup.add_argument( "--long", action="store_true", help="Print comma-separated list of all users and owners", default=False) sortgroup = list.add_mutually_exclusive_group() sortgroup.add_argument("--sort-by-id", action="store_true", default=True, help="Sort groups by ID (default)") sortgroup.add_argument("--sort-by-name", action="store_true", default=False, help="Sort groups by name") copyusers = parser.add(sub, self.copyusers, "Copy the users of one group to another group") copyusers.add_argument( "from_group", help="ID or name of the source group whose users will be copied") copyusers.add_argument( "to_group", help= "ID or name of the target group which will have new users added") copyusers.add_argument("--as-owner", action="store_true", default=False, help="Copy the group owners only") adduser = parser.add(sub, self.adduser, "Add one or more users to a group") self.add_group_arguments(adduser) group = self.add_user_arguments(adduser, "add to the group") group.add_argument("--as-owner", action="store_true", default=False, help="Add the users as owners of the group") removeuser = parser.add(sub, self.removeuser, "Remove one or more users from a group") self.add_group_arguments(removeuser) group = self.add_user_arguments(removeuser, "remove from the group") group.add_argument("--as-owner", action="store_true", default=False, help="Remove the users from the group owner list") for x in (add, perms, list, copyusers, adduser, removeuser): x.add_login_arguments()
def _configure(self, parser): self.exc = ExceptionHandler() parser.add_login_arguments() sub = parser.sub() add = parser.add(sub, self.add, help="Add user") add.add_argument("--ignore-existing", action="store_true", default=False, help="Do not fail if user already exists") add.add_argument("-m", "--middlename", help="Middle name, if available") add.add_argument("-e", "--email") add.add_argument("-i", "--institution") # Capitalized since conflict with main values add.add_argument("-a", "--admin", action="store_true", help="Whether the user should be an admin") add.add_argument("username", help="User's login name") add.add_argument("firstname", help="User's first name") add.add_argument("lastname", help="User's last name") self.add_group_arguments(add, " to join") password_group = add.add_mutually_exclusive_group() password_group.add_argument("-P", "--userpassword", help="Password for user") password_group.add_argument("--no-password", action="store_true", default=False, help="Create user with empty password") list = parser.add(sub, self.list, help="List information about all users") info = parser.add( sub, self.info, "List information about the user(s). Default to the context user") self.add_user_arguments(info) for x in (list, info): x.add_style_argument() x.add_group_print_arguments() x.add_user_sorting_arguments() listgroups = parser.add( sub, self.listgroups, "List the groups of the user. Default to the context user") self.add_user_arguments(listgroups) listgroups.add_style_argument() listgroups.add_user_print_arguments() listgroups.add_group_sorting_arguments() password = parser.add(sub, self.password, help="Set user's password") password.add_argument("username", nargs="?", help="Username if not the current user") email = parser.add(sub, self.email, help="List users' email addresses") email.add_argument("-n", "--names", action="store_true", default=False, help="Print user names along with email addresses") email.add_argument("-1", "--one", action="store_true", default=False, help="Print one user per line") email.add_argument("-i", "--ignore", action="store_true", default=False, help="Ignore users without email addresses") email.add_argument( "--all", action="store_true", default=False, help="Include all users, including deactivated accounts") joingroup = parser.add(sub, self.joingroup, "Join one or more groups") self.add_id_name_arguments(joingroup, "user. Default to the current user") group = self.add_group_arguments(joingroup, " to join") group.add_argument("--as-owner", action="store_true", default=False, help="Join the group(s) as an owner") leavegroup = parser.add(sub, self.leavegroup, "Leave one or more groups") self.add_id_name_arguments(leavegroup, "user. Default to the current user") group = self.add_group_arguments(leavegroup, " to leave") group.add_argument("--as-owner", action="store_true", default=False, help="Leave the owner list of the group(s)") for x in (email, password, list, add, joingroup, leavegroup): x.add_login_arguments()
class UserControl(UserGroupControl): def _configure(self, parser): self.exc = ExceptionHandler() parser.add_login_arguments() sub = parser.sub() add = parser.add(sub, self.add, help="Add user") add.add_argument("--ignore-existing", action="store_true", default=False, help="Do not fail if user already exists") add.add_argument("-m", "--middlename", help="Middle name, if available") add.add_argument("-e", "--email") add.add_argument("-i", "--institution") # Capitalized since conflict with main values add.add_argument("-a", "--admin", action="store_true", help="Whether the user should be an admin") add.add_argument("username", help="User's login name") add.add_argument("firstname", help="User's first name") add.add_argument("lastname", help="User's last name") self.add_group_arguments(add, " to join") password_group = add.add_mutually_exclusive_group() password_group.add_argument("-P", "--userpassword", help="Password for user") password_group.add_argument("--no-password", action="store_true", default=False, help="Create user with empty password") list = parser.add(sub, self.list, help="List information about all users") info = parser.add( sub, self.info, "List information about the user(s). Default to the context user") self.add_user_arguments(info) for x in (list, info): x.add_style_argument() x.add_group_print_arguments() x.add_user_sorting_arguments() listgroups = parser.add( sub, self.listgroups, "List the groups of the user. Default to the context user") self.add_user_arguments(listgroups) listgroups.add_style_argument() listgroups.add_user_print_arguments() listgroups.add_group_sorting_arguments() password = parser.add(sub, self.password, help="Set user's password") password.add_argument("username", nargs="?", help="Username if not the current user") email = parser.add(sub, self.email, help="List users' email addresses") email.add_argument("-n", "--names", action="store_true", default=False, help="Print user names along with email addresses") email.add_argument("-1", "--one", action="store_true", default=False, help="Print one user per line") email.add_argument("-i", "--ignore", action="store_true", default=False, help="Ignore users without email addresses") email.add_argument( "--all", action="store_true", default=False, help="Include all users, including deactivated accounts") joingroup = parser.add(sub, self.joingroup, "Join one or more groups") self.add_id_name_arguments(joingroup, "user. Default to the current user") group = self.add_group_arguments(joingroup, " to join") group.add_argument("--as-owner", action="store_true", default=False, help="Join the group(s) as an owner") leavegroup = parser.add(sub, self.leavegroup, "Leave one or more groups") self.add_id_name_arguments(leavegroup, "user. Default to the current user") group = self.add_group_arguments(leavegroup, " to leave") group.add_argument("--as-owner", action="store_true", default=False, help="Leave the owner list of the group(s)") for x in (email, password, list, add, joingroup, leavegroup): x.add_login_arguments() def format_name(self, exp): record = "" fn = _(exp.firstName) mn = " " if _(exp.middleName): mn = " %s " % _(exp.middleName) ln = _(exp.lastName) record += "%s%s%s" % (fn, mn, ln) return record def email(self, args): c = self.ctx.conn(args) a = c.sf.getAdminService() r = a.getSecurityRoles() skipped = [] records = [] for exp in a.lookupExperimenters(): # Handle users without email if not _(exp.email): if not args.ignore: skipped.append(exp) continue # Handle deactivated users if not args.all: groups = exp.linkedExperimenterGroupList() group_ids = [x.id.val for x in groups] if r.userGroupId not in group_ids: continue record = "" if args.names: record += '"%s"' % self.format_name(exp) record += " <%s>" % _(exp.email) else: record += _(exp.email) records.append(record) if args.one: for record in records: self.ctx.out(record) else: self.ctx.out(", ".join(records)) if skipped: self.ctx.err("Missing email addresses:") for s in skipped: self.ctx.err(self.format_name(s)) def password(self, args): import omero from omero.rtypes import rstring client = self.ctx.conn(args) own_name = self.ctx.get_event_context().userName admin = client.sf.getAdminService() # tickets 3202, 5841 own_pw = self._ask_for_password(" for your user (%s)" % own_name, strict=False) try: client.sf.setSecurityPassword(own_pw) self.ctx.out("Verified password.\n") except omero.SecurityViolation as sv: import traceback self.ctx.die(456, "SecurityViolation: Bad credentials") self.ctx.dbg(traceback.format_exception(None, e, sys.exc_info()[2])) if args.username: try: e = admin.lookupExperimenter(args.username) except omero.ApiUsageException: self.ctx.die(457, "Unknown user: %s" % args.username) return # Never reached self.ctx.out("Changing password for %s (id:%s)" % (args.username, e.id.val)) else: self.ctx.out("Changing password for %s" % own_name) pw = self._ask_for_password(" to be set") pw = rstring(pw) if args.username: admin.changeUserPassword(args.username, pw) else: admin.changePassword(pw) self.ctx.out("Password changed") def list(self, args): c = self.ctx.conn(args) a = c.sf.getAdminService() users = a.lookupExperimenters() self.output_users_list(a, users, args) def info(self, args): c = self.ctx.conn(args) a = c.sf.getAdminService() [uids, users] = self.list_users(a, args, use_context=True) self.output_users_list(a, users, args) def listgroups(self, args): c = self.ctx.conn(args) admin = c.sf.getAdminService() [uids, groups] = self.list_users(admin, args, use_context=True) if len(uids) != 1: self.ctx.die(516, 'Too many user arguments') groups = admin.containedGroups(uids[0]) self.output_groups_list(groups, args) @admin_only(AdminPrivilegeModifyUser, AdminPrivilegeModifyGroupMembership) def add(self, args): email = args.email login = args.username first = args.firstname middle = args.middlename last = args.lastname inst = args.institution pasw = args.userpassword import omero from omero.rtypes import rbool, rstring from omero_model_ExperimenterI import ExperimenterI as Exp from omero_model_ExperimenterGroupI import ExperimenterGroupI as Grp c = self.ctx.conn(args) e = Exp() e.omeName = rstring(login) e.firstName = rstring(first) e.lastName = rstring(last) e.middleName = rstring(middle) e.email = rstring(email) e.institution = rstring(inst) e.ldap = rbool(False) # Fail-fast if no-password is passed and the server does not accept # empty passwords configService = c.getSession().getConfigService() password_required = configService.getConfigValue( "omero.security.password_required").lower() if args.no_password and password_required != 'false': self.ctx.die( 502, "Server does not allow user creation with empty" " passwords") # Check user existence admin = c.getSession().getAdminService() try: usr = admin.lookupExperimenter(login) if usr: if args.ignore_existing: self.ctx.out("User exists: %s (id=%s)" % (login, usr.id.val)) return else: self.ctx.die( 3, "User exists: %s (id=%s)" % (login, usr.id.val)) except omero.ApiUsageException: pass # Apparently no such user exists [gid, groups] = self.list_groups(admin, args, use_context=False) roles = admin.getSecurityRoles() groups.append(Grp(roles.userGroupId, False)) if args.admin: groups.append(Grp(roles.systemGroupId, False)) group = groups.pop(0) try: if args.no_password: id = admin.createExperimenter(e, group, groups) self.ctx.out("Added user %s (id=%s) without password" % (login, id)) else: if pasw is None: pasw = self._ask_for_password(" for your new user (%s)" % login, strict=True) id = admin.createExperimenterWithPassword( e, rstring(pasw), group, groups) self.ctx.out("Added user %s (id=%s) with password" % (login, id)) except omero.ValidationException as ve: # Possible, though unlikely after previous check if self.exc.is_constraint_violation(ve): self.ctx.die(66, "User already exists: %s" % login) else: self.ctx.die(67, "Unknown ValidationException: %s" % ve.message) except omero.SecurityViolation as se: self.ctx.die(68, "Security violation: %s" % se.message) def parse_userid(self, a, args): if args.id: user = getattr(args, "id", None) return self.find_user_by_id(a, user, fatal=True) elif args.name: user = getattr(args, "name", None) return self.find_user_by_name(a, user, fatal=True) else: user = self.ctx.get_event_context().userName return self.find_user_by_name(a, user, fatal=True) def filter_groups(self, groups, uid, owner=False, join=True): for group in list(groups): if owner: uid_list = self.getownerids(group) relation = "owner of" else: uid_list = self.getuserids(group) relation = "in" if join: if uid in uid_list: self.ctx.out("%s is already %s group %s" % (uid, relation, group.id.val)) groups.remove(group) else: if uid not in uid_list: self.ctx.out("%s is not %s group %s" % (uid, relation, group.id.val)) groups.remove(group) return groups def joingroup(self, args): c = self.ctx.conn(args) a = c.sf.getAdminService() uid, username = self.parse_userid(a, args) [gid, groups] = self.list_groups(a, args, use_context=False) groups = self.filter_groups(groups, uid, args.as_owner, True) for group in groups: if args.as_owner: self.addownersbyid(a, group, [uid]) else: self.addusersbyid(a, group, [uid]) def leavegroup(self, args): c = self.ctx.conn(args) a = c.sf.getAdminService() uid, username = self.parse_userid(a, args) [gid, groups] = self.list_groups(a, args, use_context=False) groups = self.filter_groups(groups, uid, args.as_owner, False) for group in list(groups): if args.as_owner: self.removeownersbyid(a, group, [uid]) else: self.removeusersbyid(a, group, [uid])
def _configure(self, parser): self.exc = ExceptionHandler() PERM_TXT = """ Group permissions come in several styles: * private (rw----) [DEFAULT] * read-only (rwr---) * read-annotate (rwra--) [Previously known as 'collaborative'] * read-write (rwrw--) In private groups, only group owners and system administrators will be able to view someone else's data. In read-only groups, other group members can see data but not annotate or modify it. In read-annotate groups, annotation is permitted by group members. In read-write groups, all group members can behave as if they co-own all the data. Changing a group to private unlinks data from other users' containers and unlinks other users' annotations from data. The change to private will fail if different users' data is too closely related to be separated. More information is available at: https://docs.openmicroscopy.org/latest/omero/sysadmins/\ server-permissions.html """ parser.add_login_arguments() sub = parser.sub() add = parser.add(sub, self.add, "Add a new group with given permissions " + PERM_TXT) add.add_argument("--ignore-existing", action="store_true", default=False, help="Do not fail if user already exists") add.add_argument("name", help="Name of the group") self.add_permissions_arguments(add) perms = parser.add(sub, self.perms, "Modify a group's permissions " + PERM_TXT) self.add_id_name_arguments(perms, "group") self.add_permissions_arguments(perms) list = parser.add(sub, self.list, help="List information about all groups") info = parser.add( sub, self.info, "List information about the group(s). Default to the context" " group") self.add_group_arguments(info) for x in (list, info): x.add_style_argument() x.add_user_print_arguments() x.add_group_sorting_arguments() listusers = parser.add(sub, self.listusers, "List users of the current group") self.add_group_arguments(listusers) listusers.add_style_argument() listusers.add_group_print_arguments() listusers.add_user_sorting_arguments() copyusers = parser.add( sub, self.copyusers, "Copy the users of one" " group to another group") copyusers.add_argument("from_group", help="ID or name of the source" " group whose users will be copied") copyusers.add_argument("to_group", help="ID or name of the target" " group which will have new users added") copyusers.add_argument("--as-owner", action="store_true", default=False, help="Copy the group owners only") adduser = parser.add(sub, self.adduser, "Add one or more users to a group") self.add_id_name_arguments(adduser, "group") group = self.add_user_arguments(adduser, action=" to add to the group") group.add_argument("--as-owner", action="store_true", default=False, help="Add the users as owners of the group") removeuser = parser.add(sub, self.removeuser, "Remove one or more users from a group") self.add_id_name_arguments(removeuser, "group") group = self.add_user_arguments(removeuser, action=" to remove from the group") group.add_argument("--as-owner", action="store_true", default=False, help="Remove the users from the group owner list") for x in (add, perms, list, copyusers, adduser, removeuser): x.add_login_arguments()
def _configure(self, parser): self.exc = ExceptionHandler() parser.add_login_arguments() sub = parser.sub() listtags = parser.add(sub, self.list, help="List all the tags, grouped by tagset") self.add_standard_params(listtags) listtags.add_argument("--tagset", nargs="+", type=int, help="One or more tagset IDs") self.add_tag_common_params(listtags) listtags.add_login_arguments() listsets = parser.add(sub, self.listsets, help="List tag sets") self.add_standard_params(listsets) listsets.add_argument( "--tag", nargs="+", type=int, help="List only tagsets containing the following tag ID(s)") self.add_tag_common_params(listsets) listsets.add_login_arguments() create = parser.add(sub, self.create, help="Create a new tag") self.add_newtag_params(create) create.add_login_arguments() createset = parser.add(sub, self.createset, help="Create a new tag set") createset.add_argument( "--tag", nargs="+", required=True, type=int, help="ID(s) of the tag(s) to include in this set") self.add_newtag_params(createset) createset.add_login_arguments() loadj = sub.add_parser( self.load.__func__.__name__, help="Import new tag(s) and tagset(s) from JSON file", description="Import new tag(s) and tagset(s) from JSON file", epilog=""" JSON File Format: The format of the JSON file should be as follows: [{ "name" : "Name of the tagset", "desc" : "Description of the tagset", "set" : [{ "name" : "Name of tag", "desc" : "Description of tag" },{ "name" : "Name of tag", "desc" : "Description of tag" },{ .... },{ .... }] """) loadj.set_defaults(func=self.load) loadj.add_argument("filename", nargs="?", help="The filename containing tag JSON") loadj.add_login_arguments() links = parser.add(sub, self.link, help="Link annotation to an object") links.add_argument("object", help="The object to link to. Should be of form" " <object_type>:<object_id>") links.add_argument('tag_id', type=int, help="The tag annotation ID") self.add_standard_params(links) links.add_login_arguments()
class GroupControl(UserGroupControl): def _configure(self, parser): self.exc = ExceptionHandler() PERM_TXT = """ Group permissions come in several styles: * private (rw----) [DEFAULT] * read-only (rwr---) * read-annotate (rwra--) [Previously known as 'collaborative'] * read-write (rwrw--) In private groups, only group owners and system administrators will be able to view someone else's data. In read-only groups, other group members can see data but not annotate or modify it. In read-annotate groups, annotation is permitted by group members. In read-write groups, all group members can behave as if they co-own all the data. Changing a group to private unlinks data from other users' containers and unlinks other users' annotations from data. The change to private will fail if different users' data is too closely related to be separated. More information is available at: https://docs.openmicroscopy.org/latest/omero/sysadmins/\ server-permissions.html """ parser.add_login_arguments() sub = parser.sub() add = parser.add(sub, self.add, "Add a new group with given permissions " + PERM_TXT) add.add_argument("--ignore-existing", action="store_true", default=False, help="Do not fail if user already exists") add.add_argument("name", help="Name of the group") self.add_permissions_arguments(add) perms = parser.add(sub, self.perms, "Modify a group's permissions " + PERM_TXT) self.add_id_name_arguments(perms, "group") self.add_permissions_arguments(perms) list = parser.add(sub, self.list, help="List information about all groups") info = parser.add( sub, self.info, "List information about the group(s). Default to the context" " group") self.add_group_arguments(info) for x in (list, info): x.add_style_argument() x.add_user_print_arguments() x.add_group_sorting_arguments() listusers = parser.add(sub, self.listusers, "List users of the current group") self.add_group_arguments(listusers) listusers.add_style_argument() listusers.add_group_print_arguments() listusers.add_user_sorting_arguments() copyusers = parser.add( sub, self.copyusers, "Copy the users of one" " group to another group") copyusers.add_argument("from_group", help="ID or name of the source" " group whose users will be copied") copyusers.add_argument("to_group", help="ID or name of the target" " group which will have new users added") copyusers.add_argument("--as-owner", action="store_true", default=False, help="Copy the group owners only") adduser = parser.add(sub, self.adduser, "Add one or more users to a group") self.add_id_name_arguments(adduser, "group") group = self.add_user_arguments(adduser, action=" to add to the group") group.add_argument("--as-owner", action="store_true", default=False, help="Add the users as owners of the group") removeuser = parser.add(sub, self.removeuser, "Remove one or more users from a group") self.add_id_name_arguments(removeuser, "group") group = self.add_user_arguments(removeuser, action=" to remove from the group") group.add_argument("--as-owner", action="store_true", default=False, help="Remove the users from the group owner list") for x in (add, perms, list, copyusers, adduser, removeuser): x.add_login_arguments() def add_permissions_arguments(self, parser): group = parser.add_mutually_exclusive_group() group.add_argument( "--perms", help="Group permissions set as string, e.g. 'rw----' ") group.add_argument("--type", help="Group permissions set symbolically", default="private", choices=list(defaultperms.keys())) def parse_perms(self, args): from omero_model_PermissionsI import PermissionsI as Perms perms = getattr(args, "perms", None) if not perms: perms = defaultperms[args.type] try: return Perms(perms) except ValueError as ve: self.ctx.die(505, str(ve)) @admin_only(AdminPrivilegeModifyGroup) def add(self, args): import omero from omero.rtypes import rbool, rstring from omero_model_ExperimenterGroupI import ExperimenterGroupI as Grp perms = self.parse_perms(args) c = self.ctx.conn(args) g = Grp() g.name = rstring(args.name) g.ldap = rbool(False) g.details.permissions = perms admin = c.getSession().getAdminService() try: grp = admin.lookupGroup(args.name) if grp: if args.ignore_existing: self.ctx.out("Group exists: %s (id=%s)" % (args.name, grp.id.val)) return else: self.ctx.die( 3, "Group exists: %s (id=%s)" % (args.name, grp.id.val)) except omero.ApiUsageException: pass # Apparently no such group exists try: id = admin.createGroup(g) self.ctx.out("Added group %s (id=%s) with permissions %s" % (args.name, id, perms)) except omero.ValidationException as ve: # Possible, though unlikely after previous check if self.exc.is_constraint_violation(ve): self.ctx.die(66, "Group already exists: %s" % args.name) else: self.ctx.die(67, "Unknown ValidationException: %s" % ve.message) except omero.SecurityViolation as se: self.ctx.die(68, "Security violation: %s" % se.message) except omero.ServerError as se: self.ctx.die(4, "%s: %s" % (type(se), se.message)) def perms(self, args): import omero perms = self.parse_perms(args) c = self.ctx.conn(args) a = c.sf.getAdminService() gid, g = self.parse_groupid(a, args) old_perms = str(g.details.permissions) if old_perms == str(perms): self.ctx.out("Permissions for group %s (id=%s) already %s" % (g.name.val, gid, perms)) else: try: chmod = omero.cmd.Chmod2( targetObjects={'ExperimenterGroup': [gid]}, permissions=str(perms)) c.submit(chmod) self.ctx.out("Changed permissions for group %s (id=%s) to %s" % (g.name.val, gid, perms)) except omero.CmdError as ce: import traceback self.ctx.dbg(traceback.format_exc()) self.ctx.die( 504, "Cannot change permissions for group %s" " (id=%s) to %s: %s" % (g.name.val, gid, perms, ce.err)) def list(self, args): c = self.ctx.conn(args) groups = c.sf.getAdminService().lookupGroups() self.output_groups_list(groups, args) def info(self, args): c = self.ctx.conn(args) a = c.sf.getAdminService() [gid, groups] = self.list_groups(a, args, use_context=True) self.output_groups_list(groups, args) def listusers(self, args): c = self.ctx.conn(args) admin = c.sf.getAdminService() [gids, groups] = self.list_groups(admin, args, use_context=True) if len(gids) != 1: self.ctx.die(516, 'Too many group arguments') users = admin.containedExperimenters(gids[0]) self.output_users_list(admin, users, args) def parse_groupid(self, a, args): if args.id: group = getattr(args, "id", None) return self.find_group_by_id(a, group, fatal=True) elif args.name: group = getattr(args, "name", None) return self.find_group_by_name(a, group, fatal=True) else: self.error_no_input_group(fatal=True) def filter_users(self, uids, group, owner=False, join=True): if owner: uid_list = self.getownerids(group) relation = "owner of" else: uid_list = self.getuserids(group) relation = "in" for uid in list(uids): if join: if uid in uid_list: self.ctx.out("%s is already %s group %s" % (uid, relation, group.id.val)) uids.remove(uid) else: if uid not in uid_list: self.ctx.out("%s is not %s group %s" % (uid, relation, group.id.val)) uids.remove(uid) return uids def copyusers(self, args): c = self.ctx.conn(args) a = c.sf.getAdminService() f_gid, f_grp = self.find_group(a, args.from_group, fatal=True) t_gid, t_grp = self.find_group(a, args.to_group, fatal=True) if args.as_owner: uids = self.getownerids(f_grp) else: uids = self.getuserids(f_grp) uids = self.filter_users(uids, t_grp, args.as_owner, True) if args.as_owner: self.addownersbyid(a, t_grp, uids) self.ctx.out("Owners of %s copied to %s" % (args.from_group, args.to_group)) else: self.addusersbyid(a, t_grp, uids) self.ctx.out("Users of %s copied to %s" % (args.from_group, args.to_group)) def adduser(self, args): c = self.ctx.conn(args) a = c.sf.getAdminService() group = self.parse_groupid(a, args)[1] [uids, users] = self.list_users(a, args, use_context=False) uids = self.filter_users(uids, group, args.as_owner, True) if args.as_owner: self.addownersbyid(a, group, uids) else: self.addusersbyid(a, group, uids) def removeuser(self, args): c = self.ctx.conn(args) a = c.sf.getAdminService() group = self.parse_groupid(a, args)[1] [uids, users] = self.list_users(a, args, use_context=False) uids = self.filter_users(uids, group, args.as_owner, False) if args.as_owner: self.removeownersbyid(a, group, uids) else: self.removeusersbyid(a, group, uids)
class LdapControl(BaseControl): def _configure(self, parser): self.exc = ExceptionHandler() sub = parser.sub() active = parser.add( sub, self.active, help="Return code shows if LDAP is configured (admins-only)") list = parser.add( sub, self.list, help="List all OMERO users with DNs") list.add_style_argument() getdn = parser.add(sub, self.getdn, help="Get DN for user on stdout") setdn = parser.add( sub, self.setdn, help="""Set DN for user (admins only) Once the DN is set for a user, the password set via OMERO is ignored, and any attempt to change it will result in an error. When you remove the DN, the previous password will be in effect, but if the user never had a password, one will need to be set!""") for x in (getdn, setdn): x.add_argument("username", help="User's OMERO login name") setdn.add_argument( "dn", help="User's LDAP distinguished name. If empty, LDAP will" " be disabled for the user") discover = parser.add( sub, self.discover, help="Discover distinguished names for existing OMERO users") discover.add_argument( "--commands", action="store_true", default=False, help="Print setdn commands on standard out") discover.add_argument( "--urls", help="Override OMERO omero.ldap.urls setting") discover.add_argument( "--base", help="Override OMERO omero.ldap.base setting") create = parser.add( sub, self.create, help="Create a local user based on LDAP username (admins only)" ) create.add_argument( "username", help="LDAP username of user to be created") for x in (active, list, getdn, setdn, discover, create): x.add_login_arguments() def __import_ldap__(self): try: import ldap except: self.ctx.die(155, """Python "ldap" module is not installed""") return ldap def active(self, args): c = self.ctx.conn(args) ildap = c.sf.getLdapService() import omero try: if ildap.getSetting(): self.ctx.out("Yes") else: self.ctx.die(1, "No") except omero.SecurityViolation: self.error_admin_only(fatal=True) def list(self, args): c = self.ctx.conn(args) iadmin = c.sf.getAdminService() import omero from omero.rtypes import unwrap from omero.util.text import TableBuilder try: list_of_dn_user_maps = unwrap(iadmin.lookupLdapAuthExperimenters()) if list_of_dn_user_maps is None: return count = 0 tb = TableBuilder("#") if args.style: tb.set_style(args.style) tb.cols(["Id", "OmeName", "DN"]) for map in list_of_dn_user_maps: for dn, id in map.items(): try: exp = iadmin.getExperimenter(id) except: self.ctx.err("Bad experimenter: %s" % id) tb.row(count, *(id, exp.omeName.val, dn)) count += 1 self.ctx.out(str(tb.build())) except omero.SecurityViolation: self.error_admin_only(fatal=True) def getdn(self, args): c = self.ctx.conn(args) iadmin = c.sf.getAdminService() try: exp = iadmin.lookupExperimenter(args.username) except: self.ctx.die(134, "Unknown user: %s" % args.username) dn = iadmin.lookupLdapAuthExperimenter(exp.id.val) if dn is not None and dn.strip(): self.ctx.out(dn) else: self.ctx.die(136, "DN Not found: %s" % dn) def setdn(self, args): c = self.ctx.conn(args) ildap = c.sf.getLdapService() iadmin = c.sf.getAdminService() try: exp = iadmin.lookupExperimenter(args.username) except: self.ctx.die(134, "Unknown user: %s" % args.username) import omero try: ildap.setDN(exp.id, args.dn) except omero.SecurityViolation: self.error_admin_only(fatal=True) def discover(self, args): import omero ldap = self.__import_ldap__() c = self.ctx.conn(args) iconfig = c.sf.getConfigService() iadmin = c.sf.getAdminService() iquery = c.sf.getQueryService() LDAP_PROPERTIES = """ omero.ldap.urls omero.ldap.username omero.ldap.password omero.ldap.base omero.ldap.user_filter omero.ldap.user_mapping omero.ldap.group_filter omero.ldap.group_mapping omero.ldap.new_user_group """.split() cfg = dict() for key in LDAP_PROPERTIES: cfg[key.split(".")[-1]] = iconfig.getConfigValue(key) urls = args.urls and args.urls or cfg["urls"] basedn = args.base and args.base or cfg["base"] for url in urls.split(","): self.ctx.err("Connecting to %s..." % url) ld = ldap.initialize(url) ld.simple_bind_s(cfg['username'], cfg['password']) user_filter = cfg["user_filter"] user_mapping = cfg["user_mapping"] user_mapping = user_mapping.split(",") omeName_mapping = None for um in user_mapping: parts = um.split("=") if parts[0] == "omeName": omeName_mapping = parts[1] from ldap.controls import SimplePagedResultsControl cookie = '' # This is the limit for Active Directory, 1000. However # the LDAP connection has a sizeLimit that overrides # this value if the page_size exceeds it so it is safe # to enter pretty much anything here when using paged results. page_size = 1000 results = [] first = True page_control = SimplePagedResultsControl(False, page_size, cookie) while first or page_control.cookie: first = False try: msgid = ld.search_ext( basedn, ldap.SCOPE_SUBTREE, user_filter, serverctrls=[page_control] ) except: self.ctx.die(1, "Failed to execute LDAP search") result_type, results, msgid, serverctrls = ld.result3(msgid) if serverctrls: page_control.cookie = serverctrls[0].cookie user_names = set() user_dns = {} for dn, entry in results: omeName = entry[omeName_mapping] if isinstance(omeName, (list, tuple)): if len(omeName) == 1: omeName = omeName[0] user_names.add(omeName) user_dns[omeName] = dn else: self.ctx.err("Failed to unwrap omeName: %s" % omeName) continue if not user_names: continue # Early exit! from omero.rtypes import rlist from omero.rtypes import rstring from omero.rtypes import unwrap params = omero.sys.ParametersI() params.add("names", rlist([rstring(x) for x in user_names])) id_names = unwrap(iquery.projection( "select id, omeName from Experimenter " "where omeName in (:names)", params)) for eid, omeName in id_names: try: olddn = iadmin.lookupLdapAuthExperimenter(eid) dn = user_dns[omeName] except omero.ApiUsageException: continue # Unknown user if olddn: if olddn.lower() != dn.lower(): self.ctx.err("Found different DN for %s: %s" % (omeName, olddn)) else: self.ctx.dbg("DN already set for %s: %s" % (omeName, olddn)) else: if args.commands: self.ctx.out("%s ldap setdn %s %s" % (sys.argv[0], omeName, dn)) else: self.ctx.out("Experimenter:%s\tomeName=%s\t%s" % (eid, omeName, dn)) def create(self, args): c = self.ctx.conn(args) ildap = c.sf.getLdapService() iadmin = c.sf.getAdminService() import omero import Ice try: exp = ildap.createUser(args.username) dn = iadmin.lookupLdapAuthExperimenter(exp.id.val) self.ctx.out("Added user %s (id=%s) with DN=%s" % (exp.omeName.val, exp.id.val, dn)) except omero.SecurityViolation: self.ctx.die(131, "SecurityViolation: Admins only!") except omero.ValidationException as ve: self.ctx.die(132, ve.message) except Ice.RequestFailedException as rfe: self.ctx.die(133, self.exc.handle_failed_request(rfe))
class LdapControl(BaseControl): def _configure(self, parser): self.exc = ExceptionHandler() sub = parser.sub() active = parser.add( sub, self.active, help="Return code shows if LDAP is configured (admins-only)") list = parser.add(sub, self.list, help="List all OMERO users with DNs") list.add_style_argument() getdn = parser.add(sub, self.getdn, help="Get DN for user on stdout") setdn = parser.add(sub, self.setdn, help="""Set DN for user (admins only) Once the DN is set for a user, the password set via OMERO is ignored, and any attempt to change it will result in an error. When you remove the DN, the previous password will be in effect, but if the user never had a password, one will need to be set!""") for x in (getdn, setdn): x.add_argument("username", help="User's OMERO login name") setdn.add_argument( "dn", help="User's LDAP distinguished name. If empty, LDAP will" " be disabled for the user") discover = parser.add( sub, self.discover, help="Discover distinguished names for existing OMERO users") discover.add_argument("--commands", action="store_true", default=False, help="Print setdn commands on standard out") discover.add_argument("--urls", help="Override OMERO omero.ldap.urls setting") discover.add_argument("--base", help="Override OMERO omero.ldap.base setting") create = parser.add( sub, self.create, help="Create a local user based on LDAP username (admins only)") create.add_argument("username", help="LDAP username of user to be created") for x in (active, list, getdn, setdn, discover, create): x.add_login_arguments() def __import_ldap__(self): try: import ldap except: self.ctx.die(155, """Python "ldap" module is not installed""") return ldap def active(self, args): c = self.ctx.conn(args) ildap = c.sf.getLdapService() import omero try: if ildap.getSetting(): self.ctx.out("Yes") else: self.ctx.die(1, "No") except omero.SecurityViolation: self.error_admin_only(fatal=True) def list(self, args): c = self.ctx.conn(args) iadmin = c.sf.getAdminService() import omero from omero.rtypes import unwrap from omero.util.text import TableBuilder try: list_of_dn_user_maps = unwrap(iadmin.lookupLdapAuthExperimenters()) if list_of_dn_user_maps is None: return count = 0 tb = TableBuilder("#") if args.style: tb.set_style(args.style) tb.cols(["Id", "OmeName", "DN"]) for map in list_of_dn_user_maps: for dn, id in map.items(): try: exp = iadmin.getExperimenter(id) except: self.ctx.err("Bad experimenter: %s" % id) tb.row(count, *(id, exp.omeName.val, dn)) count += 1 self.ctx.out(str(tb.build())) except omero.SecurityViolation: self.error_admin_only(fatal=True) def getdn(self, args): c = self.ctx.conn(args) iadmin = c.sf.getAdminService() try: exp = iadmin.lookupExperimenter(args.username) except: self.ctx.die(134, "Unknown user: %s" % args.username) dn = iadmin.lookupLdapAuthExperimenter(exp.id.val) if dn is not None and dn.strip(): self.ctx.out(dn) else: self.ctx.die(136, "DN Not found: %s" % dn) def setdn(self, args): c = self.ctx.conn(args) ildap = c.sf.getLdapService() iadmin = c.sf.getAdminService() try: exp = iadmin.lookupExperimenter(args.username) except: self.ctx.die(134, "Unknown user: %s" % args.username) import omero try: ildap.setDN(exp.id, args.dn) except omero.SecurityViolation: self.error_admin_only(fatal=True) def discover(self, args): import omero ldap = self.__import_ldap__() c = self.ctx.conn(args) iconfig = c.sf.getConfigService() iadmin = c.sf.getAdminService() iquery = c.sf.getQueryService() LDAP_PROPERTIES = """ omero.ldap.urls omero.ldap.username omero.ldap.password omero.ldap.base omero.ldap.user_filter omero.ldap.user_mapping omero.ldap.group_filter omero.ldap.group_mapping omero.ldap.new_user_group """.split() cfg = dict() for key in LDAP_PROPERTIES: cfg[key.split(".")[-1]] = iconfig.getConfigValue(key) urls = args.urls and args.urls or cfg["urls"] basedn = args.base and args.base or cfg["base"] for url in urls.split(","): self.ctx.err("Connecting to %s..." % url) ld = ldap.initialize(url) ld.simple_bind_s(cfg['username'], cfg['password']) user_filter = cfg["user_filter"] user_mapping = cfg["user_mapping"] user_mapping = user_mapping.split(",") omeName_mapping = None for um in user_mapping: parts = um.split("=") if parts[0] == "omeName": omeName_mapping = parts[1] from ldap.controls import SimplePagedResultsControl cookie = '' # This is the limit for Active Directory, 1000. However # the LDAP connection has a sizeLimit that overrides # this value if the page_size exceeds it so it is safe # to enter pretty much anything here when using paged results. page_size = 1000 results = [] first = True page_control = SimplePagedResultsControl(False, page_size, cookie) while first or page_control.cookie: first = False try: msgid = ld.search_ext(basedn, ldap.SCOPE_SUBTREE, user_filter, serverctrls=[page_control]) except: self.ctx.die(1, "Failed to execute LDAP search") result_type, results, msgid, serverctrls = ld.result3(msgid) if serverctrls: page_control.cookie = serverctrls[0].cookie user_names = set() user_dns = {} for dn, entry in results: omeName = entry[omeName_mapping] if isinstance(omeName, (list, tuple)): if len(omeName) == 1: omeName = omeName[0] user_names.add(omeName) user_dns[omeName] = dn else: self.ctx.err("Failed to unwrap omeName: %s" % omeName) continue if not user_names: continue # Early exit! from omero.rtypes import rlist from omero.rtypes import rstring from omero.rtypes import unwrap params = omero.sys.ParametersI() params.add("names", rlist([rstring(x) for x in user_names])) id_names = unwrap( iquery.projection( "select id, omeName from Experimenter " "where omeName in (:names)", params)) for eid, omeName in id_names: try: olddn = iadmin.lookupLdapAuthExperimenter(eid) dn = user_dns[omeName] except omero.ApiUsageException: continue # Unknown user if olddn: if olddn.lower() != dn.lower(): self.ctx.err("Found different DN for %s: %s" % (omeName, olddn)) else: self.ctx.dbg("DN already set for %s: %s" % (omeName, olddn)) else: if args.commands: self.ctx.out("%s ldap setdn %s %s" % (sys.argv[0], omeName, dn)) else: self.ctx.out("Experimenter:%s\tomeName=%s\t%s" % (eid, omeName, dn)) def create(self, args): c = self.ctx.conn(args) ildap = c.sf.getLdapService() iadmin = c.sf.getAdminService() import omero import Ice try: exp = ildap.createUser(args.username) dn = iadmin.lookupLdapAuthExperimenter(exp.id.val) self.ctx.out("Added user %s (id=%s) with DN=%s" % (exp.omeName.val, exp.id.val, dn)) except omero.SecurityViolation: self.ctx.die(131, "SecurityViolation: Admins only!") except omero.ValidationException as ve: self.ctx.die(132, ve.message) except Ice.RequestFailedException as rfe: self.ctx.die(133, self.exc.handle_failed_request(rfe))