def add(self, data): # msg: {key: value} msg = {} self.domain = web.safestr(data.get('domainName', '')).strip().lower() # Check domain name. if not iredutils.is_domain(self.domain): return (False, 'INVALID_DOMAIN_NAME') # Check whether domain name already exist (domainName, domainAliasName). connutils = connUtils.Utils() if connutils.is_domain_exists(self.domain): return (False, 'ALREADY_EXISTS') self.dn = ldaputils.convert_keyword_to_dn(self.domain, accountType='domain') if self.dn[0] is False: return self.dn self.cn = data.get('cn', None) ldif = iredldif.ldif_maildomain(domain=self.domain, cn=self.cn,) # Add domain dn. try: self.conn.add_s(self.dn, ldif) web.logger(msg="Create domain: %s." % (self.domain), domain=self.domain, event='create',) except ldap.ALREADY_EXISTS: msg[self.domain] = 'ALREADY_EXISTS' except ldap.LDAPError, e: msg[self.domain] = str(e)
def enableOrDisableAccount( self, domains, action, attr='accountStatus', ): if domains is None or len(domains) == 0: return (False, 'NO_DOMAIN_SELECTED') result = {} connutils = connUtils.Utils() for domain in domains: self.domain = web.safestr(domain) self.dn = ldaputils.convert_keyword_to_dn(self.domain, accountType='domain') if self.dn[0] is False: return self.dn try: connutils.enableOrDisableAccount( domain=self.domain, account=self.domain, dn=self.dn, action=web.safestr(action).strip().lower(), accountTypeInLogger='domain', ) except ldap.LDAPError, e: result[self.domain] = str(e)
def getNumberOfManagedAccounts(self, admin=None, accountType='domain', domains=[],): if admin is None: admin = session.get('username') else: admin = str(admin) if not iredutils.is_email(admin): return 0 domains = [] if len(domains) > 0: domains = [str(d).lower() for d in domains if iredutils.is_domain(d)] else: connutils = connUtils.Utils() qr = connutils.getManagedDomains(mail=admin, attrs=['domainName'], listedOnly=True) if qr[0] is True: domains = qr[1] if accountType == 'domain': try: return len(domains) except Exception: pass return 0
def listAccounts(self, domain): self.domain = domain self.domainDN = ldaputils.convert_keyword_to_dn(self.domain, accountType='domain') if self.domainDN[0] is False: return self.domainDN try: # Use '(!([email protected]))' to hide catch-all account. self.users = self.conn.search_s( attrs.DN_BETWEEN_USER_AND_DOMAIN + self.domainDN, ldap.SCOPE_SUBTREE, '(&(objectClass=mailUser)(!(mail=@%s)))' % self.domain, attrs.USER_SEARCH_ATTRS, ) connutils = connUtils.Utils() connutils.updateAttrSingleValue(self.domainDN, 'domainCurrentUserNumber', len(self.users)) return (True, self.users) except ldap.NO_SUCH_OBJECT: #self.conn.add_s( # attrs.DN_BETWEEN_USER_AND_DOMAIN + self.domainDN, # iredldif.ldif_group(attrs.GROUP_USERS), # ) return (False, 'NO_SUCH_OBJECT') except ldap.SIZELIMIT_EXCEEDED: return (False, 'EXCEEDED_LDAP_SERVER_SIZELIMIT') except Exception, e: return (False, ldaputils.getExceptionDesc(e))
def enableOrDisableAccount( self, mails, action, attr='accountStatus', ): if mails is None or len(mails) == 0: return (False, 'NO_ACCOUNT_SELECTED') result = {} connutils = connUtils.Utils() for mail in mails: self.mail = web.safestr(mail).strip().lower() if not iredutils.isEmail(self.mail): continue self.domain = self.mail.split('@')[-1] self.dn = ldaputils.convKeywordToDN(self.mail, accountType='admin') try: connutils.enableOrDisableAccount( domain=self.domain, account=self.mail, dn=self.dn, action=web.safestr(action).strip().lower(), accountTypeInLogger='admin', ) except ldap.LDAPError, e: result[self.mail] = str(e)
def enableOrDisableAccount(self, mails, action, attr='accountStatus',): if mails is None or len(mails) == 0: return (False, 'NO_ACCOUNT_SELECTED') result = {} connutils = connUtils.Utils() for mail in mails: self.mail = web.safestr(mail).strip().lower() if not iredutils.is_email(self.mail): continue self.domain = self.mail.split('@')[-1] self.dn = ldaputils.convert_keyword_to_dn(self.mail, accountType='admin') if self.dn[0] is False: return self.dn try: connutils.enableOrDisableAccount( domain=self.domain, account=self.mail, dn=self.dn, action=web.safestr(action).strip().lower(), accountTypeInLogger='admin', ) except ldap.LDAPError as e: result[self.mail] = str(e) if result == {}: return (True,) else: return (False, ldaputils.getExceptionDesc(result))
def GET(self, cur_page=1): i = web.input() cur_page = int(cur_page) if cur_page == 0: cur_page == 1 adminLib = admin.Admin() result = adminLib.listAccounts() connutils = connUtils.Utils() sl = connutils.getSizelimitFromAccountLists( result[1], curPage=cur_page, sizelimit=session['pageSizeLimit'], ) if cur_page > sl.get('totalPages', 0): cur_page = sl.get('totalPages', 0) return web.render( 'ldap/admin/list.html', cur_page=cur_page, total=sl.get('totalAccounts'), admins=sl.get('accountList'), msg=i.get('msg', None), )
def deleteSingleUserFromGroups(self, mail): self.mail = web.safestr(mail) if not iredutils.is_email(self.mail): return (False, 'INVALID_MAIL') # Get domain name of this account. self.domain = self.mail.split('@')[-1] # Get dn of mail user and domain. self.dnUser = ldaputils.convert_keyword_to_dn(self.mail, accountType='user') self.dnDomain = ldaputils.convert_keyword_to_dn(self.domain, accountType='domain') if self.dnUser[0] is False: return self.dnUser if self.dnDomain[0] is False: return self.dnDomain try: # Get accounts which contains destination email. objsHasUser = self.conn.search_s( self.dnDomain, ldap.SCOPE_SUBTREE, self.getFilterOfDeleteUserFromGroups(self.mail), ['dn'], ) if len(objsHasUser) >= 1: connutils = connUtils.Utils() for obj in objsHasUser: if obj[0].endswith(attrs.DN_BETWEEN_ALIAS_AND_DOMAIN + self.dnDomain) or \ obj[0].endswith(attrs.DN_BETWEEN_USER_AND_DOMAIN + self.dnDomain): # Remove address from alias and user. connutils.addOrDelAttrValue( dn=obj[0], attr='mailForwardingAddress', value=self.mail, action='delete', ) elif obj[0].endswith('ou=Externals,' + self.domaindn): # Remove address from external member list. connutils.addOrDelAttrValue( dn=obj[0], attr='mail', value=self.mail, action='delete', ) else: pass else: pass return (True, ) except Exception, e: return (False, ldaputils.getExceptionDesc(e))
def add(self, data): # msg: {key: value} msg = {} self.domain = web.safestr(data.get('domainName', '')).strip().lower() # Check domain name. if not iredutils.is_domain(self.domain): return (False, 'INVALID_DOMAIN_NAME') # Check whether domain name already exist (domainName, domainAliasName). connutils = connUtils.Utils() if connutils.is_domain_exists(self.domain): return (False, 'ALREADY_EXISTS') self.dn = ldaputils.convert_keyword_to_dn(self.domain, accountType='domain') if self.dn[0] is False: return self.dn self.cn = data.get('cn', None) ldif = iredldif.ldif_maildomain( domain=self.domain, cn=self.cn, ) # Add domain dn. try: self.conn.add_s(self.dn, ldif) web.logger( msg="Create domain: %s." % (self.domain), domain=self.domain, event='create', ) except ldap.ALREADY_EXISTS: msg[self.domain] = 'ALREADY_EXISTS' except ldap.LDAPError as e: msg[self.domain] = str(e) # Add default groups under domain. if len(attrs.DEFAULT_GROUPS) >= 1: for i in attrs.DEFAULT_GROUPS: try: group_dn = 'ou=' + str(i) + ',' + str(self.dn) group_ldif = iredldif.ldif_group(str(i)) self.conn.add_s(group_dn, group_ldif) except ldap.ALREADY_EXISTS: pass except ldap.LDAPError as e: msg[i] = str(e) else: pass if len(msg) == 0: return (True, ) else: return (False, ldaputils.getExceptionDesc(msg))
def GET(self, domain='', cur_page=1): domain = web.safestr(domain).split('/', 1)[0] cur_page = int(cur_page) if not iredutils.is_domain(domain): raise web.seeother('/domains?msg=INVALID_DOMAIN_NAME') if cur_page == 0: cur_page = 1 i = web.input() domainLib = domainlib.Domain() result = domainLib.listAccounts(attrs=[ 'domainName', 'accountStatus', ]) if result[0] is True: allDomains = result[1] else: return result userLib = user.User() result = userLib.listAccounts(domain=domain) if result[0] is True: connutils = connUtils.Utils() sl = connutils.getSizelimitFromAccountLists( result[1], curPage=cur_page, sizelimit=settings.PAGE_SIZE_LIMIT, accountType='user', domain=domain, ) accountList = sl.get('accountList', []) if cur_page > sl.get('totalPages'): cur_page = sl.get('totalPages') return web.render( 'ldap/user/list.html', cur_page=cur_page, total=sl.get('totalAccounts'), users=accountList, cur_domain=domain, allDomains=allDomains, accountUsedQuota={}, msg=i.get('msg'), ) else: raise web.seeother('/domains?msg=%s' % web.urlquote(result[1]))
def update(self, profile_type, domain, data): self.profile_type = web.safestr(profile_type) self.domain = web.safestr(domain) self.domaindn = ldaputils.convert_keyword_to_dn(self.domain, accountType='domain') if self.domaindn[0] is False: return self.domaindn connutils = connUtils.Utils() self.accountSetting = [] mod_attrs = [] # Allow normal admin to update profiles. if self.profile_type == 'general': cn = data.get('cn', None) mod_attrs += ldaputils.getSingleModAttr(attr='cn', value=cn, default=self.domain) # Allow global admin to update profiles. if session.get('domainGlobalAdmin') is True: if self.profile_type == 'general': # Get accountStatus. if 'accountStatus' in data.keys(): accountStatus = 'active' else: accountStatus = 'disabled' mod_attrs += [(ldap.MOD_REPLACE, 'accountStatus', accountStatus)] try: dn = ldaputils.convert_keyword_to_dn(self.domain, accountType='domain') if dn[0] is False: return dn self.conn.modify_s(dn, mod_attrs) web.logger( msg="Update domain profile: %s (%s)." % (domain, profile_type), domain=domain, event='update', ) return (True, ) except Exception, e: return (False, ldaputils.getExceptionDesc(e))
def update(self, profile_type, mail, data): self.profile_type = web.safestr(profile_type) self.mail = str(mail).lower() self.domain = self.mail.split('@', 1)[-1] domainAccountSetting = {} connutils = connUtils.Utils() domainLib = domainlib.Domain() # Get account dn. self.dn = connutils.getDnWithKeyword(self.mail, accountType='user') try: result = domainLib.getDomainAccountSetting(domain=self.domain) if result[0] is True: domainAccountSetting = result[1] except Exception, e: pass
def delete(self, mails): if mails is None or len(mails) == 0: return (False, 'NO_ACCOUNT_SELECTED') result = {} for mail in mails: self.mail = web.safestr(mail) dn = ldaputils.convert_keyword_to_dn(self.mail, accountType='admin') if dn[0] is False: return dn try: deltree.DelTree(self.conn, dn, ldap.SCOPE_SUBTREE) web.logger( msg="Delete admin: %s." % (self.mail, ), event='delete', ) except ldap.NO_SUCH_OBJECT: # This is a mail user admin dn = ldaputils.convert_keyword_to_dn(self.mail, accountType='user') try: connutils = connUtils.Utils() # Delete enabledService=domainadmin connutils.addOrDelAttrValue(dn=dn, attr='enabledService', value='domainadmin', action='delete') # Delete domainGlobalAdmin=yes connutils.addOrDelAttrValue(dn=dn, attr='domainGlobalAdmin', value='yes', action='delete') web.logger(msg="Delete admin: %s." % (self.mail), event='delete') except Exception, e: result[self.mail] = str(e) except ldap.LDAPError, e: result[self.mail] = str(e)
def enableOrDisableAccount(self, domain, mails, action, attr='accountStatus'): if mails is None or len(mails) == 0: return (False, 'NO_ACCOUNT_SELECTED') self.mails = [ str(v) for v in mails if iredutils.is_email(v) and str(v).endswith('@' + str(domain)) ] result = {} connutils = connUtils.Utils() for mail in self.mails: self.mail = web.safestr(mail) if not iredutils.is_email(self.mail): continue self.domain = self.mail.split('@')[-1] self.dn = ldaputils.convert_keyword_to_dn(self.mail, accountType='user') if self.dn[0] is False: result[self.mail] = self.dn[1] continue try: connutils.enableOrDisableAccount( domain=self.domain, account=self.mail, dn=self.dn, action=web.safestr(action).strip().lower(), accountTypeInLogger='user', ) except ldap.LDAPError as e: result[self.mail] = str(e) if result == {}: return (True, ) else: return (False, str(result))
def GET(self, cur_page=1): i = web.input() cur_page = int(cur_page) if cur_page == 0: cur_page == 1 domainLib = domainlib.Domain() result = domainLib.listAccounts() if result[0] is True: allDomains = result[1] # Get value of accountSetting. allAccountSettings = ldaputils.getAccountSettingFromLdapQueryResult( allDomains, key='domainName', ) else: return result connutils = connUtils.Utils() sl = connutils.getSizelimitFromAccountLists( allDomains, curPage=cur_page, sizelimit=session.get('pageSizeLimit', 50), ) if cur_page > sl.get('totalPages'): cur_page = sl.get('totalPages') return web.render( 'ldap/domain/list.html', cur_page=cur_page, total=sl.get('totalAccounts'), allDomains=sl.get('accountList'), allAccountSettings=allAccountSettings, msg=i.get('msg', None), )
def GET(self, domainName=None): i = web.input() if domainName is None: self.cur_domain = '' else: self.cur_domain = web.safestr(domainName) domainLib = domainlib.Domain() result = domainLib.listAccounts(attrs=[ 'domainName', 'accountSetting', 'domainCurrentQuotaSize', ]) if result[0] is True: allDomains = result[1] if len(allDomains) == 0: raise web.seeother('/domains?msg=NO_DOMAIN_AVAILABLE') else: # Redirect to create new user under first domain, so that we # can get per-domain account settings, such as number of # account limit, password length control, etc. if self.cur_domain == '': raise web.seeother('/create/user/' + str(allDomains[0][1]['domainName'][0])) # Get accountSetting of current domain. allAccountSettings = ldaputils.getAccountSettingFromLdapQueryResult( allDomains, key='domainName') domainAccountSetting = allAccountSettings.get(self.cur_domain, {}) defaultUserQuota = domainLib.getDomainDefaultUserQuota( self.cur_domain, domainAccountSetting) else: raise web.seeother('/domains?msg=' % web.urlquote(result[1])) # Get number of account limit. connutils = connUtils.Utils() result = connutils.getNumberOfCurrentAccountsUnderDomain( self.cur_domain, accountType='user', ) if result[0] is True: numberOfCurrentAccounts = result[1] else: numberOfCurrentAccounts = 0 # Get current domain quota size. result = connutils.getDomainCurrentQuotaSizeFromLDAP( domain=self.cur_domain) if result[0] is True: domainCurrentQuotaSize = result[1] else: # -1 means temporary error. Don't allow to create new user. domainCurrentQuotaSize = -1 return web.render('ldap/user/create.html', cur_domain=self.cur_domain, allDomains=allDomains, defaultUserQuota=defaultUserQuota, domainAccountSetting=domainAccountSetting, numberOfCurrentAccounts=numberOfCurrentAccounts, domainCurrentQuotaSize=domainCurrentQuotaSize, msg=i.get('msg'))
def update(self, profile_type, mail, data): self.profile_type = web.safestr(profile_type) self.mail = str(mail).lower() self.username, self.domain = self.mail.split('@', 1) domainAccountSetting = {} connutils = connUtils.Utils() domainLib = domainlib.Domain() # Get account dn. self.dn = connutils.getDnWithKeyword(self.mail, accountType='user') try: result = domainLib.getDomainAccountSetting(domain=self.domain) if result[0] is True: domainAccountSetting = result[1] except Exception as e: pass mod_attrs = [] if self.profile_type == 'general': # Update domainGlobalAdmin=yes if session.get('domainGlobalAdmin') is True: # Update domainGlobalAdmin=yes if 'domainGlobalAdmin' in data: mod_attrs = [(ldap.MOD_REPLACE, 'domainGlobalAdmin', 'yes') ] # Update enabledService=domainadmin connutils.addOrDelAttrValue( dn=self.dn, attr='enabledService', value='domainadmin', action='add', ) else: mod_attrs = [(ldap.MOD_REPLACE, 'domainGlobalAdmin', None)] # Remove enabledService=domainadmin connutils.addOrDelAttrValue( dn=self.dn, attr='enabledService', value='domainadmin', action='delete', ) # Get display name. cn = data.get('cn', None) mod_attrs += ldaputils.getSingleModAttr(attr='cn', value=cn, default=self.username) first_name = data.get('first_name', '') mod_attrs += ldaputils.getSingleModAttr(attr='givenName', value=first_name, default=self.username) last_name = data.get('last_name', '') mod_attrs += ldaputils.getSingleModAttr(attr='sn', value=last_name, default=self.username) # Get preferred language: short lang code. e.g. en_US, de_DE. preferred_lang = web.safestr(data.get('preferredLanguage', 'en_US')) # Must be equal to or less than 5 characters. if len(preferred_lang) > 5: preferred_lang = preferred_lang[:5] mod_attrs += [(ldap.MOD_REPLACE, 'preferredLanguage', preferred_lang)] # Update language immediately. if session.get('username') == self.mail and \ session.get('lang', 'en_US') != preferred_lang: session['lang'] = preferred_lang # Update employeeNumber, mobile, title. for tmp_attr in [ 'employeeNumber', 'mobile', 'title', ]: mod_attrs += ldaputils.getSingleModAttr( attr=tmp_attr, value=data.get(tmp_attr), default=None) ############ # Get quota # Get mail quota from web form. quota = web.safestr(data.get('mailQuota', '')).strip() oldquota = web.safestr(data.get('oldMailQuota', '')).strip() if not oldquota.isdigit(): oldquota = 0 else: oldquota = int(oldquota) if quota == '' or not quota.isdigit(): # Don't touch it, keep original value. pass else: # Assign quota which got from web form. mailQuota = int(quota) # If mailQuota > domainSpareQuotaSize, use domainSpareQuotaSize. # if mailQuota < domainSpareQuotaSize, use mailQuota # 0 means unlimited. domainQuotaSize, domainQuotaUnit = domainAccountSetting.get( 'domainQuota', '0:GB').split(':') if int(domainQuotaSize) == 0: # Unlimited. Keep quota which got from web form. mod_attrs += [(ldap.MOD_REPLACE, 'mailQuota', str(mailQuota * 1024 * 1024))] else: # Get domain quota. if domainQuotaUnit == 'TB': domainQuota = int(domainQuotaSize) * 1024 * 1024 # TB elif domainQuotaUnit == 'GB': domainQuota = int(domainQuotaSize) * 1024 # GB else: domainQuota = int(domainQuotaSize) # MB # Query LDAP and get current domain quota size. result = connutils.getDomainCurrentQuotaSizeFromLDAP( domain=self.domain) if result[0] is True: domainCurrentQuotaSizeInBytes = result[1] else: domainCurrentQuotaSizeInBytes = 0 # Spare quota. domainSpareQuotaSize = (domainQuota + oldquota) - ( domainCurrentQuotaSizeInBytes / (1024 * 1024)) if domainSpareQuotaSize <= 0: # Set to 1MB. don't exceed domain quota size. mod_attrs += [(ldap.MOD_REPLACE, 'mailQuota', str(1024 * 1024))] else: # Get FINAL mailbox quota. if mailQuota >= domainSpareQuotaSize: mailQuota = domainSpareQuotaSize mod_attrs += [(ldap.MOD_REPLACE, 'mailQuota', str(mailQuota * 1024 * 1024))] # End quota ############ # Get telephoneNumber. telephoneNumber = data.get('telephoneNumber', []) nums = [str(num) for num in telephoneNumber if len(num) > 0] mod_attrs += [(ldap.MOD_REPLACE, 'telephoneNumber', nums)] # Get accountStatus. if 'accountStatus' in list(data.keys()): accountStatus = 'active' else: accountStatus = 'disabled' mod_attrs += [(ldap.MOD_REPLACE, 'accountStatus', accountStatus)] elif self.profile_type == 'password': # Get password length from @domainAccountSetting. minPasswordLength = domainAccountSetting.get( 'minPasswordLength', settings.min_passwd_length) maxPasswordLength = domainAccountSetting.get( 'maxPasswordLength', settings.max_passwd_length) # Get new passwords from user input. self.newpw = str(data.get('newpw', None)) self.confirmpw = str(data.get('confirmpw', None)) result = iredutils.verify_new_password( newpw=self.newpw, confirmpw=self.confirmpw, min_passwd_length=minPasswordLength, max_passwd_length=maxPasswordLength, ) if result[0] is True: if 'storePasswordInPlainText' in data and settings.STORE_PASSWORD_IN_PLAIN_TEXT: self.passwd = iredutils.generate_password_hash( result[1], pwscheme='PLAIN') else: self.passwd = iredutils.generate_password_hash(result[1]) mod_attrs += [(ldap.MOD_REPLACE, 'userPassword', self.passwd)] mod_attrs += [(ldap.MOD_REPLACE, 'shadowLastChange', str(ldaputils.getDaysOfShadowLastChange()))] else: return result try: self.conn.modify_s(self.dn, mod_attrs) return (True, ) except Exception as e: return (False, ldaputils.getExceptionDesc(e))
def update(self, profile_type, mail, data): self.profile_type = web.safestr(profile_type) self.mail = web.safestr(mail) if session.get('domainGlobalAdmin' ) is not True and session.get('username') != self.mail: # Don't allow to view/update other admins' profile. return (False, 'PERMISSION_DENIED') self.dn = ldaputils.convKeywordToDN(self.mail, accountType='admin') mod_attrs = [] if self.profile_type == 'general': # Get preferredLanguage. self.lang = web.safestr(data.get('preferredLanguage', 'en_US')) mod_attrs += [(ldap.MOD_REPLACE, 'preferredLanguage', self.lang)] # Get cn. cn = data.get('cn', None) mod_attrs += ldaputils.getSingleModAttr( attr='cn', value=cn, default=self.mail.split('@')[0], ) # Get accountStatus. if 'accountStatus' in data.keys(): accountStatus = 'active' else: accountStatus = 'disabled' mod_attrs += [(ldap.MOD_REPLACE, 'accountStatus', accountStatus)] try: # Modify profiles. self.conn.modify_s(self.dn, mod_attrs) if session.get('username') == self.mail: session['lang'] = self.lang except ldap.LDAPError, e: return (False, ldaputils.getExceptionDesc(e)) ######################### # Managed domains # if session.get('domainGlobalAdmin') is not True: return (False, 'PERMISSION_DENIED') # Get domains under control. result = self.getManagedDomains(mail=self.mail, attrs=[ 'domainName', ]) if result[0] is True: self.managedDomains = [] for d in result[1]: if 'domainName' in d[1].keys(): self.managedDomains += d[1].get('domainName') else: return result # Get domains from web form. self.newmd = [ web.safestr(v) for v in data.get('domainName', []) if iredutils.isDomain(v) ] # Compare two lists, get domain list which need to remove or add domain admins. self.domainsRemoveAdmins = [ str(v) for v in self.managedDomains if v not in self.newmd and iredutils.isDomain(v) ] self.domainsAddAdmins = [ str(v) for v in self.newmd if v not in self.managedDomains and iredutils.isDomain(v) ] connutils = connUtils.Utils() for i in self.domainsRemoveAdmins: result = connutils.addOrDelAttrValue( dn=ldaputils.convKeywordToDN(i, accountType='domain'), attr='domainAdmin', value=self.mail, action='delete', ) if result[0] is False: return result for i in self.domainsAddAdmins: result = connutils.addOrDelAttrValue( dn=ldaputils.convKeywordToDN(i, accountType='domain'), attr='domainAdmin', value=self.mail, action='add', ) if result[0] is False: return result return (True, )
result = iredutils.verifyNewPasswords(self.newpw, self.confirmpw) if result[0] is True: self.passwd = result[1] else: return result # Change password. if self.cur_passwd is None and session.get( 'domainGlobalAdmin') is True: # Reset password without verify old password. self.cur_passwd = None else: self.cur_passwd = str(self.cur_passwd) connutils = connUtils.Utils() result = connutils.changePasswd( dn=self.dn, cur_passwd=self.cur_passwd, newpw=self.passwd, ) if result[0] is True: return (True, ) else: return result @decorators.require_global_admin def delete(self, mails): if mails is None or len(mails) == 0: return (False, 'NO_ACCOUNT_SELECTED')
def add(self, domain, data): # Get domain name, username, cn. self.domain = web.safestr(data.get('domainName')).strip().lower() self.username = web.safestr(data.get('username')).strip().lower() self.mail = self.username + '@' + self.domain self.groups = data.get('groups', []) if not iredutils.isDomain(self.domain) or not iredutils.isEmail( self.mail): return (False, 'MISSING_DOMAIN_OR_USERNAME') # Check account existing. connutils = connUtils.Utils() if connutils.isAccountExists(domain=self.domain, filter='(mail=%s)' % self.mail): return (False, 'ALREADY_EXISTS') # Get @domainAccountSetting. domainLib = domainlib.Domain() result_domain_profile = domainLib.profile(self.domain) # Initial parameters. domainAccountSetting = {} self.aliasDomains = [] if result_domain_profile[0] is True: domainProfile = result_domain_profile[1] domainAccountSetting = ldaputils.getAccountSettingFromLdapQueryResult( domainProfile, key='domainName').get(self.domain, {}) self.aliasDomains = domainProfile[0][1].get('domainAliasName', []) # Check password. self.newpw = web.safestr(data.get('newpw')) self.confirmpw = web.safestr(data.get('confirmpw')) result = iredutils.verifyNewPasswords( self.newpw, self.confirmpw, min_passwd_length=domainAccountSetting.get('minPasswordLength', '0'), max_passwd_length=domainAccountSetting.get('maxPasswordLength', '0'), ) if result[0] is True: self.passwd = ldaputils.generatePasswd(result[1]) else: return result # Get display name. self.cn = data.get('cn') # Get user quota. Unit is MB. # 0 or empty is not allowed if domain quota is set, set to # @defaultUserQuota or @domainSpareQuotaSize # Initial final mailbox quota. self.quota = 0 # Get mail quota from web form. defaultUserQuota = domainLib.getDomainDefaultUserQuota( self.domain, domainAccountSetting) self.mailQuota = str(data.get('mailQuota')).strip() if self.mailQuota.isdigit(): self.mailQuota = int(self.mailQuota) else: self.mailQuota = defaultUserQuota # 0 means unlimited. domainQuotaSize, domainQuotaUnit = domainAccountSetting.get( 'domainQuota', '0:GB').split(':') if int(domainQuotaSize) == 0: # Unlimited. self.quota = self.mailQuota else: # Get domain quota, convert to MB. if domainQuotaUnit == 'TB': domainQuota = int(domainQuotaSize) * 1024 * 1024 # TB elif domainQuotaUnit == 'GB': domainQuota = int(domainQuotaSize) * 1024 # GB else: domainQuota = int(domainQuotaSize) # MB # TODO Query whole domain and calculate current quota size, not read from domain profile. #domainCurrentQuotaSize = int(domainProfile[0][1].get('domainCurrentQuotaSize', ['0'])[0]) / (1024*1024) result = connutils.getDomainCurrentQuotaSizeFromLDAP( domain=self.domain) if result[0] is True: domainCurrentQuotaSize = result[1] else: domainCurrentQuotaSize = 0 # Spare quota. domainSpareQuotaSize = domainQuota - domainCurrentQuotaSize / ( 1024 * 1024) if domainSpareQuotaSize <= 0: return (False, 'EXCEEDED_DOMAIN_QUOTA_SIZE') # Get FINAL mailbox quota. if self.mailQuota == 0: self.quota = domainSpareQuotaSize else: if domainSpareQuotaSize > self.mailQuota: self.quota = self.mailQuota else: self.quota = domainSpareQuotaSize # Get default groups. self.groups = [ web.safestr(v) for v in domainAccountSetting.get('defaultList', '').split(',') if iredutils.isEmail(v) ] self.defaultStorageBaseDirectory = domainAccountSetting.get( 'defaultStorageBaseDirectory', None) # Get default mail list which set in domain accountSetting. ldif = iredldif.ldif_mailuser( domain=self.domain, aliasDomains=self.aliasDomains, username=self.username, cn=self.cn, passwd=self.passwd, quota=self.quota, groups=self.groups, storageBaseDirectory=self.defaultStorageBaseDirectory, ) if attrs.RDN_USER == 'mail': self.dn = ldaputils.convKeywordToDN(self.mail, accountType='user') elif attrs.RDN_USER == 'cn': self.dn = 'cn=' + self.cn + ',' + attrs.DN_BETWEEN_USER_AND_DOMAIN + \ ldaputils.convKeywordToDN(self.domain, accountType='domain') elif attrs.RDN_USER == 'uid': self.dn = 'uid=' + self.username + ',' + attrs.DN_BETWEEN_USER_AND_DOMAIN + \ ldaputils.convKeywordToDN(self.domain, accountType='domain') else: return (False, 'UNSUPPORTED_USER_RDN') try: self.conn.add_s( ldap.filter.escape_filter_chars(self.dn), ldif, ) web.logger( msg="Create user: %s." % (self.mail), domain=self.domain, event='create', ) return (True, ) except ldap.ALREADY_EXISTS: return (False, 'ALREADY_EXISTS') except Exception, e: return (False, ldaputils.getExceptionDesc(e))
def GET(self): i = web.input(_unicode=False, ) # Get queries. self.event = web.safestr(i.get('event', 'all')) self.domain = web.safestr(i.get('domain', 'all')) self.admin = web.safestr(i.get('admin', 'all')) self.cur_page = web.safestr(i.get('page', '1')) if not self.cur_page.isdigit() or self.cur_page == '0': self.cur_page = 1 else: self.cur_page = int(self.cur_page) logLib = loglib.Log() total, entries = logLib.listLogs( event=self.event, domain=self.domain, admin=self.admin, cur_page=self.cur_page, ) # Pre-defined allDomains = [] allAdmins = [] if cfg.general.backend == 'ldap': # Get all managed domains under control. connutils = connUtils.Utils() qr = connutils.getManagedDomains( mail=session.get('username'), attrs=['domainName'], ) if qr[0] is True: allDomains = [ str(v[1]['domainName'][0]).lower() for v in qr[1] ] # Get all admins. if session.get('domainGlobalAdmin') is True: adminLib = adminlib.Admin() result = adminLib.listAccounts(attrs=['mail']) if result[0] is not False: allAdmins = [v[1]['mail'][0] for v in result[1]] else: allAdmins = [self.admin] elif cfg.general.backend in [ 'mysql', 'dbmail_mysql', ]: # Get all managed domains under control. connutils = connUtils.Utils() qr = connutils.getManagedDomains( admin=session.get('username'), domainNameOnly=True, ) if qr[0] is True: allDomains = qr[1] # Get all admins. if session.get('domainGlobalAdmin') is True: adminLib = adminlib.Admin() qr = adminLib.getAllAdmins(columns=['username']) if qr[0] is True: for r in qr[1]: allAdmins += [r.username] else: allAdmins = [self.admin] return web.render( 'panel/log.html', event=self.event, domain=self.domain, admin=self.admin, allEvents=LOG_EVENTS, cur_page=self.cur_page, total=total, entries=entries, allDomains=allDomains, allAdmins=allAdmins, msg=i.get('msg'), )
def update(self, profile_type, mail, data): self.profile_type = web.safestr(profile_type) self.mail = web.safestr(mail) self.username, self.domain = self.mail.split('@', 1) if session.get('domainGlobalAdmin') is not True and session.get('username') != self.mail: # Don't allow to view/update other admins' profile. return (False, 'PERMISSION_DENIED') self.dn = ldaputils.convert_keyword_to_dn(self.mail, accountType='admin') if self.dn[0] is False: return self.dn mod_attrs = [] if self.profile_type == 'general': # Get preferredLanguage. lang = web.safestr(data.get('preferredLanguage', 'en_US')) mod_attrs += [(ldap.MOD_REPLACE, 'preferredLanguage', lang)] # Get cn. cn = data.get('cn', None) mod_attrs += ldaputils.getSingleModAttr(attr='cn', value=cn, default=self.username) first_name = data.get('first_name', '') mod_attrs += ldaputils.getSingleModAttr(attr='givenName', value=first_name, default=self.username) last_name = data.get('last_name', '') mod_attrs += ldaputils.getSingleModAttr(attr='sn', value=last_name, default=self.username) # Get accountStatus. if 'accountStatus' in list(data.keys()): accountStatus = 'active' else: accountStatus = 'disabled' mod_attrs += [(ldap.MOD_REPLACE, 'accountStatus', accountStatus)] try: # Modify profiles. self.conn.modify_s(self.dn, mod_attrs) if session.get('username') == self.mail and \ session.get('lang', 'en_US') != lang: session['lang'] = lang except ldap.LDAPError as e: return (False, ldaputils.getExceptionDesc(e)) elif self.profile_type == 'password': self.cur_passwd = data.get('oldpw', None) self.newpw = web.safestr(data.get('newpw')) self.confirmpw = web.safestr(data.get('confirmpw')) result = iredutils.verify_new_password(self.newpw, self.confirmpw) if result[0] is True: self.passwd = result[1] else: return result # Change password. if self.cur_passwd is None and session.get('domainGlobalAdmin') is True: # Reset password without verify old password. self.cur_passwd = None else: self.cur_passwd = str(self.cur_passwd) connutils = connUtils.Utils() result = connutils.changePasswd(dn=self.dn, cur_passwd=self.cur_passwd, newpw=self.passwd,) if result[0] is True: return (True,) else: return result return (True,)