class Tool(ldapdb.models.Model): """A tool is a specially named LDAP group.""" base_dn = settings.TOOLS_TOOL_BASE_DN object_classes = ['posixGroup', 'groupOfNames'] objects = ToolManager() group_name = fields.CharField(db_column='cn', max_length=200, primary_key=True) gid = fields.IntegerField(db_column='gidNumber', unique=True) maintainer_ids = fields.ListField(db_column='member') @property def name(self): return self.group_name[6:] @name.setter def name(self, value): self.group_name = 'tools.{0!s}'.format(value) def maintainers(self): # OMG, this is horrible. You can't search LDAP by dn. return Maintainer.objects.filter( username__in=(dn.split(',')[0].split('=')[1] for dn in self.maintainer_ids)) def __str__(self): return self.name
class AbstractGroup(ldapdb.models.Model): class Meta: abstract = True object_classes = ['posixGroup'] gid = fields.IntegerField(db_column='gidNumber', unique=True) name = fields.CharField(db_column='cn', max_length=200, primary_key=True) usernames = fields.ListField(db_column='memberUid') def __str__(self): return self.name def __unicode__(self): return self.name
class LdapGroup(ldapdb.models.Model): """ Class for representing an LDAP group entry. """ # LDAP meta-data base_dn = "ou=groups,dc=example,dc=org" object_classes = ['posixGroup'] # posixGroup attributes gid = fields.IntegerField(db_column='gidNumber', unique=True) name = fields.CharField(db_column='cn', max_length=200, primary_key=True) usernames = fields.ListField(db_column='memberUid') def __str__(self): return self.name def __unicode__(self): return self.name
class CuLdapUser(LdapUser): class Meta: managed = False base_dn = settings.LDAPCONFS['culdap']['people_dn'] object_classes = [] uid = ldap_fields.IntegerField(db_column='uidNumber', unique=True) # Used for automatic determination of role and affiliation. edu_affiliation = ldap_fields.ListField(db_column='eduPersonAffiliation') edu_primary_affiliation = ldap_fields.CharField(db_column='eduPersonPrimaryAffiliation') cu_primary_major = ldap_fields.CharField(db_column='cuEduPersonPrimaryMajor1') cu_home_department = ldap_fields.CharField(db_column='cuEduPersonHomeDepartment') @sensitive_variables('pwd') def authenticate(self,pwd): authed = ldap_utils.authenticate(self.dn,pwd,'culdap') logger = logging.getLogger('accounts') logger.info('CU user {} auth attempt: {}'.format(self.username, authed)) return authed
class LdapGroup(ldapdb.models.Model): """ Class for representing an LDAP group entry. """ class Meta: verbose_name = "LDAP group" verbose_name_plural = "LDAP groups" # LDAP meta-data base_dn = settings.REG_GROUP_BASE_DN object_classes = settings.REG_GROUP_OBJECT_CLASSES # LDAP group attributes cn = ldapdb_fields.CharField(db_column="cn", max_length=200, primary_key=True) description = ldapdb_fields.CharField(db_column="description", max_length=200) members = ldapdb_fields.ListField(db_column="member") def __str__(self): return self.cn def __unicode__(self): return self.cn
class LdapGroup(Model): """ Class for representing an LDAP group entry. """ # LDAP meta-data ROOT_DN = os.environ.get('LDAP_USER_ENTRY', 'dc=test,dc=de') base_dn = ROOT_DN object_classes = ['groupOfNames'] name = ldap_fields.CharField(db_column='cn', max_length=200, primary_key=True) description = ldap_fields.CharField(db_column='description', max_length=1024) members = ldap_fields.ListField(db_column='member') @staticmethod def get_user_groups(realm: Realm, ldap_user: LdapUser): LdapUser.base_dn = f'ou=people,{realm.ldap_base_dn}' LdapGroup.base_dn = LdapGroup.ROOT_DN return LdapGroup.objects.filter(members=ldap_user.dn) @staticmethod def add_user_to_groups(ldap_user: LdapUser, ldap_groups: List): for ldap_group in ldap_groups: ldap_group.members.append(ldap_user.dn) ldap_group.save() @staticmethod def remove_user_from_groups(ldap_user_dn, user_groups=None): if not user_groups: LdapGroup.base_dn = LdapGroup.ROOT_DN user_groups = LdapGroup.objects.filter( members__contains=ldap_user_dn) for group in user_groups: LdapGroup.base_dn = re.compile( 'cn=([a-zA-Z0-9_-]*),(ou=[a-zA-Z_]*.*)').match( group.dn).group(2) group.members.remove(ldap_user_dn) group.save() def get_django_group(self): django_group, _ = Group.objects.get_or_create(name=self.name) return django_group @staticmethod def get_group(group_name: str, realm: Realm = None): LdapGroup.base_dn = f'ou=groups,{realm.ldap_base_dn}' if realm else LdapGroup.ROOT_DN try: return LdapGroup.objects.get(name=group_name) except Exception as e: logger.error(e) return None @staticmethod def get_groups(realm: Realm = None): LdapGroup.base_dn = f'ou=groups,{realm.ldap_base_dn}' if realm else LdapGroup.ROOT_DN try: return LdapGroup.objects.all() except Exception as e: logger.error(e) return None @staticmethod def set_root_dn(realm): LdapGroup.base_dn = f'ou=groups,{realm.ldap_base_dn}' def __str__(self): return self.name def __unicode__(self): return self.name
class RcLdapGroup(ldapdb.models.Model): class Meta: verbose_name = 'LDAP group' verbose_name_plural = 'LDAP groups' managed = False def __init__(self,*args,**kwargs): super(RcLdapGroup,self).__init__(*args,**kwargs) rdn = self.dn.lower().replace(self.base_dn.lower(), '') rdn_list = rdn.split(',') self.org = '' if len(rdn_list) > 1: ou = self.base_dn.lower().split(',')[0] __, org = ou.split('=') self.org = org self.base_dn = self.base_dn.lower() objects = RcLdapGroupManager() rdn_keys = ['name'] base_dn = settings.LDAPCONFS['rcldap']['group_dn'] object_classes = ['top','posixGroup'] # posixGroup attributes # gid = ldap_fields.IntegerField(db_column='gidNumber', unique=True) gid = ldap_fields.IntegerField(db_column='gidNumber',null=True,blank=True) name = ldap_fields.CharField(db_column='cn', max_length=200) members = ldap_fields.ListField(db_column='memberUid',blank=True,null=True) def __str__(self): return self.name def __str__(self): return self.name @property def organization(self): return self.org @property def effective_cn(self): suffixed_name = ldap_utils.get_suffixed_username(self.name,self.organization) return suffixed_name def _set_base_dn(self,org): if org in list(settings.ORGANIZATION_INFO.keys()): ou = 'ou={}'.format(org) self.org = org if ou not in self.base_dn.lower(): self.base_dn = ','.join([ou,self.base_dn]) else: raise ValueError('Invalid organization specified: {}'.format(org)) def save(self,*args,**kwargs): org = kwargs.pop('organization', None) if not org: raise ValueError('No organization specified.') self._set_base_dn(org) force_insert = kwargs.pop('force_insert',None) # If no GID specified, auto-assign if self.gid == None: id_tracker = IdTracker.objects.get(category='posix') gid = id_tracker.get_next_id() self.gid = gid logger = logging.getLogger('accounts') logger.info('Auto-assigned GID to group: {}, {}'.format(gid, self.name)) super(RcLdapGroup,self).save(*args,**kwargs)
class RcLdapUser(LdapUser): class Meta: verbose_name = 'LDAP user' verbose_name_plural = 'LDAP users' managed = False def __init__(self,*args,**kwargs): super(RcLdapUser,self).__init__(*args,**kwargs) rdn = self.dn.lower().replace(self.base_dn.lower(), '') rdn_list = rdn.split(',') self.org = '' if len(rdn_list) > 1: ou = self.base_dn.lower().split(',')[0] __, org = ou.split('=') self.org = org self.base_dn = self.base_dn.lower() objects = RcLdapUserManager() base_dn = str(settings.LDAPCONFS['rcldap']['people_dn']) object_classes = list(map(str, ['top','person','inetorgperson','posixaccount','curcPerson','shadowAccount'])) expires = ldap_fields.IntegerField(db_column='shadowExpire',blank=True,null=True) uid = ldap_fields.IntegerField(db_column='uidNumber',null=True,blank=True) gid = ldap_fields.IntegerField(db_column='gidNumber',null=True,blank=True) gecos = ldap_fields.CharField(db_column='gecos',default='') home_directory = ldap_fields.CharField(db_column='homeDirectory') login_shell = ldap_fields.CharField(db_column='loginShell', default='/bin/bash') #curcPerson attributes role = ldap_fields.ListField(db_column='curcRole',blank=True,null=True) affiliation = ldap_fields.ListField(db_column='curcAffiliation',blank=True,null=True) @property def organization(self): return self.org @property def effective_uid(self): suffixed_username = ldap_utils.get_suffixed_username(self.username,self.organization) return suffixed_username def _set_base_dn(self,org): if org in list(map(str, list(settings.ORGANIZATION_INFO.keys()))): ou = 'ou={}'.format(org) self.org = org if ou not in self.base_dn.lower(): self.base_dn = ','.join([ou,self.base_dn]) else: raise ValueError('Invalid organization specified: {}'.format(org)) def save(self,*args,**kwargs): org = str(kwargs.pop('organization', None)) if not org: raise ValueError('No organization specified.') self._set_base_dn(org) # If no UID/GID specified, auto-assign logger = logging.getLogger('accounts') if (self.uid == None) and (self.gid == None): id_tracker = IdTracker.objects.get(category='posix') uid = id_tracker.get_next_id() self.uid = uid self.gid = uid logger.info('Auto-assigning UID and GID to user: {}, {}'.format(uid, self.effective_uid)) elif self.uid == None: self.uid = self.gid logger.info('Auto-assigning UID to user: {}, {}'.format(self.gid, self.effective_uid)) elif self.gid == None: self.gid = self.uid logger.info('Auto-assigning GID to user: {}, {}'.format(self.uid, self.effective_uid)) super(RcLdapUser,self).save(*args,**kwargs)