def add(self, data): self.domain = web.safestr(data.get('domainName', '')).strip().lower() # Get company/organization name. self.cn = data.get('cn', '') # Check domain name. if not iredutils.isDomain(self.domain): return (False, 'INVALID_DOMAIN_NAME') # Check whether domain name already exist (domainName, domainAliasName). connutils = connUtils.Utils() if connutils.isDomainExists(self.domain): return (False, 'ALREADY_EXISTS') # Add domain in database. try: self.conn.insert( 'domain', domain=self.domain, description=self.cn, transport=cfg.general.get('transport', 'dovecot'), created=iredutils.sqlNOW, active='1', ) web.logger(msg="Create domain: %s." % (self.domain), domain=self.domain, event='create',) except Exception, e: return (False, str(e))
def delete(self, domains=[]): if not isinstance(domains, types.ListType): return (False, 'INVALID_DOMAIN_NAME') self.domains = [str(v).lower() for v in domains if iredutils.isDomain(v) ] self.sql_domains = web.sqlquote(domains) # Delete domain and related records. try: self.conn.delete('alias', where='domain IN %s' % self.sql_domains) self.conn.delete( 'alias_domain', where='alias_domain IN %s OR target_domain IN %s' % (self.sql_domains,self.sql_domains,), ) self.conn.delete('domain_admins', where='domain IN %s' % self.sql_domains) self.conn.delete('mailbox', where='domain IN %s' % self.sql_domains) self.conn.delete('recipient_bcc_domain', where='domain IN %s' % self.sql_domains) self.conn.delete('recipient_bcc_user', where='domain IN %s' % self.sql_domains) self.conn.delete('sender_bcc_domain', where='domain IN %s' % self.sql_domains) self.conn.delete('sender_bcc_user', where='domain IN %s' % self.sql_domains) # Finally, delete from table `domain` to make sure all related # records were deleted. self.conn.delete('domain', where='domain IN %s' % self.sql_domains) for d in self.domains: web.logger(msg="Delete domain: %s." % (d), domain=d, event='delete',) return (True,) except Exception, e: return (False, str(e))
def delete(self, domain, mails=[]): self.domain = str(domain) if not iredutils.isDomain(self.domain): return (False, 'INVALID_DOMAIN_NAME') if not isinstance(mails, types.ListType): return (False, 'INVALID_MAIL') self.mails = [str(v).lower() for v in mails if iredutils.isEmail(v) and str(v).endswith('@'+self.domain)] self.sqlMails = web.sqlquote(self.mails) # Delete domain and related records. try: self.conn.delete('mailbox', where='username IN %s' % self.sqlMails) self.conn.delete('alias', where='address IN %s' % self.sqlMails) self.conn.delete('recipient_bcc_user', where='username IN %s' % self.sqlMails) self.conn.delete('sender_bcc_user', where='username IN %s' % self.sqlMails) # TODO Remove email from alias.goto. #self.conn.delete() web.logger( msg="Delete user: %s." % ', '.join(self.mails), domain=self.domain, event='delete', ) return (True,) except Exception, e: return (False, str(e))
def add(self, data): # msg: {key: value} msg = {} self.domain = web.safestr(data.get('domainName', '')).strip().lower() # Check domain name. if not iredutils.isDomain(self.domain): return (False, 'INVALID_DOMAIN_NAME') # Check whether domain name already exist (domainName, domainAliasName). connutils = connUtils.Utils() if connutils.isDomainExists(self.domain): return (False, 'ALREADY_EXISTS') self.dn = ldaputils.convKeywordToDN(self.domain, accountType='domain') self.cn = data.get('cn', None) ldif = iredldif.ldif_maildomain(domain=self.domain, cn=self.cn,) # Add domain dn. try: result = 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 delete(self, domain, mails=None, keep_mailbox_days=0): domain = str(domain).lower() if not iredutils.is_domain(domain): return (False, 'INVALID_DOMAIN_NAME') if not mails: return (False, 'INVALID_MAIL') mails = [ str(v).lower() for v in mails if iredutils.is_email(v) and str(v).endswith('@' + domain) ] if not mails: return (False, 'INVALID_MAIL') # Delete user and related records. try: qr = self.deleteAccounts(accounts=mails, accountType='user', keep_mailbox_days=keep_mailbox_days) if qr[0] is True: web.logger( msg="Delete user: %s." % ', '.join(mails), domain=domain, event='delete', ) else: return qr return (True, ) except Exception as e: return (False, str(e))
def add(self, data): domain = web.safestr(data.get('domainName', '')).strip().lower() # Get company/organization name. cn = data.get('cn', '') # Check domain name. if not iredutils.is_domain(domain): return (False, 'INVALID_DOMAIN_NAME') # Check whether domain name already exist (domainName, domainAliasName). connutils = connUtils.Utils() if connutils.is_domain_exists(domain): return (False, 'ALREADY_EXISTS') # Add domain in database. try: self.conn.insert( 'domain', domain=domain, description=cn, transport=settings.default_mta_transport, created=iredutils.get_gmttime(), active='1', ) web.logger( msg="Create domain: %s." % (domain), domain=domain, event='create', ) except Exception, e: return (False, str(e))
def delete(self, domain, mails=[]): self.domain = str(domain) if not iredutils.isDomain(self.domain): return (False, 'INVALID_DOMAIN_NAME') if not isinstance(mails, types.ListType): return (False, 'INVALID_MAIL') self.mails = [ str(v).lower() for v in mails if iredutils.isEmail(v) and str(v).endswith('@' + self.domain) ] self.sqlMails = web.sqlquote(self.mails) # Delete domain and related records. try: self.conn.delete('mailbox', where='username IN %s' % self.sqlMails) self.conn.delete('alias', where='address IN %s' % self.sqlMails) self.conn.delete('recipient_bcc_user', where='username IN %s' % self.sqlMails) self.conn.delete('sender_bcc_user', where='username IN %s' % self.sqlMails) # TODO Remove email from alias.goto. #self.conn.delete() web.logger( msg="Delete user: %s." % ', '.join(self.mails), domain=self.domain, event='delete', ) return (True, ) except Exception, e: return (False, str(e))
def enableOrDisableAccount(self, domain, account, dn, action, accountTypeInLogger=None): self.domain = web.safestr(domain).strip().lower() self.account = web.safestr(account).strip().lower() self.dn = escape_filter_chars(web.safestr(dn)) # Validate operation action. if action in ['enable', 'disable',]: self.action = action else: return (False, 'INVALID_ACTION') # Set value of valid account status. if action == 'enable': self.status = attrs.ACCOUNT_STATUS_ACTIVE else: self.status = attrs.ACCOUNT_STATUS_DISABLED try: self.updateAttrSingleValue( dn=self.dn, attr='accountStatus', value=self.status, ) if accountTypeInLogger is not None: web.logger( msg="%s %s: %s." % (str(action).capitalize(), str(accountTypeInLogger), self.account), domain=self.domain, event=self.action, ) return (True,) except ldap.LDAPError, e: return (False, ldaputils.getExceptionDesc(e))
def delete(self, domain, mails=[]): domain = str(domain) if not iredutils.is_domain(domain): return (False, 'INVALID_DOMAIN_NAME') if not isinstance(mails, list): return (False, 'INVALID_MAIL') mails = [str(v).lower() for v in mails if iredutils.is_email(v) and str(v).endswith('@' + domain)] if not mails: return (False, 'INVALID_MAIL') # Delete user and related records. try: qr = self.deleteAccounts(accounts=mails, accountType='user') if qr[0] is True: web.logger( msg="Delete user: %s." % ', '.join(mails), domain=domain, event='delete', ) else: return qr return (True,) except Exception, e: return (False, str(e))
def add(self, data): self.domain = web.safestr(data.get('domainName', '')).strip().lower() # Get company/organization name. cn = data.get('cn', '') # Check domain name. if not iredutils.isDomain(self.domain): return (False, 'INVALID_DOMAIN_NAME') # Check whether domain name already exist (domainName, domainAliasName). connutils = connUtils.Utils() if connutils.isDomainExists(self.domain): return (False, 'ALREADY_EXISTS') # Add domain in database. try: self.conn.insert( 'dbmail_domains', domain=self.domain, description=cn, transport=settings.DBMAIL_DEFAULT_DOMAIN_TRANSPORT, ) web.logger( msg="Create domain: %s." % (self.domain), domain=self.domain, event='create', ) except Exception, e: return (False, str(e))
def deleteSingleUser( self, mail, deleteFromGroups=True, ): self.mail = web.safestr(mail) if not iredutils.isEmail(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.convKeywordToDN(self.mail, accountType='user') # Delete user object. try: #deltree.DelTree(self.conn, self.dnUser, ldap.SCOPE_SUBTREE) self.conn.delete_s(self.dnUser) if deleteFromGroups: self.deleteSingleUserFromGroups(self.mail) # Log delete action. web.logger( msg="Delete user: %s." % (self.mail), domain=self.domain, event='delete', ) return (True, ) except ldap.LDAPError, e: return (False, ldaputils.getExceptionDesc(e))
def delete(self, mails=[]): if not isinstance(mails, list): return (False, 'INVALID_MAIL') self.mails = [str(v).lower() for v in mails if iredutils.is_email(v)] sql_vars = { 'username': self.mails, } # Delete domain and related records. try: self.conn.delete( 'admin', vars=sql_vars, where='username IN $username', ) self.conn.delete( 'domain_admins', vars=sql_vars, where='username IN $username', ) web.logger( msg="Delete admin: %s." % ', '.join(self.mails), event='delete', ) return (True, ) except Exception as e: return (False, str(e))
def deleteSingleUser(self, mail, deleteFromGroups=True,): self.mail = web.safestr(mail) if not iredutils.isEmail(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.convKeywordToDN(self.mail, accountType='user') # Delete user object. try: #deltree.DelTree(self.conn, self.dnUser, ldap.SCOPE_SUBTREE) self.conn.delete_s(self.dnUser) if deleteFromGroups: self.deleteSingleUserFromGroups(self.mail) # Log delete action. web.logger( msg="Delete user: %s." % (self.mail), domain=self.domain, event='delete', ) return (True,) except ldap.LDAPError, e: return (False, ldaputils.getExceptionDesc(e))
def deleteObjWithDN( self, domain, dn, account, accountType, ): self.domain = web.safestr(domain) if not iredutils.is_domain(self.domain): return (False, 'INVALID_DOMAIN_NAME') self.dn = escape_filter_chars(dn) # Used for logger. self.account = web.safestr(account) try: delete_ldap_tree(dn=self.dn, conn=self.conn) web.logger( msg="Delete %s: %s." % (str(accountType), self.account), domain=self.domain, event='delete', ) return (True, ) except Exception, e: return (False, ldaputils.getExceptionDesc(e))
def POST(self): # Get username, password. i = web.input(_unicode=False) username = web.safestr(i.get('username').strip()) password = str(i.get('password').strip()) save_pass = web.safestr(i.get('save_pass', 'no').strip()) auth = core.Auth() auth_result = auth.auth(username=username, password=password) if auth_result[0] is True: # Config session data. web.config.session_parameters['cookie_name'] = 'iRedAdmin-Pro' # Session expire when client ip was changed. web.config.session_parameters['ignore_change_ip'] = False # Don't ignore session expiration. web.config.session_parameters['ignore_expiry'] = False if save_pass == 'yes': # Session timeout (in seconds). web.config.session_parameters['timeout'] = 86400 # 24 hours else: # Expire session when browser closed. web.config.session_parameters['timeout'] = 600 # 10 minutes web.logger(msg="Login success", event='login',) raise web.seeother('/dashboard/checknew') else: session['failedTimes'] += 1 web.logger(msg="Login failed.", admin=username, event='login', loglevel='error',) raise web.seeother('/login?msg=%s' % web.urlquote(auth_result[1]))
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 deleteSingleUser(self, mail, deleteFromGroups=True): 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") if self.dnUser[0] is False: return self.dnUser # Delete user object. try: # Delete single object. # self.conn.delete_s(self.dnUser) # Delete object and its subtree. deltree.DelTree(self.conn, self.dnUser, ldap.SCOPE_SUBTREE) if deleteFromGroups: self.deleteSingleUserFromGroups(self.mail) # Delete record from SQL database: real-time used quota. try: connUtils.deleteAccountFromUsedQuota([self.mail]) except Exception, e: pass # Log delete action. web.logger(msg="Delete user: %s." % (self.mail), domain=self.domain, event="delete") return (True,)
def POST(self): # Get username, password. i = web.input(_unicode=False) username = web.safestr(i.get('username').strip()) password = str(i.get('password').strip()) save_pass = web.safestr(i.get('save_pass', 'no').strip()) auth = core.Auth() auth_result = auth.auth(username=username, password=password) if auth_result[0] is True: # Config session data. web.config.session_parameters['cookie_name'] = 'iRedAdmin' # Session expire when client ip was changed. web.config.session_parameters['ignore_change_ip'] = False # Don't ignore session expiration. web.config.session_parameters['ignore_expiry'] = False if save_pass == 'yes': # Session timeout (in seconds). web.config.session_parameters['timeout'] = 86400 # 24 hours else: # Expire session when browser closed. web.config.session_parameters['timeout'] = 600 # 10 minutes web.logger(msg="Login success", event='login',) return web.seeother('/dashboard/checknew') else: session['failedTimes'] += 1 web.logger(msg="Login failed.", admin=username, event='login', loglevel='error',) return web.seeother('/login?msg=%s' % auth_result[1])
def delete(self, domains=[]): if not isinstance(domains, list): return (False, 'INVALID_DOMAIN_NAME') domains = [str(v).lower() for v in domains if iredutils.is_domain(v)] if not domains: return (True, ) msg = {} for domain in domains: dn = ldaputils.convert_keyword_to_dn(web.safestr(domain), accountType='domain') if dn[0] is False: return dn try: deltree.DelTree(self.conn, dn, ldap.SCOPE_SUBTREE) web.logger( msg="Delete domain: %s." % (domain), domain=domain, event='delete', ) except ldap.LDAPError, e: msg[domain] = str(e)
def add(self, data): domain = web.safestr(data.get('domainName', '')).strip().lower() # Get company/organization name. cn = data.get('cn', '') # Check domain name. if not iredutils.is_domain(domain): return (False, 'INVALID_DOMAIN_NAME') # Check whether domain name already exist (domainName, domainAliasName). connutils = connUtils.Utils() if connutils.is_domain_exists(domain): return (False, 'ALREADY_EXISTS') # Add domain in database. try: self.conn.insert( 'domain', domain=domain, description=cn, transport=settings.default_mta_transport, created=iredutils.get_gmttime(), active='1', ) web.logger(msg="Create domain: %s." % (domain), domain=domain, event='create',) except Exception, e: return (False, str(e))
def add(self, data): self.domain = web.safestr(data.get("domainName", "")).strip().lower() # Get company/organization name. self.cn = data.get("cn", "") # Check domain name. if not iredutils.isDomain(self.domain): return (False, "INVALID_DOMAIN_NAME") # Check whether domain name already exist (domainName, domainAliasName). connutils = connUtils.Utils() if connutils.isDomainExists(self.domain): return (False, "ALREADY_EXISTS") # Add domain in database. try: self.conn.insert( "domain", domain=self.domain, description=self.cn, transport=cfg.general.get("transport", "dovecot"), created=iredutils.sqlNOW, active="1", ) web.logger(msg="Create domain: %s." % (self.domain), domain=self.domain, event="create") except Exception, e: return (False, str(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, e: msg[self.domain] = str(e)
def delete(self, domains=[]): if not isinstance(domains, types.ListType): return (False, "INVALID_DOMAIN_NAME") self.domains = [str(v).lower() for v in domains if iredutils.isDomain(v)] self.sql_domains = web.sqlquote(domains) # Delete domain and related records. try: self.conn.delete("alias", where="domain IN %s" % self.sql_domains) self.conn.delete( "alias_domain", where="alias_domain IN %s OR target_domain IN %s" % (self.sql_domains, self.sql_domains) ) self.conn.delete("domain_admins", where="domain IN %s" % self.sql_domains) self.conn.delete("mailbox", where="domain IN %s" % self.sql_domains) self.conn.delete("recipient_bcc_domain", where="domain IN %s" % self.sql_domains) self.conn.delete("recipient_bcc_user", where="domain IN %s" % self.sql_domains) self.conn.delete("sender_bcc_domain", where="domain IN %s" % self.sql_domains) self.conn.delete("sender_bcc_user", where="domain IN %s" % self.sql_domains) # Finally, delete from table `domain` to make sure all related # records were deleted. self.conn.delete("domain", where="domain IN %s" % self.sql_domains) for d in self.domains: web.logger(msg="Delete domain: %s." % (d), domain=d, event="delete") return (True,) except Exception, e: return (False, str(e))
def enableOrDisableAccount(self, domain, account, dn, action, accountTypeInLogger=None): self.domain = web.safestr(domain).strip().lower() self.account = web.safestr(account).strip().lower() self.dn = escape_filter_chars(web.safestr(dn)) # Validate operation action. if action in ["enable", "disable"]: self.action = action else: return (False, "INVALID_ACTION") # Set value of valid account status. if action == "enable": self.status = attrs.ACCOUNT_STATUS_ACTIVE else: self.status = attrs.ACCOUNT_STATUS_DISABLED try: self.updateAttrSingleValue(dn=self.dn, attr="accountStatus", value=self.status) if accountTypeInLogger is not None: web.logger( msg="%s %s: %s." % (str(action).capitalize(), str(accountTypeInLogger), self.account), domain=self.domain, event=self.action, ) return (True,) except ldap.LDAPError, e: return (False, ldaputils.getExceptionDesc(e))
def setAccountStatus(self, accounts, accountType, active=True): # accounts must be a list/tuple. # accountType in ['domain', 'user', 'admin'] # active: True -> active, False -> disabled if not len(accounts) > 0: return (True,) accountType = str(accountType) if active is True: active = 1 action = 'Active' else: active = 0 action = 'Disable' if accountType == 'domain': accounts = [str(v) for v in accounts if iredutils.is_domain(v)] try: self.conn.update( 'domain', vars={'accounts': accounts}, where='domain IN $accounts', active=active, ) except Exception as e: return (False, str(e)) elif accountType == 'user': accounts = [str(v) for v in accounts if iredutils.is_email(v)] try: self.conn.update( 'mailbox', vars={'accounts': accounts}, where='username IN $accounts', active=active, ) except Exception as e: return (False, str(e)) elif accountType == 'admin': accounts = [str(v) for v in accounts if iredutils.is_email(v)] try: self.conn.update( 'admin', vars={'accounts': accounts}, where='username IN $accounts', active=active, ) except Exception as e: return (False, str(e)) else: pass try: web.logger( msg="%s %s: %s." % (action, accountType, ', '.join(accounts)), event=action.lower(), ) except: pass return (True,)
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 delete(self, domains=[]): if not isinstance(domains, list): return (False, 'INVALID_DOMAIN_NAME') domains = [str(v).lower() for v in domains if iredutils.is_domain(v)] if not domains: return (True, ) sql_vars = { 'domains': domains, } # Delete domain and related records. try: self.conn.delete( 'domain', vars=sql_vars, where='domain IN $domains', ) self.conn.delete( 'alias_domain', vars=sql_vars, where='alias_domain IN $domains OR target_domain IN $domains', ) for tbl in ['alias', 'domain_admins', 'mailbox', \ 'recipient_bcc_domain', 'recipient_bcc_user', \ 'sender_bcc_domain', 'sender_bcc_user', \ ]: self.conn.delete( tbl, vars=sql_vars, where='domain IN $domains', ) # Delete real-time mailbox quota. try: self.conn.query( 'DELETE FROM used_quota WHERE %s' % \ web.sqlors('username LIKE ', ['%@' + d for d in domains]) ) except: pass for d in domains: web.logger( msg="Delete domain: %s." % (d), domain=d, event='delete', ) return (True, ) except Exception, e: return (False, str(e))
def POST(self): # Get username, password. i = web.input(_unicode=False) username = web.safestr(i.get('username', '').strip()) password = i.get('password', '').strip() save_pass = web.safestr(i.get('save_pass', 'no').strip()) if not iredutils.isEmail(username): return web.seeother('/login?msg=INVALID_USERNAME') if len(password) == 0: return web.seeother('/login?msg=EMPTY_PASSWORD') # Convert username to ldap dn. userdn = ldaputils.convKeywordToDN(username, accountType='admin') # Return True if auth success, otherwise return error msg. self.auth_result = auth.Auth(cfg.ldap.get('uri', 'ldap://127.0.0.1/'), userdn, password,) if self.auth_result is True: session['username'] = username session['logged'] = True # Read preferred language from db. adminLib = adminlib.Admin() #session['lang'] = adminLib.getPreferredLanguage(userdn) or cfg.general.get('lang', 'en_US') adminProfile = adminLib.profile(username) if adminProfile[0] is True: cn = adminProfile[1][0][1].get('cn', [None])[0] lang = adminProfile[1][0][1].get('preferredLanguage', [cfg.general.get('lang', 'en_US')])[0] session['cn'] = cn session['lang'] = lang else: pass web.config.session_parameters['cookie_name'] = 'iRedAdmin' # Session expire when client ip was changed. web.config.session_parameters['ignore_change_ip'] = False # Don't ignore session expiration. web.config.session_parameters['ignore_expiry'] = False if save_pass == 'yes': # Session timeout (in seconds). web.config.session_parameters['timeout'] = 86400 # 24 hours else: # Expire session when browser closed. web.config.session_parameters['timeout'] = 600 # 10 minutes web.logger(msg="Login success", event='login',) return web.seeother('/dashboard/checknew') else: session['failedTimes'] += 1 web.logger(msg="Login failed.", admin=username, event='login', loglevel='error',) return web.seeother('/login?msg=%s' % self.auth_result)
def add(self, data): self.cn = data.get('cn', '') self.mail = web.safestr(data.get('mail')).strip().lower() if not iredutils.is_email(self.mail): return (False, 'INVALID_MAIL') # Check admin exist. connutils = connUtils.Utils() if connutils.isAdminExists(self.mail): return (False, 'ALREADY_EXISTS') # Get domainGlobalAdmin setting. self.domainGlobalAdmin = web.safestr(data.get('domainGlobalAdmin', 'no')) if self.domainGlobalAdmin not in ['yes', 'no', ]: self.domainGlobalAdmin = 'no' # Get language setting. self.preferredLanguage = web.safestr(data.get('preferredLanguage', 'en_US')) # Get new password. 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 try: self.conn.insert( 'admin', username=self.mail, name=self.cn, password=iredutils.generate_password_hash(self.passwd), language=self.preferredLanguage, created=iredutils.get_gmttime(), active='1', ) if self.domainGlobalAdmin == 'yes': self.conn.insert( 'domain_admins', username=self.mail, domain='ALL', created=iredutils.get_gmttime(), active='1', ) web.logger(msg="Create admin: %s." % (self.mail), event='create',) return (True,) except Exception, e: return (False, str(e))
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('listname')).strip().lower() self.mail = self.username + '@' + self.domain if self.domain != domain: return (False, 'PERMISSION_DENIED') if not iredutils.isDomain(self.domain): return (False, 'INVALID_DOMAIN_NAME') if not iredutils.isEmail(self.mail): return (False, 'INVALID_MAIL') # Define columns and values used to insert. columns = {'domain': self.domain, 'alias': self.mail, } # Check account existing. connutils = connUtils.Utils() if connutils.isEmailExists(mail=self.mail): return (False, 'ALREADY_EXISTS') # Get domain profile. domainLib = domainlib.Domain() resultOfDomainProfile = domainLib.profile(domain=self.domain) if resultOfDomainProfile[0] is True: self.domainProfile = resultOfDomainProfile[1] else: return resultOfDomainProfile # Check account limit. adminLib = adminlib.Admin() numberOfExistAccounts = adminLib.getNumberOfManagedAccounts(accountType='alias', domains=[self.domain]) if self.domainProfile.aliases == -1: return (False, 'NOT_ALLOWED') elif self.domainProfile.aliases > 0: if self.domainProfile.aliases <= numberOfExistAccounts: return (False, 'EXCEEDED_DOMAIN_ACCOUNT_LIMIT') # Get display name from <form> columns['name'] = data.get('cn', '') try: # Store new user in required SQL DBs. self.conn.insert( 'dbmail_aliases_extra', **columns ) web.logger(msg="Create mail alias: %s." % (self.mail), domain=self.domain, event='create',) return (True,) except Exception, e: return (False, str(e))
def add(self, data): self.cn = data.get('cn') self.mail = web.safestr(data.get('mail')).strip().lower() if not iredutils.is_email(self.mail): return (False, 'INVALID_MAIL') self.domainGlobalAdmin = web.safestr( data.get('domainGlobalAdmin', 'no')) if self.domainGlobalAdmin not in [ 'yes', 'no', ]: self.domainGlobalAdmin = 'no' self.preferredLanguage = web.safestr( data.get('preferredLanguage', 'en_US')) # Check password. 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 = iredutils.generate_password_hash(result[1]) else: return result ldif = iredldif.ldif_mailadmin( mail=self.mail, passwd=self.passwd, cn=self.cn, preferredLanguage=self.preferredLanguage, domainGlobalAdmin=self.domainGlobalAdmin) self.dn = ldaputils.convert_keyword_to_dn(self.mail, accountType='admin') if self.dn[0] is False: return self.dn try: self.conn.add_s(self.dn, ldif) web.logger( msg="Create admin: %s." % (self.mail), event='create', ) return (True, ) except ldap.ALREADY_EXISTS: return (False, 'ALREADY_EXISTS') except Exception, e: return (False, ldaputils.getExceptionDesc(e))
def delete(self, domains=None, keep_mailbox_days=0): if not domains: return (False, 'INVALID_DOMAIN_NAME') domains = [str(v).lower() for v in domains if iredutils.is_domain(v)] if not domains: return (True, ) msg = {} for domain in domains: dn = ldaputils.convert_keyword_to_dn(web.safestr(domain), accountType='domain') if dn[0] is False: return dn # Log maildir path in SQL table. try: qr = self.conn.search_s(attrs.DN_BETWEEN_USER_AND_DOMAIN + dn, ldap.SCOPE_ONELEVEL, "(objectClass=mailUser)", ['mail', 'homeDirectory']) if keep_mailbox_days == 0: keep_mailbox_days = 36500 # Convert keep days to string _now_in_seconds = time.time() _days_in_seconds = _now_in_seconds + (keep_mailbox_days * 24 * 60 * 60) sql_keep_days = time.strftime('%Y-%m-%d', time.strptime(time.ctime(_days_in_seconds))) v = [] for obj in qr: deleted_mail = obj[1].get('mail')[0] deleted_maildir = obj[1].get('homeDirectory', [''])[0] v += [{'maildir': deleted_maildir, 'username': deleted_mail, 'domain': domain, 'admin': session.get('username'), 'delete_date': sql_keep_days}] if v: web.admindb.multiple_insert('deleted_mailboxes', values=v) except: pass try: connUtils.delete_ldap_tree(dn=dn, conn=self.conn) web.logger(msg="Delete domain: %s." % (domain), domain=domain, event='delete',) except ldap.LDAPError, e: msg[domain] = str(e)
def delete(self, domain, mails=[]): self.domain = str(domain) if not iredutils.isDomain(self.domain): return (False, 'INVALID_DOMAIN_NAME') if not isinstance(mails, (list, tuple,)): return (False, 'INVALID_MAIL') self.mails = [str(v).lower() for v in mails if iredutils.isEmail(v) and str(v).endswith('@' + self.domain) ] # Remove alias from domain.defaultuseraliases. # Get domain profile. domainLib = domainlib.Domain() qr = domainLib.simpleProfile(domain=self.domain, columns=['domain', 'defaultuseraliases', ]) if qr[0] is True: self.domainProfile = qr[1] else: return qr self.defaultUserAliases = self.domainProfile.defaultuseraliases.split(',') # Remove from domain.defaultuseraliases. self.newDefaultAliases = [str(v).lower() for v in self.defaultUserAliases if v not in self.mails ] # Delete domain and related records. try: self.conn.delete('dbmail_aliases_extra', where='%s' % web.sqlors('alias = ', self.mails),) self.conn.delete('dbmail_aliases', where='%s' % web.sqlors('alias = ', self.mails),) self.conn.update('dbmail_domains', vars={'domain': self.domain, }, defaultuseraliases=','.join(self.newDefaultAliases), modified=iredutils.getGMTTime(), where='domain = $domain', ) web.logger( msg="Delete mail alias: %s." % ', '.join(self.mails), domain=self.domain, event='delete', ) return (True,) except Exception, e: return (False, str(e))
def delete(self, domains=[]): if not isinstance(domains, list): return (False, 'INVALID_DOMAIN_NAME') domains = [str(v).lower() for v in domains if iredutils.is_domain(v) ] if not domains: return (True, ) sql_vars = {'domains': domains, } # Delete domain and related records. try: self.conn.delete('domain', vars=sql_vars, where='domain IN $domains', ) self.conn.delete( 'alias_domain', vars=sql_vars, where='alias_domain IN $domains OR target_domain IN $domains', ) for tbl in ['alias', 'domain_admins', 'mailbox', \ 'recipient_bcc_domain', 'recipient_bcc_user', \ 'sender_bcc_domain', 'sender_bcc_user', \ ]: self.conn.delete( tbl, vars=sql_vars, where='domain IN $domains', ) # Delete real-time mailbox quota. try: self.conn.query( 'DELETE FROM used_quota WHERE %s' % \ web.sqlors('username LIKE ', ['%@' + d for d in domains]) ) except: pass for d in domains: web.logger(msg="Delete domain: %s." % (d), domain=d, event='delete',) return (True,) except Exception, e: return (False, str(e))
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.convKeywordToDN(self.mail, accountType='admin') try: deltree.DelTree( self.conn, dn, ldap.SCOPE_SUBTREE ) web.logger(msg="Delete admin: %s." % (self.mail,), event='delete',) except ldap.LDAPError, e: result[self.mail] = str(e)
def delete(self, mails=[]): if not isinstance(mails, types.ListType): return (False, 'INVALID_MAIL') self.mails = [str(v).lower() for v in mails if iredutils.isEmail(v)] self.sqlMails = web.sqlquote(self.mails) # Delete domain and related records. try: self.conn.delete('admin', where='username IN %s' % self.sqlMails) self.conn.delete('domain_admins', where='username IN %s' % self.sqlMails) web.logger(msg="Delete admin: %s." % ', '.join(self.mails), event='delete',) return (True,) except Exception, e: return (False, str(e))
def delete(self, domains=[]): if not isinstance(domains, types.ListType): return (False, 'INVALID_DOMAIN_NAME') msg = {} for domain in domains: if not iredutils.isDomain(domain): continue dn = ldaputils.convKeywordToDN(web.safestr(domain), accountType='domain') try: deltree.DelTree(self.conn, dn, ldap.SCOPE_SUBTREE) web.logger(msg="Delete domain: %s." % (domain), domain=domain, event='delete',) except ldap.LDAPError, e: msg[domain] = str(e)
def deleteObjWithDN(self, domain, dn, account, accountType): self.domain = web.safestr(domain) if not iredutils.is_domain(self.domain): return (False, "INVALID_DOMAIN_NAME") self.dn = escape_filter_chars(dn) # Used for logger. self.account = web.safestr(account) try: deltree.DelTree(self.conn, self.dn, ldap.SCOPE_SUBTREE) web.logger(msg="Delete %s: %s." % (str(accountType), self.account), domain=self.domain, event="delete") return (True,) except Exception, e: return (False, ldaputils.getExceptionDesc(e))
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, domain, profile_type, data, ): profile_type = str(profile_type) domain = str(domain) # Pre-defined update key:value. updates = { 'modified': iredutils.get_gmttime(), } sql_vars = { 'domain': domain, } if profile_type == 'general': # Get name cn = data.get('cn', '') updates['description'] = cn if session.get('domainGlobalAdmin') is True: # Get account status if 'accountStatus' in list(data.keys()): updates['active'] = 1 else: updates['active'] = 0 # Update SQL db with columns: maxquota, active. try: self.conn.update('domain', vars=sql_vars, where='domain=$domain', **updates) except Exception as e: return (False, str(e)) web.logger(msg="Update domain profile: %s (%s)." % (domain, profile_type), domain=domain, event='update') return (True, )
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.convKeywordToDN(self.mail, accountType='admin') try: deltree.DelTree(self.conn, dn, ldap.SCOPE_SUBTREE) web.logger( msg="Delete admin: %s." % (self.mail, ), event='delete', ) except ldap.LDAPError, e: result[self.mail] = str(e)
def add(self, data): self.cn = data.get("cn") self.mail = web.safestr(data.get("mail")).strip().lower() if not iredutils.is_email(self.mail): return (False, "INVALID_MAIL") self.domainGlobalAdmin = web.safestr(data.get("domainGlobalAdmin", "no")) if self.domainGlobalAdmin not in ["yes", "no"]: self.domainGlobalAdmin = "no" self.preferredLanguage = web.safestr(data.get("preferredLanguage", "en_US")) # Check password. 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 = iredutils.generate_password_hash(result[1]) else: return result ldif = iredldif.ldif_mailadmin( mail=self.mail, passwd=self.passwd, cn=self.cn, preferredLanguage=self.preferredLanguage, domainGlobalAdmin=self.domainGlobalAdmin, ) self.dn = ldaputils.convert_keyword_to_dn(self.mail, accountType="admin") if self.dn[0] is False: return self.dn try: self.conn.add_s(self.dn, ldif) web.logger(msg="Create admin: %s." % (self.mail), event="create") return (True,) except ldap.ALREADY_EXISTS: return (False, "ALREADY_EXISTS") except Exception, e: return (False, ldaputils.getExceptionDesc(e))
def add(self, data): self.cn = data.get('cn') self.mail = web.safestr(data.get('mail')).strip().lower() if not iredutils.is_email(self.mail): return (False, 'INVALID_MAIL') self.domainGlobalAdmin = web.safestr(data.get('domainGlobalAdmin', 'no')) if self.domainGlobalAdmin not in ['yes', 'no', ]: self.domainGlobalAdmin = 'no' self.preferredLanguage = web.safestr(data.get('preferredLanguage', 'en_US')) # Check password. 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 = ldaputils.generate_ldap_password(result[1]) else: return result ldif = iredldif.ldif_mailadmin( mail=self.mail, passwd=self.passwd, cn=self.cn, preferredLanguage=self.preferredLanguage, domainGlobalAdmin=self.domainGlobalAdmin, ) self.dn = ldaputils.convert_keyword_to_dn(self.mail, accountType='admin') if self.dn[0] is False: return self.dn try: self.conn.add_s(self.dn, ldif) web.logger(msg="Create admin: %s." % (self.mail), event='create',) return (True,) except ldap.ALREADY_EXISTS: return (False, 'ALREADY_EXISTS') except Exception, e: return (False, ldaputils.getExceptionDesc(e))
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 deleteSingleUser( self, mail, deleteFromGroups=True, ): 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') if self.dnUser[0] is False: return self.dnUser # Delete user object. try: # Delete single object. #self.conn.delete_s(self.dnUser) # Delete object and its subtree. deltree.DelTree(self.conn, self.dnUser, ldap.SCOPE_SUBTREE) if deleteFromGroups: self.deleteSingleUserFromGroups(self.mail) # Delete record from SQL database: real-time used quota. try: connUtils.deleteAccountFromUsedQuota([self.mail]) except Exception, e: pass # Log delete action. web.logger( msg="Delete user: %s." % (self.mail), domain=self.domain, event='delete', ) return (True, )
def delete(self, domains=[]): if not isinstance(domains, list): return (False, 'INVALID_DOMAIN_NAME') self.domains = [ str(v).lower() for v in domains if iredutils.isDomain(v) ] sql_vars = { 'domains': self.domains, } # Delete domain and related records. try: self.conn.delete( 'dbmail_alias_domains', vars=sql_vars, where='alias_domain IN $domains OR target_domain IN $domains', ) self.conn.delete( 'dbmail_domain_admins', vars=sql_vars, where='domain IN $domains', ) # Finally, delete from table `domain` to make sure all related # records were deleted. self.conn.delete( 'dbmail_domains', vars=sql_vars, where='domain IN $domains', ) for d in self.domains: web.logger( msg="Delete domain: %s." % (d), domain=d, event='delete', ) return (True, ) except Exception, e: return (False, str(e))
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 delete(self, domain, mails=[]): self.domain = str(domain) if not iredutils.isDomain(self.domain): return (False, 'INVALID_DOMAIN_NAME') if not isinstance(mails, list): return (False, 'INVALID_MAIL') self.mails = [ str(addr).lower() for addr in mails if iredutils.isEmail(addr) and str(addr).endswith('@' + self.domain) ] if not self.mails: return (False, 'INVALID_MAIL') # Delete domain and related records. try: # Delete from aliases. self.conn.delete('dbmail_aliases', where='%s' % web.sqlors('deliver_to = ', self.mails)) self.conn.delete('dbmail_aliases', where='%s' % web.sqlors('alias = ', self.mails)) # Delete user record. self.conn.delete('dbmail_users', where='%s' % web.sqlors('userid = ', self.mails)) web.logger( msg="Delete user: %s." % ', '.join(self.mails), domain=self.domain, event='delete', ) return (True, ) except Exception, e: return (False, str(e))
def delete(self, domains=[]): if not isinstance(domains, list): return (False, 'INVALID_DOMAIN_NAME') domains = [str(v).lower() for v in domains if iredutils.is_domain(v) ] if not domains: return (True,) msg = {} for domain in domains: dn = ldaputils.convert_keyword_to_dn(web.safestr(domain), accountType='domain') if dn[0] is False: return dn try: deltree.DelTree(self.conn, dn, ldap.SCOPE_SUBTREE) web.logger(msg="Delete domain: %s." % (domain), domain=domain, event='delete',) except ldap.LDAPError, e: msg[domain] = str(e)
def delete(self, mails=[]): if not isinstance(mails, list): return (False, 'INVALID_MAIL') self.mails = [str(v).lower() for v in mails if iredutils.is_email(v)] sql_vars = {'username': self.mails, } # Delete domain and related records. try: self.conn.delete( 'admin', vars=sql_vars, where='username IN $username', ) self.conn.delete( 'domain_admins', vars=sql_vars, where='username IN $username', ) web.logger(msg="Delete admin: %s." % ', '.join(self.mails), event='delete',) return (True,) except Exception, e: return (False, str(e))
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 if self.domain != domain: return (False, 'PERMISSION_DENIED') if not iredutils.isDomain(self.domain): return (False, 'INVALID_DOMAIN_NAME') # Check account existing. connutils = connUtils.Utils() if connutils.isEmailExists(mail=self.mail): return (False, 'ALREADY_EXISTS') # Get domain profile. domainLib = domainlib.Domain() resultOfDomainProfile = domainLib.profile(domain=self.domain) if resultOfDomainProfile[0] is True: self.domainProfile = resultOfDomainProfile[1] else: return resultOfDomainProfile # Check account limit. adminLib = adminlib.Admin() numberOfExistAccounts = adminLib.getNumberOfManagedAccounts(accountType='user', domains=[self.domain]) if self.domainProfile.mailboxes == 0: # Unlimited. pass elif self.domainProfile.mailboxes <= numberOfExistAccounts: return (False, 'EXCEEDED_DOMAIN_ACCOUNT_LIMIT') # Check spare quota and number of spare account limit. # Get quota from <form> self.mailQuota = str(data.get('mailQuota')).strip() self.defaultUserQuota = self.domainProfile.get('defaultuserquota', 0) if self.mailQuota.isdigit(): self.mailQuota = int(self.mailQuota) else: self.mailQuota = self.defaultUserQuota # Re-calculate mail quota if this domain has limited max quota. if self.domainProfile.maxquota > 0: # Get used quota. qr = domainLib.getAllocatedQuotaSize(domain=self.domain) if qr[0] is True: self.allocatedQuota = qr[1] else: return qr spareQuota = self.domainProfile.maxquota - self.allocatedQuota if spareQuota > 0: if spareQuota < self.mailQuota: self.mailQuota = spareQuota else: # No enough quota. return (False, 'EXCEEDED_DOMAIN_QUOTA_SIZE') # # Get password from <form>. # self.newpw = str(data.get('newpw', '')) self.confirmpw = str(data.get('confirmpw', '')) # Get password length limit from domain profile or global setting. self.minPasswordLength = self.domainProfile.get('minpasswordlength',cfg.general.get('min_passwd_length', '0')) self.maxPasswordLength = self.domainProfile.get('maxpasswordlength', cfg.general.get('max_passwd_length', '0')) resultOfPW = iredutils.verifyNewPasswords( self.newpw, self.confirmpw, min_passwd_length=self.minPasswordLength, max_passwd_length=self.maxPasswordLength, ) if resultOfPW[0] is True: self.passwd = iredutils.getSQLPassword(resultOfPW[1]) else: return resultOfPW # Get display name from <form> self.cn = data.get('cn', '') # Assign new user to default mail aliases. assignedAliases = [str(v).lower() for v in str(self.domainProfile.defaultuseraliases).split(',') if iredutils.isEmail(v) ] try: # Store new user in SQL db. self.conn.insert( 'mailbox', domain=self.domain, username=self.mail, password=self.passwd, name=self.cn, maildir=iredutils.setMailMessageStore(self.mail), quota=self.mailQuota, created=iredutils.sqlNOW, active='1', local_part=self.username, ) # Assign new user to default mail aliases. if len(assignedAliases) > 0: for ali in assignedAliases: try: self.conn.query( ''' UPDATE alias SET goto=CONCAT(goto, %s) WHERE address=%s AND domain=%s ''' % ( web.sqlquote(','+self.mail), web.sqlquote(ali), web.sqlquote(self.domain), ) ) except: pass # Create an alias account: address=goto. self.conn.insert( 'alias', address=self.mail, goto=self.mail, domain=self.domain, created=iredutils.sqlNOW, active='1', ) web.logger(msg="Create user: %s." % (self.mail), domain=self.domain, event='create',) return (True,) except Exception, e: return (False, str(e))
elif self.accountType == 'alias': self.accounts = [str(v) for v in accounts if iredutils.isEmail(v)] try: self.conn.update( 'alias', where='address IN %s' % (web.sqlquote(self.accounts)), active=self.active, ) except Exception, e: return (False, str(e)) else: pass try: web.logger( msg="%s %s: %s." % (self.action, self.accountType, ', '.join(self.accounts)), event=self.action.lower(), ) except: pass return (True,) def getUsedBytesMessages(self, domain=None): """Return (messages, bytes)""" if domain is None: resultOfSum = self.conn.query( ''' SELECT SUM(messages) AS messages, SUM(bytes) AS bytes FROM mailbox '''
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))
accounts = [str(v) for v in accounts if iredutils.is_email(v)] try: self.conn.update( 'alias', vars={'accounts': accounts}, where='address IN $accounts', active=active, ) except Exception, e: return (False, str(e)) else: pass try: web.logger( msg="%s %s: %s." % (action, accountType, ', '.join(accounts)), event=action.lower(), ) except: pass return (True,) def deleteAccounts(self, accounts, accountType,): # accounts must be a list/tuple. # accountType in ['domain', 'user', 'admin', 'alias',] if not accounts: return (True,) accountType = str(accountType) if accountType == 'domain': accounts = [str(v) for v in accounts if iredutils.is_domain(v)]
if sender_records.get(s): values.append({"rid": user_id, "sid": sender_records[s], "wb": "W"}) for s in bl_senders: # Filter out same record in blacklist if sender_records.get(s) and s not in wl_senders: values.append({"rid": user_id, "sid": sender_records[s], "wb": "B"}) try: conn.multiple_insert("wblist", values) # Log if wl_senders or bl_senders: if flush_before_import: web.logger( msg="Update whitelists and/or blacklists for %s." % account, admin="CLI", event="update_wblist" ) else: if wl_senders: web.logger( msg="Add whitelists for %s: %s." % (account, ", ".join(wl_senders)), admin="CLI", event="update_wblist", ) if bl_senders: web.logger( msg="Add blacklists for %s: %s." % (account, ", ".join(bl_senders)), admin=session["username"], event="update_wblist", )
if profile_type == 'general': # Get name cn = data.get('cn', '') updates['description'] = cn if session.get('domainGlobalAdmin') is True: # Get account status if 'accountStatus' in data.keys(): updates['active'] = 1 else: updates['active'] = 0 # Update SQL db with columns: maxquota, active. try: self.conn.update( 'domain', vars=sql_vars, where='domain=$domain', **updates ) except Exception, e: return (False, str(e)) web.logger(msg="Update domain profile: %s (%s)." % (domain, profile_type), domain=domain, event='update', ) return (True,)
def add(self, domain, data): # Get domain name, username, cn. self.domain = web.safestr(data.get('domainName')).strip().lower() mail_local_part = web.safestr(data.get('username')).strip().lower() self.mail = mail_local_part + '@' + self.domain if not iredutils.is_domain(self.domain): return (False, 'INVALID_DOMAIN_NAME') if self.domain != domain: return (False, 'PERMISSION_DENIED') if not iredutils.is_email(self.mail): return (False, 'INVALID_MAIL') # Check account existing. connutils = connUtils.Utils() if connutils.is_email_exists(mail=self.mail): return (False, 'ALREADY_EXISTS') # Get domain profile. domainLib = domainlib.Domain() resultOfDomainProfile = domainLib.profile(domain=self.domain) if resultOfDomainProfile[0] is True: domainProfile = resultOfDomainProfile[1] else: return resultOfDomainProfile # Check account limit. adminLib = adminlib.Admin() numberOfExistAccounts = adminLib.getNumberOfManagedAccounts(accountType='user', domains=[self.domain]) if domainProfile.mailboxes == -1: return (False, 'NOT_ALLOWED') elif domainProfile.mailboxes > 0: if domainProfile.mailboxes <= numberOfExistAccounts: return (False, 'EXCEEDED_DOMAIN_ACCOUNT_LIMIT') # Check spare quota and number of spare account limit. # Get quota from <form> mailQuota = str(data.get('mailQuota')).strip() if mailQuota.isdigit(): mailQuota = int(mailQuota) else: mailQuota = 0 # Re-calculate mail quota if this domain has limited max quota. if domainProfile.maxquota > 0: # Get used quota. qr = domainLib.getAllocatedQuotaSize(domain=self.domain) if qr[0] is True: allocatedQuota = qr[1] else: return qr spareQuota = domainProfile.maxquota - allocatedQuota if spareQuota > 0: if spareQuota < mailQuota: mailQuota = spareQuota else: # No enough quota. return (False, 'EXCEEDED_DOMAIN_QUOTA_SIZE') # # Get password from <form>. # newpw = web.safestr(data.get('newpw', '')) confirmpw = web.safestr(data.get('confirmpw', '')) resultOfPW = iredutils.verify_new_password( newpw, confirmpw, min_passwd_length=settings.min_passwd_length, max_passwd_length=settings.max_passwd_length, ) if resultOfPW[0] is True: pwscheme = None if 'storePasswordInPlainText' in data and settings.STORE_PASSWORD_IN_PLAIN_TEXT: pwscheme = 'PLAIN' passwd = iredutils.generate_password_for_sql_mail_account(resultOfPW[1], pwscheme=pwscheme) else: return resultOfPW # Get display name from <form> cn = data.get('cn', '') # Get storage base directory. tmpStorageBaseDirectory = settings.storage_base_directory.lower() splitedSBD = tmpStorageBaseDirectory.rstrip('/').split('/') storageNode = splitedSBD.pop() storageBaseDirectory = '/'.join(splitedSBD) try: # Store new user in SQL db. self.conn.insert( 'mailbox', domain=self.domain, username=self.mail, password=passwd, name=cn, maildir=iredutils.generate_maildir_path(self.mail), quota=mailQuota, storagebasedirectory=storageBaseDirectory, storagenode=storageNode, created=iredutils.get_gmttime(), active='1', local_part=mail_local_part, ) # Create an alias account: address=goto. self.conn.insert( 'alias', address=self.mail, goto=self.mail, domain=self.domain, created=iredutils.get_gmttime(), active='1', ) web.logger(msg="Create user: %s." % (self.mail), domain=self.domain, event='create',) return (True,) except Exception, e: return (False, str(e))