Pattern matching + asking + bugfixes

This commit is contained in:
Kload 2012-11-09 18:04:15 +01:00
parent d54ebd86eb
commit b9f3369609
6 changed files with 192 additions and 254 deletions

View file

@ -75,8 +75,7 @@ user:
full: --username
help: Must be unique
ask: "Username"
#pattern: '^[a-z0-9_]+$'
pattern: 'aza'
pattern: '^[a-z0-9_]+$'
-f:
full: --firstname
ask: "Firstname"
@ -184,6 +183,8 @@ domain:
domain:
help: Domain name to add
nargs: '*'
ask: "New domain"
pattern: '^([a-zA-Z0-9]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)(\.[a-zA-Z0-9]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)*(\.[a-zA-Z]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)$'
### domain_remove()
remove:
@ -194,6 +195,8 @@ domain:
domain:
help: Domain(s) to delete
nargs: "*"
ask: "Domain to remove"
pattern: '^([a-zA-Z0-9]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)(\.[a-zA-Z0-9]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)*(\.[a-zA-Z]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)$'
### domain_info()
info:
@ -203,6 +206,7 @@ domain:
arguments:
domain:
help: ""
pattern: '^([a-zA-Z0-9]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)(\.[a-zA-Z0-9]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)*(\.[a-zA-Z]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)$'
### domain_renewcert()
renewcert:
@ -210,6 +214,7 @@ domain:
arguments:
domain:
help: ""
pattern: '^([a-zA-Z0-9]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)(\.[a-zA-Z0-9]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)*(\.[a-zA-Z]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)$'
#############################
# App #
@ -481,6 +486,7 @@ tools:
-d:
full: --domain
help: YunoHost main domain
pattern: '^([a-zA-Z0-9]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)(\.[a-zA-Z0-9]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)*(\.[a-zA-Z]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)$'
### tools_adminpw()
adminpw:
@ -488,8 +494,12 @@ tools:
arguments:
-o:
full: --old-password
ask: "Actual admin password"
password: yes
-n:
full: --new-password
ask: "New admin password"
password: yes
### tools_maindomain()
maindomain:
@ -497,8 +507,11 @@ tools:
arguments:
-o:
full: --old-domain
pattern: '^([a-zA-Z0-9]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)(\.[a-zA-Z0-9]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)*(\.[a-zA-Z]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)$'
-n:
full: --new-domain
ask: "New main domain"
pattern: '^([a-zA-Z0-9]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)(\.[a-zA-Z0-9]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)*(\.[a-zA-Z]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)$'
### tools_postinstall()
postinstall:
@ -507,6 +520,10 @@ tools:
-d:
full: --domain
help: YunoHost main domain
ask: "Main domain"
pattern: '^([a-zA-Z0-9]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)(\.[a-zA-Z0-9]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)*(\.[a-zA-Z]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)$'
-p:
full: --password
help: YunoHost admin password
ask: "New admin password"
password: yes

View file

