moulinette/yunohost_user.py

314 lines
10 KiB
Python
Raw Normal View History

2012-10-06 17:10:19 +02:00
# -*- coding: utf-8 -*-
2012-10-08 18:16:43 +02:00
import os
2012-10-07 17:57:57 +02:00
import sys
2012-10-06 17:57:08 +02:00
import ldap
2012-10-07 23:51:40 +02:00
import crypt
import random
import string
2012-10-07 17:57:57 +02:00
import getpass
2012-11-08 19:20:13 +01:00
from yunohost import YunoHostError, YunoHostLDAP, win_msg, colorize, validate, get_required_args
2012-10-07 16:20:20 +02:00
def user_list(fields=None, filter=None, limit=None, offset=None):
2012-10-28 17:27:47 +01:00
"""
List YunoHost users from LDAP
Keyword argument:
fields -- Fields to fetch
filter -- LDAP filter to use
limit -- Number of user to fetch
offset -- User number to begin with
2012-10-28 17:27:47 +01:00
Returns:
Dict
"""
2012-11-08 19:20:13 +01:00
with YunoHostLDAP() as yldap:
user_attrs = ['uid', 'mail', 'cn', 'mailalias']
attrs = []
result_dict = {}
if offset: offset = int(offset)
2012-11-08 19:20:13 +01:00
else: offset = 0
if limit: limit = int(limit)
2012-11-08 19:20:13 +01:00
else: limit = 1000
if not filter: filter = 'uid=*'
if fields:
for attr in fields:
2012-11-08 19:20:13 +01:00
if attr in user_attrs:
attrs.append(attr)
continue
else:
raise YunoHostError(22, _("Invalid field : ") + attr)
else:
attrs = user_attrs
2012-10-28 17:27:47 +01:00
2012-11-08 19:20:13 +01:00
result = yldap.search('ou=users,dc=yunohost,dc=org', filter, attrs)
if result and len(result) > (0 + offset) and limit > 0:
i = 0 + offset
for user in result[i:]:
if i < limit:
entry = {
'Username': user['uid'],
'Fullname': user['cn'],
'Mail': user['mail'][0]
}
if len(user['mail']) > 1:
entry['Mail Forward'] = user['mail'][1:]
if 'mailalias' in user:
entry['Mail Aliases'] = user['mailalias']
result_dict[str(i)] = entry
i += 1
else:
raise YunoHostError(167, _("No user found"))
2012-10-28 17:27:47 +01:00
return result_dict
2012-10-07 17:57:57 +02:00
def user_create(username, firstname, lastname, mail, password):
2012-10-07 23:51:40 +02:00
"""
Add user to LDAP
Keyword argument:
username
firstname
lastname
password
2012-10-07 23:51:40 +02:00
Returns:
2012-10-28 17:27:47 +01:00
Dict
2012-10-07 23:51:40 +02:00
"""
2012-11-08 19:20:13 +01:00
with YunoHostLDAP() as yldap:
# Validate password length
if len(password) < 4:
2012-11-08 19:20:13 +01:00
raise YunoHostError(22, _("Password is too short"))
yldap.validate_uniqueness({
'uid' : username,
'mail' : mail,
'mailalias' : mail
2012-11-08 19:20:13 +01:00
})
# Check if unix user already exists (doesn't work)
#if not os.system("getent passwd " + username):
2012-11-08 19:20:13 +01:00
# raise YunoHostError(17, _("Username not available"))
#TODO: check if mail belongs to a domain
# Get random UID/GID
uid_check = gid_check = 0
while uid_check == 0 and gid_check == 0:
uid = str(random.randint(200, 99999))
uid_check = os.system("getent passwd " + uid)
gid_check = os.system("getent group " + uid)
# Adapt values for LDAP
fullname = firstname + ' ' + lastname
rdn = 'uid=' + username + ',ou=users'
2012-11-08 19:20:13 +01:00
char_set = string.ascii_uppercase + string.digits
salt = ''.join(random.sample(char_set,8))
salt = '$1$' + salt + '$'
pwd = '{CRYPT}' + crypt.crypt(str(password), salt)
2012-11-08 19:20:13 +01:00
attr_dict = {
'objectClass' : ['mailAccount', 'inetOrgPerson', 'posixAccount'],
'givenName' : firstname,
'sn' : lastname,
2012-11-08 19:20:13 +01:00
'displayName' : fullname,
'cn' : fullname,
'uid' : username,
'mail' : mail,
2012-11-08 19:20:13 +01:00
'userPassword' : pwd,
'gidNumber' : uid,
'uidNumber' : uid,
'homeDirectory' : '/home/' + username,
2012-11-08 19:20:13 +01:00
'loginShell' : '/bin/false'
}
if yldap.add(rdn, attr_dict):
# Create user /home directory by switching user
os.system("su - " + username + " -c ''")
2012-11-08 19:20:13 +01:00
#TODO: Send a welcome mail to user
win_msg(_("User successfully created"))
return { _("Fullname") : fullname, _("Username") : username, _("Mail") : mail }
2012-11-08 19:20:13 +01:00
else:
raise YunoHostError(169, _("An error occured during user creation"))
def user_delete(users, purge=None):
2012-10-29 12:35:29 +01:00
"""
Remove user from LDAP
Keyword argument:
users -- List of users to delete or single user
purge -- Whether or not purge /home/user directory
2012-10-29 12:35:29 +01:00
Returns:
Dict
"""
2012-11-08 19:20:13 +01:00
with YunoHostLDAP() as yldap:
result = { 'Users' : [] }
if not isinstance(users, list):
users = [ users ]
2012-11-08 19:20:13 +01:00
for user in users:
2012-11-08 19:20:13 +01:00
if yldap.remove('uid=' + user+ ',ou=users'):
if purge:
2012-11-08 19:20:13 +01:00
os.system('rm -rf /home/' + user)
result['Users'].append(user)
continue
else:
raise YunoHostError(169, _("An error occured during user deletion"))
2012-10-29 12:35:29 +01:00
2012-11-08 19:20:13 +01:00
win_msg(_("User(s) successfully deleted"))
2012-10-29 12:35:29 +01:00
return result
def user_update(username, firstname=None, lastname=None, mail=None, change_password=None,
add_mailforward=None, remove_mailforward=None,
add_mailalias=None, remove_mailalias=None):
2012-10-29 15:43:43 +01:00
"""
Update user informations
Keyword argument:
username -- Username to update
firstname
lastname
mail
change_password -- New password
add_mailforward
remove_mailforward
add_mailalias
remove_mailalias
2012-10-29 15:43:43 +01:00
Returns:
Dict
"""
2012-11-08 19:20:13 +01:00
with YunoHostLDAP() as yldap:
attrs_to_fetch = ['givenName', 'sn', 'mail', 'mailAlias']
new_attr_dict = {}
# Populate user informations
result = yldap.search(base='ou=users,dc=yunohost,dc=org', filter='uid=' + username, attrs=attrs_to_fetch)
2012-11-08 19:20:13 +01:00
if not result:
raise YunoHostError(167, _("No user found"))
user = result[0]
# Get modifications from arguments
if firstname:
new_attr_dict['givenName'] = firstname # TODO: Validate
new_attr_dict['cn'] = new_attr_dict['displayName'] = firstname + ' ' + user['sn'][0]
2012-11-08 19:20:13 +01:00
if lastname:
new_attr_dict['sn'] = lastname # TODO: Validate
new_attr_dict['cn'] = new_attr_dict['displayName'] = user['givenName'][0] + ' ' + lastname
2012-11-08 19:20:13 +01:00
if lastname and firstname:
new_attr_dict['cn'] = new_attr_dict['displayName'] = firstname + ' ' + lastname
2012-11-08 19:20:13 +01:00
if change_password:
2012-11-08 19:20:13 +01:00
char_set = string.ascii_uppercase + string.digits
salt = ''.join(random.sample(char_set,8))
salt = '$1$' + salt + '$'
new_attr_dict['userPassword'] = '{CRYPT}' + crypt.crypt(str(change_password), salt)
2012-11-08 19:20:13 +01:00
if mail:
2012-10-29 15:43:43 +01:00
yldap.validate_uniqueness({
'mail' : mail,
'mailalias' : mail
2012-10-29 15:43:43 +01:00
})
2012-11-08 19:20:13 +01:00
del user['mail'][0]
new_attr_dict['mail'] = [mail] + user['mail']
2012-11-08 19:20:13 +01:00
if add_mailforward:
if not isinstance(add_mailforward, list):
add_mailforward = [ add_mailforward ]
for mail in add_mailforward:
2012-11-08 19:20:13 +01:00
yldap.validate_uniqueness({
'mail' : mail,
'mailalias' : mail
})
user['mail'].append(mail)
new_attr_dict['mail'] = user['mail']
if remove_mailforward:
if not isinstance(remove_mailforward, list):
remove_mailforward = [ remove_mailforward ]
for mail in remove_mailforward:
2012-11-08 19:20:13 +01:00
if len(user['mail']) > 1 and mail in user['mail'][1:]:
user['mail'].remove(mail)
else:
raise YunoHostError(22, _("Invalid mail forward : ") + mail)
new_attr_dict['mail'] = user['mail']
if add_mailalias:
if not isinstance(add_mailalias, list):
add_mailalias = [ add_mailalias ]
for mail in add_mailalias:
2012-11-08 19:20:13 +01:00
yldap.validate_uniqueness({
'mail' : mail,
'mailalias' : mail
})
if 'mailalias' in user:
user['mailalias'].append(mail)
else:
user['mailalias'] = [ mail ]
new_attr_dict['mailalias'] = user['mailalias']
if remove_mailalias:
if not isinstance(remove_mailalias, list):
remove_mailalias = [ remove_mailalias ]
for mail in remove_mailalias:
2012-11-08 19:20:13 +01:00
if 'mailalias' in user and mail in user['mailalias']:
user['mailalias'].remove(mail)
else:
raise YunoHostError(22, _("Invalid mail alias : ") + mail)
new_attr_dict['mailalias'] = user['mailalias']
if yldap.update('uid=' + username + ',ou=users', new_attr_dict):
2012-11-08 19:20:13 +01:00
win_msg(_("User successfully updated"))
return user_info(username=username)
2012-11-08 19:20:13 +01:00
else:
raise YunoHostError(169, _("An error occured during user update"))
2012-10-29 15:43:43 +01:00
def user_info(username=None, mail=None):
"""
Fetch user informations from LDAP
Keyword argument:
username
mail
Returns:
Dict
"""
2012-11-08 19:20:13 +01:00
with YunoHostLDAP() as yldap:
user_attrs = ['cn', 'mail', 'uid', 'mailAlias']
if mail:
filter = 'mail=' + mail
2012-11-08 19:20:13 +01:00
else:
filter = 'uid=' + username
2012-11-08 19:20:13 +01:00
result = yldap.search('ou=users,dc=yunohost,dc=org', filter, user_attrs)
user = result[0]
result_dict = {
'Username': user['uid'],
'Fullname': user['cn'],
'Mail': user['mail'][0]
}
if len(user['mail']) > 1:
result_dict['Mail Forward'] = user['mail'][1:]
if 'mailalias' in user:
result_dict['Mail Aliases'] = user['mailalias']
if result:
return result_dict
else:
raise YunoHostError(167, _("No user found"))