This commit is contained in:
root 2012-11-08 19:20:13 +01:00
parent 0e17445ff0
commit d54ebd86eb
4 changed files with 295 additions and 268 deletions

View file

@ -58,7 +58,6 @@ user:
-f: -f:
full: --filter full: --filter
help: LDAP filter used to search help: LDAP filter used to search
pattern: 'yayaya'
-l: -l:
full: --limit full: --limit
help: Maximum number of user fetched help: Maximum number of user fetched
@ -75,15 +74,24 @@ user:
-u: -u:
full: --username full: --username
help: Must be unique help: Must be unique
ask: "Username"
#pattern: '^[a-z0-9_]+$'
pattern: 'aza'
-f: -f:
full: --firstname full: --firstname
ask: "Firstname"
-l: -l:
full: --lastname full: --lastname
ask: "Lastname"
-m: -m:
full: --mail full: --mail
help: Main mail address must be unique help: Main mail address must be unique
ask: "Mail address"
pattern: '^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,6}$'
-p: -p:
full: --password full: --password
ask: "User password"
password: yes
### user_delete() ### user_delete()
delete: delete:

View file

@ -24,6 +24,7 @@ import os
import sys import sys
import argparse import argparse
import gettext import gettext
import getpass
try: try:
import yaml import yaml
except ImportError: except ImportError:
@ -38,7 +39,7 @@ if not __debug__:
gettext.install('YunoHost') gettext.install('YunoHost')
try: try:
from yunohost import YunoHostError, YunoHostLDAP, str_to_func, colorize, pretty_print_dict, display_error, connect_services, disconnect_services, validate from yunohost import YunoHostError, YunoHostLDAP, str_to_func, colorize, pretty_print_dict, display_error, validate
except ImportError: except ImportError:
sys.stderr.write('Error: Yunohost CLI Require YunoHost lib\n') sys.stderr.write('Error: Yunohost CLI Require YunoHost lib\n')
sys.exit(1) sys.exit(1)
@ -59,6 +60,8 @@ def parse_dict(action_map):
parsers = subparsers_category = subparsers_action = {} parsers = subparsers_category = subparsers_action = {}
parsers['general'] = argparse.ArgumentParser() parsers['general'] = argparse.ArgumentParser()
subparsers = parsers['general'].add_subparsers() subparsers = parsers['general'].add_subparsers()
new_args = []
patterns = {}
# Add general arguments # Add general arguments
for arg_name, arg_params in action_map['general_arguments'].items(): for arg_name, arg_params in action_map['general_arguments'].items():
@ -88,28 +91,59 @@ def parse_dict(action_map):
# Add arguments # Add arguments
if 'arguments' in action_params: if 'arguments' in action_params:
for arg_name, arg_params in action_params['arguments'].items(): for arg_name, arg_params in action_params['arguments'].items():
if 'password' in arg_params:
if arg_params['password']: is_password = True
del arg_params['password']
else: is_password = False
if 'full' in arg_params: if 'full' in arg_params:
arg_fullname = arg_params['full'] arg_names = [arg_name, arg_params['full']]
del arg_params['full'] del arg_params['full']
else: arg_names = [arg_name]
if 'ask' in arg_params:
require_input = True
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 require_input:
if is_password:
if os.isatty(1):
pwd1 = getpass.getpass(colorize(arg_params['ask'] + ': ', 'cyan'))
pwd2 = getpass.getpass(colorize('Retype ' + arg_params['ask'][0].lower() + arg_params['ask'][1:] + ': ', 'cyan'))
if pwd1 != pwd2:
raise YunoHostError(22, _("Passwords don't match"))
sys.exit(1)
else: else:
arg_fullname = False raise YunoHostError(22, _("Missing arguments") + ': ' + arg_name)
new_args.extend([arg_name, 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])
del arg_params['ask']
if 'pattern' in arg_params: if 'pattern' in arg_params:
pattern = arg_params['pattern'] 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
else: name = arg_name
patterns[name] = arg_params['pattern']
del arg_params['pattern'] del arg_params['pattern']
def pmatch(string):
validate({ string : pattern })
if arg_fullname:
parsers[category + '_' + action].add_argument(arg_name, arg_fullname, type=pmatch, **arg_params)
else:
parsers[category + '_' + action].add_argument(arg_name, type=pmatch, **arg_params)
else:
if arg_fullname:
parsers[category + '_' + action].add_argument(arg_name, arg_fullname, **arg_params)
else:
parsers[category + '_' + action].add_argument(arg_name, **arg_params)
return parsers['general'].parse_args() 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
for key, value in patterns.items():
validate({ args_dict[key] : value })
return args
def main(): def main():
@ -126,12 +160,8 @@ def main():
with open('action_map.yml') as f: with open('action_map.yml') as f:
action_map = yaml.load(f) action_map = yaml.load(f)
args = parse_dict(action_map)
connections = connect_services(action_map)
try: try:
if connections: args = parse_dict(action_map)
result = args.func(vars(args), connections)
else:
result = args.func(vars(args)) result = args.func(vars(args))
except TypeError, error: except TypeError, error:
if not __debug__ : if not __debug__ :
@ -148,8 +178,6 @@ def main():
pretty_print_dict(result) pretty_print_dict(result)
else: else:
print(json.dumps(result)) print(json.dumps(result))
finally:
disconnect_services(connections)
return 0 return 0

View file