@ -65,12 +65,12 @@ def parse_dict(action_map):
# Add general arguments
for arg_name, arg_params in action_map['general_arguments'].items():
if arg_params['full']:
arg_fullname = arg_params['full']
del arg_params['full']
parsers['general'].add_argument(arg_name, arg_fullname, **arg_params)
else:
parsers['general'].add_argument(arg_name, **arg_params)
if 'full' in arg_params:
arg_names = [arg_name, arg_params['full']]
arg_fullname = arg_params['full']
del arg_params['full']
else: arg_names = [arg_name]
parsers['general'].add_argument(*arg_names, **arg_params)
del action_map['general_arguments']
@ -91,6 +91,8 @@ def parse_dict(action_map):
# Add arguments
if 'arguments' in action_params:
for arg_name, arg_params in action_params['arguments'].items():
arg_fullname = False
if 'password' in arg_params:
if arg_params['password']: is_password = True
del arg_params['password']
@ -98,6 +100,7 @@ def parse_dict(action_map):
if 'full' in arg_params:
arg_names = [arg_name, arg_params['full']]
arg_fullname = arg_params['full']
del arg_params['full']
else: arg_names = [arg_name]
@ -106,7 +109,7 @@ def parse_dict(action_map):
if (category != sys.argv[1]) or (action != sys.argv[2]):
require_input = False
for name in arg_names:
if name in sys.argv: require_input = False
if name in sys.argv[2:]: require_input = False
if require_input:
if is_password:
@ -118,30 +121,34 @@ def parse_dict(action_map):
sys.exit(1)
else:
raise YunoHostError(22, _("Missing arguments") + ': ' + arg_name)
new_args.extend([arg_name, pwd1])
if arg_name[0] == '-': arg_extend = [arg_name, pwd1]
else: arg_extend = [pwd1]
else:
if os.isatty(1):
arg_value = raw_input(colorize(arg_params['ask'] + ': ', 'cyan'))
else:
raise YunoHostError(22, _("Missing arguments") + ': ' + arg_name)
new_args.extend([arg_name, arg_value])
if arg_name[0] == '-': arg_extend = [arg_name, arg_value]
else: arg_extend = [arg_value]
new_args.extend(arg_extend)
del arg_params['ask']
if 'pattern' in arg_params:
if (category == sys.argv[1]) and (action == sys.argv[2]):
if 'dest' in arg_params: name = arg_params['dest']
elif arg_fullname: name = arg_fullname
elif arg_fullname: name = arg_fullname[2:]
else: name = arg_name
patterns[name] = arg_params['pattern']
del arg_params['pattern']
del arg_params['pattern']
parsers[category + '_' + action].add_argument(*arg_names, **arg_params)
args = parsers['general'].parse_args(sys.argv.extend(new_args))
args_dict = vars(args)
print patterns
print args_dict
for key, value in patterns.items():
validate({ args_dict[key] : value })
validate(value, args_dict[key])
return args

View file

@ -88,24 +88,26 @@ def str_to_func(astr):
return func
def validate(regex_dict):
def validate(pattern, array):
"""
Validate attributes with a pattern
Keyword arguments:
regex_dict -- Dictionnary of values/pattern to check
pattern -- Regex to match with the strings
array -- List of strings to check
Returns:
Boolean | YunoHostError
"""
print regex_dict
for attr, pattern in regex_dict.items():
if re.match(pattern, attr):
continue
if isinstance(array, str):
array = [array]
for string in array:
if re.match(pattern, string):
pass
else:
raise YunoHostError(22, _('Invalid attribute') + ' ' + attr)
return True
raise YunoHostError(22, _('Invalid attribute') + ' ' + string)
return True
def get_required_args(args, required_args, password=False):
"""
@ -156,62 +158,6 @@ def display_error(error):
print(json.dumps({ 'error' : error.message }))
def connect_services(action_map):
"""
Connect to different services needed by the action
Keyword arguments:
action_map -- Map of actions
Returns:
Dict -- openned connections or error code
"""
action_dict = action_map[sys.argv[1]]['actions'][sys.argv[2]]
connections = {}
required_connections = []
if 'connections' in action_dict:
required_connections = action_dict['connections']
try:
# Connect to different services if the action is requiring it
if 'ldap' in required_connections:
connections['ldap'] = YunoHostLDAP()
if 'firewall' in required_connections:
connections['firewall'] = open('/etc/init.d/iptables', 'w')
# TODO: Add other services connections
except YunoHostError, error:
display_error(error)
sys.exit(error.code)
else:
return connections
def disconnect_services(connections):
"""
Disconnect openned connections
Keyword arguments:
connections -- Dictionnary of openned connections
Returns:
Boolean
"""
try:
if 'ldap' in connections:
connections['ldap'].disconnect()
if 'firewall' in connections:
connections['firewall'].close()
# TODO: Add other services deconnections
except YunoHostError, error:
display_error(error)
sys.exit(error.code)
else:
return True
class YunoHostError(Exception):
"""
Custom exception

View file

@ -5,156 +5,150 @@ import sys
import datetime
import re
from urllib import urlopen
from yunohost import YunoHostError, win_msg, colorize, validate, get_required_args
from yunohost import YunoHostError, YunoHostLDAP, win_msg, colorize, validate, get_required_args
def domain_list(args, connections):
def domain_list(args):
"""
List YunoHost domains
Keyword argument:
args -- Dictionnary of values (can be empty)
connections -- LDAP connection
Returns:
Dict
"""
yldap = connections['ldap']
result_dict = {}
if args['offset']: offset = int(args['offset'])
else: offset = 0
if args['limit']: limit = int(args['limit'])
else: limit = 1000
if args['filter']: filter = args['filter']
else: filter = 'virtualdomain=*'
with YunoHostLDAP() as yldap:
result_dict = {}
if args['offset']: offset = int(args['offset'])
else: offset = 0
if args['limit']: limit = int(args['limit'])
else: limit = 1000
if args['filter']: filter = args['filter']
else: filter = 'virtualdomain=*'
result = yldap.search('ou=domains,dc=yunohost,dc=org', filter, attrs=['virtualdomain'])
if result and len(result) > (0 + offset) and limit > 0:
i = 0 + offset
for domain in result[i:]:
if i < limit:
result_dict[str(i)] = domain['virtualdomain']
i += 1
else:
raise YunoHostError(167, _("No domain found"))
result = yldap.search('ou=domains,dc=yunohost,dc=org', filter, attrs=['virtualdomain'])
if result and len(result) > (0 + offset) and limit > 0:
i = 0 + offset
for domain in result[i:]:
if i < limit:
result_dict[str(i)] = domain['virtualdomain']
i += 1
else:
raise YunoHostError(167, _("No domain found"))
return result_dict
return result_dict
def domain_add(args, connections):
def domain_add(args):
"""
Add one or more domains
Keyword argument:
args -- Dictionnary of values (can be empty)
connections -- LDAP connection
Returns:
Dict
"""
yldap = connections['ldap']
attr_dict = { 'objectClass' : ['mailDomain', 'top'] }
ip = str(urlopen('http://ip.yunohost.org').read())
now = datetime.datetime.now()
timestamp = str(now.year) + str(now.month) + str(now.day)
result = []
with YunoHostLDAP() as yldap:
attr_dict = { 'objectClass' : ['mailDomain', 'top'] }
ip = str(urlopen('http://ip.yunohost.org').read())
now = datetime.datetime.now()
timestamp = str(now.year) + str(now.month) + str(now.day)
result = []
args = get_required_args(args, { 'domain' : _('New domain') })
if not isinstance(args['domain'], list):
args['domain'] = [ args['domain'] ]
for domain in args['domain']:
validate({ domain : r'^([a-zA-Z0-9]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)(\.[a-zA-Z0-9]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)*(\.[a-zA-Z]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)$' })
yldap.validate_uniqueness({ 'virtualdomain' : domain })
attr_dict['virtualdomain'] = domain
if not isinstance(args['domain'], list):
args['domain'] = [ args['domain'] ]
for domain in args['domain']:
yldap.validate_uniqueness({ 'virtualdomain' : domain })
attr_dict['virtualdomain'] = domain
try:
with open('/var/lib/bind/'+ domain +'.zone') as f: pass
except IOError as e:
zone_lines = [
'$TTL 38400',
domain +'. IN SOA ns.'+ domain +'. root.'+ domain +'. '+ timestamp +' 10800 3600 604800 38400',
domain +'. IN NS ns.'+ domain +'.',
domain +'. IN A '+ ip,
domain +'. IN MX 5 mail.'+ domain +'.',
domain +'. IN TXT "v=spf1 a mx a:'+ domain +' ?all"',
'mail.'+ domain +'. IN A '+ ip,
'ns.'+ domain +'. IN A '+ ip,
'root.'+ domain +'. IN A '+ ip
try:
with open('/var/lib/bind/'+ domain +'.zone') as f: pass
except IOError as e:
zone_lines = [
'$TTL 38400',
domain +'. IN SOA ns.'+ domain +'. root.'+ domain +'. '+ timestamp +' 10800 3600 604800 38400',
domain +'. IN NS ns.'+ domain +'.',
domain +'. IN A '+ ip,
domain +'. IN MX 5 mail.'+ domain +'.',
domain +'. IN TXT "v=spf1 a mx a:'+ domain +' ?all"',
'mail.'+ domain +'. IN A '+ ip,
'ns.'+ domain +'. IN A '+ ip,
'root.'+ domain +'. IN A '+ ip
]
with open('/var/lib/bind/' + domain + '.zone', 'w') as zone:
for line in zone_lines:
zone.write(line + '\n')
else:
raise YunoHostError(17, _("Zone file already exists for ") + domain)
conf_lines = [
'zone "'+ domain +'" {',
' type master;',
' file "/var/lib/bind/'+ domain +'.zone";',
' allow-transfer {',
' 127.0.0.1;',
' localnets;',
' };',
'};'
]
with open('/var/lib/bind/' + domain + '.zone', 'w') as zone:
for line in zone_lines:
zone.write(line + '\n')
else:
raise YunoHostError(17, _("Zone file already exists for ") + domain)
with open('/etc/bind/named.conf.local', 'a') as conf:
for line in conf_lines:
conf.write(line + '\n')
conf_lines = [
'zone "'+ domain +'" {',
' type master;',
' file "/var/lib/bind/'+ domain +'.zone";',
' allow-transfer {',
' 127.0.0.1;',
' localnets;',
' };',
'};'
]
with open('/etc/bind/named.conf.local', 'a') as conf:
for line in conf_lines:
conf.write(line + '\n')
if yldap.add('virtualdomain=' + domain + ',ou=domains', attr_dict):
result.append(domain)
continue
else:
raise YunoHostError(169, _("An error occured during domain creation"))
if yldap.add('virtualdomain=' + domain + ',ou=domains', attr_dict):
result.append(domain)
continue
else:
raise YunoHostError(169, _("An error occured during domain creation"))
win_msg(_("Domain(s) successfully created"))
win_msg(_("Domain(s) successfully created"))
return { 'Domains' : result }
return { 'Domains' : result }
def domain_remove(args, connections):
def domain_remove(args):
"""
Remove domain from LDAP
Keyword argument:
args -- Dictionnary of values
connections -- LDAP connection
Returns:
Dict
"""
yldap = connections['ldap']
result = []
with YunoHostLDAP() as yldap:
result = []
args = get_required_args(args, { 'domain' : _('Domain to remove') })
if not isinstance(args['domain'], list):
args['domain'] = [ args['domain'] ]
if not isinstance(args['domain'], list):
args['domain'] = [ args['domain'] ]
for domain in args['domain']:
validate({ domain : r'^([a-zA-Z0-9]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)(\.[a-zA-Z0-9]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)*(\.[a-zA-Z]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)$' })
if yldap.remove('virtualdomain=' + domain + ',ou=domains'):
try:
os.remove('/var/lib/bind/'+ domain +'.zone')
except:
pass
with open('/etc/bind/named.conf.local', 'r') as conf:
conf_lines = conf.readlines()
with open('/etc/bind/named.conf.local', 'w') as conf:
in_block = False
for line in conf_lines:
if re.search(r'^zone "'+ domain, line):
in_block = True
if in_block:
if re.search(r'^};$', line):
in_block = False
else:
conf.write(line)
result.append(domain)
continue
else:
raise YunoHostError(169, _("An error occured during domain deletion"))
for domain in args['domain']:
if yldap.remove('virtualdomain=' + domain + ',ou=domains'):
try:
os.remove('/var/lib/bind/'+ domain +'.zone')
except:
pass
with open('/etc/bind/named.conf.local', 'r') as conf:
conf_lines = conf.readlines()
with open('/etc/bind/named.conf.local', 'w') as conf:
in_block = False
for line in conf_lines:
if re.search(r'^zone "'+ domain, line):
in_block = True
if in_block:
if re.search(r'^};$', line):
in_block = False
else:
conf.write(line)
result.append(domain)
continue
else:
raise YunoHostError(169, _("An error occured during domain deletion"))
win_msg(_("Domain(s) successfully deleted"))
return { 'Domains' : result }
win_msg(_("Domain(s) successfully deleted"))
return { 'Domains' : result }

View file

@ -8,48 +8,47 @@ import getpass
from yunohost import YunoHostError, YunoHostLDAP, validate, colorize, get_required_args, win_msg
def tools_ldapinit(args, connections):
def tools_ldapinit(args):
"""
Initialize YunoHost LDAP scheme
Keyword arguments:
args
connections
Returns:
dict
"""
yldap = connections['ldap']
with YunoHostLDAP() as yldap:
with open('ldap_scheme.yml') as f:
ldap_map = yaml.load(f)
with open('ldap_scheme.yml') as f:
ldap_map = yaml.load(f)
for rdn, attr_dict in ldap_map['parents'].items():
yldap.add(rdn, attr_dict)
for rdn, attr_dict in ldap_map['parents'].items():
yldap.add(rdn, attr_dict)
for rdn, attr_dict in ldap_map['childs'].items():
yldap.add(rdn, attr_dict)
for rdn, attr_dict in ldap_map['childs'].items():
yldap.add(rdn, attr_dict)
validate({ args['domain'] : r'^([a-zA-Z0-9]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)(\.[a-zA-Z0-9]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)*(\.[a-zA-Z]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)$' })
domain_dict = {
'objectClass' : ['mailDomain', 'top'],
'virtualdomain' : args['domain']
}
yldap.add('virtualdomain=' + args['domain'] + ',ou=domains', domain_dict)
domain_dict = {
'objectClass' : ['mailDomain', 'top'],
'virtualdomain' : args['domain']
}
admin_dict = {
'cn': 'admin',
'uid': 'admin',
'description': 'LDAP Administrator',
'gidNumber': '1007',
'uidNumber': '1007',
'homeDirectory': '/home/admin',
'loginShell': '/bin/bash',
'objectClass': ['organizationalRole', 'posixAccount', 'simpleSecurityObject']
}
yldap.add('virtualdomain=' + args['domain'] + ',ou=domains', domain_dict)
yldap.update('cn=admin', admin_dict)
admin_dict = {
'cn': 'admin',
'uid': 'admin',
'description': 'LDAP Administrator',
'gidNumber': '1007',
'uidNumber': '1007',
'homeDirectory': '/home/admin',
'loginShell': '/bin/bash',
'objectClass': ['organizationalRole', 'posixAccount', 'simpleSecurityObject']
}
yldap.update('cn=admin', admin_dict)
win_msg(_("LDAP has been successfully initialized"))
@ -65,15 +64,6 @@ def tools_adminpw(args):
dict
"""
if not 'old' in args:
args['old'] = getpass.getpass(colorize('Actual admin password: ', 'cyan'))
if not 'new' in args:
args['new'] = getpass.getpass(colorize('New admin password: ', 'cyan'))
pwd2 = getpass.getpass(colorize('Retype new password: ', 'cyan'))
if args['new'] != pwd2:
raise YunoHostError(22, _("Passwords doesn't match"))
# Validate password length
if len(args['new']) < 4:
raise YunoHostError(22, _("Password is too short"))
@ -97,16 +87,11 @@ def tools_maindomain(args):
dict
"""
args = get_required_args(args, {'new_domain' : _('New main domain name')})
if not args['old_domain']:
with open('/usr/share/yunohost/yunohost-config/others/current_host', 'r') as f:
args['old_domain'] = f.readline().rstrip()
validate({
args['new_domain'] : r'^([a-zA-Z0-9]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)(\.[a-zA-Z0-9]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)*(\.[a-zA-Z]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)$',
args['old_domain'] : r'^([a-zA-Z0-9]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)(\.[a-zA-Z0-9]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)*(\.[a-zA-Z]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)$'
})
validate(r'^([a-zA-Z0-9]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)(\.[a-zA-Z0-9]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)*(\.[a-zA-Z]{1}([a-zA-Z0-9\-]*[a-zA-Z0-9])*)$', args['old_domain'])
config_files = [
'/etc/postfix/main.cf',
@ -155,7 +140,7 @@ def tools_maindomain(args):
n = os.system('/etc/init.d/postfix restart')
o = os.system('/etc/init.d/ejabberd restart')
if a == b == c == d == e == f == g == h == i == j == k == l == m == n == o:
if a == b == c == d == e == f == g == h == i == j == k == l == m == n == o == 0:
win_msg(_("YunoHost main domain has been successfully changed"))
else:
raise YunoHostError(17, _("There were a problem during domain changing"))
@ -167,31 +152,28 @@ def tools_postinstall(args):
Keyword arguments:
args
connection
Returns:
dict
"""
connections = { 'ldap' : YunoHostLDAP(password='yunohost') }
try:
with open('/usr/share/yunohost/yunohost-config/others/installed') as f: pass
except IOError:
print('Installing YunoHost')
else:
raise YunoHostError(17, _("YunoHost is already installed"))
with YunoHostLDAP(password='yunohost') as yldap:
try:
with open('/usr/share/yunohost/yunohost-config/others/installed') as f: pass
except IOError:
print('Installing YunoHost')
else:
raise YunoHostError(17, _("YunoHost is already installed"))
args = get_required_args(args, {'domain' : _('Main domain name'), 'password' : _('New admin password') }, True)
# New domain config
tools_maindomain({ 'old_domain' : 'yunohost.org', 'new_domain' : args['domain']})
# New domain config
tools_maindomain({ 'old_domain' : 'yunohost.org', 'new_domain' : args['domain']})
# Initialize YunoHost LDAP base
tools_ldapinit(args)
# Initialize YunoHost LDAP base
tools_ldapinit(args, connections)
# Change LDAP admin password
tools_adminpw({ 'old' : 'yunohost', 'new' : args['password']})
# Change LDAP admin password
tools_adminpw({ 'old' : 'yunohost', 'new' : args['password']})
os.system('touch /usr/share/yunohost/yunohost-config/others/installed')
os.system('touch /usr/share/yunohost/yunohost-config/others/installed')
win_msg(_("YunoHost has been successfully configured"))

View file

@ -73,7 +73,6 @@ def user_create(args):
Returns:
Dict
"""
print args
with YunoHostLDAP() as yldap:
# Validate password length
if len(args['password']) < 4:
@ -148,7 +147,6 @@ def user_delete(args):
args['users'] = [ args['users'] ]
for user in args['users']:
validate({ user : r'^[a-z0-9_]+$' })
if yldap.remove('uid=' + user+ ',ou=users'):
if args['purge']:
os.system('rm -rf /home/' + user)
@ -172,7 +170,6 @@ def user_update(args):
Dict
"""
with YunoHostLDAP() as yldap:
validate({ args['user'] : r'^[a-z0-9_]+$' })
attrs_to_fetch = ['givenName', 'sn', 'mail', 'mailAlias']
new_attr_dict = {}
@ -201,7 +198,6 @@ def user_update(args):
new_attr_dict['userPassword'] = '{CRYPT}' + crypt.crypt(str(args['change_password']), salt)
if args['mail']:
validate({ args['mail'] : r'^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,6}$' })
yldap.validate_uniqueness({
'mail' : args['mail'],
'mailalias' : args['mail']
@ -213,7 +209,6 @@ def user_update(args):
if not isinstance(args['add_mailforward'], list):
args['add_mailforward'] = [ args['add_mailforward'] ]
for mail in args['add_mailforward']:
validate({ mail : r'^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,6}$' })
yldap.validate_uniqueness({
'mail' : mail,
'mailalias' : mail
@ -235,7 +230,6 @@ def user_update(args):
if not isinstance(args['add_mailalias'], list):
args['add_mailalias'] = [ args['add_mailalias'] ]
for mail in args['add_mailalias']:
validate({ mail : r'^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,6}$' })
yldap.validate_uniqueness({
'mail' : mail,
'mailalias' : mail
@ -278,11 +272,9 @@ def user_info(args):
user_attrs = ['cn', 'mail', 'uid', 'mailAlias']
if args['mail']:
validate({ args['mail'] : r'^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,6}$' })
filter = 'mail=' + args['mail']
else:
args = get_required_args(args, { 'user' : _("Username") })
validate({ args['user'] : r'^[a-z0-9_]+$' })
filter = 'uid=' + args['user']
result = yldap.search('ou=users,dc=yunohost,dc=org', filter, user_attrs)