@ -99,6 +99,7 @@ def validate(regex_dict):
Boolean | YunoHostError Boolean | YunoHostError
""" """
print regex_dict
for attr, pattern in regex_dict.items(): for attr, pattern in regex_dict.items():
if re.match(pattern, attr): if re.match(pattern, attr):
continue continue
@ -242,27 +243,35 @@ class YunoHostError(Exception):
self.desc = code self.desc = code
class YunoHostLDAP: class YunoHostLDAP(object):
""" Specific LDAP functions for YunoHost """ """ Specific LDAP functions for YunoHost """
conn = None
def __init__(self, password=False): def __enter__(self, password=False):
""" """
Connect to LDAP base Connect to LDAP base
Initialize to localhost, base yunohost.org, prompt for password Initialize to localhost, base yunohost.org, prompt for password
""" """
if self.conn is None:
self.conn = ldap.initialize('ldap://localhost:389') self.conn = ldap.initialize('ldap://localhost:389')
self.base = 'dc=yunohost,dc=org' self.base = 'dc=yunohost,dc=org'
if password: if password:
self.pwd = password self.pwd = password
else: else:
try:
self.pwd = getpass.getpass(colorize(_('Admin Password: '), 'yellow')) self.pwd = getpass.getpass(colorize(_('Admin Password: '), 'yellow'))
except KeyboardInterrupt, EOFError:
raise YunoHostError(125, _("Interrupted"))
try: try:
self.conn.simple_bind_s('cn=admin,' + self.base, self.pwd) self.conn.simple_bind_s('cn=admin,' + self.base, self.pwd)
except ldap.INVALID_CREDENTIALS: except ldap.INVALID_CREDENTIALS:
raise YunoHostError(13, _('Invalid credentials')) raise YunoHostError(13, _('Invalid credentials'))
return self
def __exit__(self, type, value, traceback):
self.disconnect()
def disconnect(self): def disconnect(self):
""" """

View file

@ -7,20 +7,19 @@ import crypt
import random import random
import string import string
import getpass import getpass
from yunohost import YunoHostError, win_msg, colorize, validate, get_required_args from yunohost import YunoHostError, YunoHostLDAP, win_msg, colorize, validate, get_required_args
def user_list(args, connections): def user_list(args):
""" """
List YunoHost users from LDAP List YunoHost users from LDAP
Keyword argument: Keyword argument:
args -- Dictionnary of values (can be empty) args -- Dictionnary of values (can be empty)
connections -- LDAP connection
Returns: Returns:
Dict Dict
""" """
yldap = connections['ldap'] with YunoHostLDAP() as yldap:
user_attrs = ['uid', 'mail', 'cn', 'mailalias'] user_attrs = ['uid', 'mail', 'cn', 'mailalias']
attrs = [] attrs = []
result_dict = {} result_dict = {}
@ -64,36 +63,22 @@ def user_list(args, connections):
return result_dict return result_dict
def user_create(args, connections): def user_create(args):
""" """
Add user to LDAP Add user to LDAP
Keyword argument: Keyword argument:
args -- Dictionnary of values (can be empty) args -- Dictionnary of values (can be empty)
connections -- LDAP connections
Returns: Returns:
Dict Dict
""" """
yldap = connections['ldap'] print args
args = get_required_args(args, { with YunoHostLDAP() as yldap:
'username': _('Username'),
'mail': _('Mail address'),
'firstname': _('Firstname'),
'lastname': _('Lastname'),
'password': _('Password')
}, True)
# Validate password length # Validate password length
if len(args['password']) < 4: if len(args['password']) < 4:
raise YunoHostError(22, _("Password is too short")) raise YunoHostError(22, _("Password is too short"))
# Validate other values TODO: validate all values
validate({
args['username'] : r'^[a-z0-9_]+$',
args['mail'] : r'^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,6}$',
})
yldap.validate_uniqueness({ yldap.validate_uniqueness({
'uid' : args['username'], 'uid' : args['username'],
'mail' : args['mail'], 'mail' : args['mail'],
@ -145,18 +130,17 @@ def user_create(args, connections):
raise YunoHostError(169, _("An error occured during user creation")) raise YunoHostError(169, _("An error occured during user creation"))
def user_delete(args, connections): def user_delete(args):
""" """
Remove user from LDAP Remove user from LDAP
Keyword argument: Keyword argument:
args -- Dictionnary of values (can be empty) args -- Dictionnary of values (can be empty)
connections -- LDAP connection
Returns: Returns:
Dict Dict
""" """
yldap = connections['ldap'] with YunoHostLDAP() as yldap:
result = { 'Users' : [] } result = { 'Users' : [] }
args = get_required_args(args, { 'users' : _('User to delete') }) args = get_required_args(args, { 'users' : _('User to delete') })
@ -177,18 +161,17 @@ def user_delete(args, connections):
return result return result
def user_update(args, connections): def user_update(args):
""" """
Update user informations Update user informations
Keyword argument: Keyword argument:
args -- Dictionnary of values args -- Dictionnary of values
connections -- LDAP connection
Returns: Returns:
Dict Dict
""" """
yldap = connections['ldap'] with YunoHostLDAP() as yldap:
validate({ args['user'] : r'^[a-z0-9_]+$' }) validate({ args['user'] : r'^[a-z0-9_]+$' })
attrs_to_fetch = ['givenName', 'sn', 'mail', 'mailAlias'] attrs_to_fetch = ['givenName', 'sn', 'mail', 'mailAlias']
new_attr_dict = {} new_attr_dict = {}
@ -281,18 +264,17 @@ def user_update(args, connections):
def user_info(args, connections): def user_info(args):
""" """
Fetch user informations from LDAP Fetch user informations from LDAP
Keyword argument: Keyword argument:
args -- Dictionnary of values (can be empty) args -- Dictionnary of values (can be empty)
connections -- LDAP connection
Returns: Returns:
Dict Dict
""" """
yldap = connections['ldap'] with YunoHostLDAP() as yldap:
user_attrs = ['cn', 'mail', 'uid', 'mailAlias'] user_attrs = ['cn', 'mail', 'uid', 'mailAlias']
if args['mail']: if args['mail']: