Move some functionality from user-add to the backend ldap create function

This commit is contained in:
Rob Crittenden 2008-10-14 17:46:36 -04:00
parent 9788800aa4
commit 30664cde88
5 changed files with 63 additions and 71 deletions

View File

@ -25,7 +25,11 @@ This wraps the python-ldap bindings.
import ldap as _ldap
from ipalib import api
from ipalib import errors
from ipalib.crud import CrudBackend
from ipa_server import servercore
from ipa_server import ipaldap
import ldap
class ldap(CrudBackend):
@ -46,6 +50,18 @@ class ldap(CrudBackend):
)
def create(self, **kw):
return kw
if servercore.entry_exists(kw['dn']):
raise errors.DuplicateEntry("entry already exists")
entry = ipaldap.Entry(kw['dn'])
# dn isn't allowed to be in the entry itself
del kw['dn']
# Fill in our new entry
for k in kw:
entry.setValues(k, kw[k])
return servercore.add_entry(entry)
api.register(ldap)

View File

@ -184,18 +184,13 @@ def get_user_by_uid(uid, sattrs):
# User support
def user_exists(uid):
"""Return True if the exists, False otherwise."""
# FIXME: fix the filter
# FIXME: should accept a container to look in
# uid = self.__safe_filter(uid)
searchfilter = "(&(uid=%s)(objectclass=posixAccount))" % uid
def entry_exists(dn):
"""Return True if the entry exists, False otherwise."""
try:
get_sub_entry("cn=accounts," + basedn, searchfilter, ['dn','uid'])
get_base_entry(dn, "objectclass=*", ['dn','objectclass'])
return True
except errors.NotFound:
return True
return False
def get_user_by_uid (uid, sattrs):
"""Get a specific user's entry. Return as a dict of values.

View File

@ -13,16 +13,16 @@ def user_find(uid):
# main
server = xmlrpclib.ServerProxy("http://localhost:8888/")
print server.system.listMethods()
print server.system.methodHelp("user_add")
#print server.system.listMethods()
#print server.system.methodHelp("user_add")
try:
args="admin"
args="jsmith1"
kw = {'givenname':'Joe', 'sn':'Smith'}
result = server.user_add(args, kw)
result = server.user_add(kw, args)
print "returned %s" % result
except xmlrpclib.Fault, e:
print e.faultString
user_find("admin")
user_find("notfound")
#user_find("admin")
#user_find("notfound")

View File

@ -69,16 +69,17 @@ class user(frontend.Object):
default_from=lambda givenname, sn: givenname[0] + sn,
normalize=lambda value: value.lower(),
),
Param('gecos',
Param('gecos?',
doc='GECOS field',
default_from=lambda uid: uid,
),
Param('homedirectory',
Param('homedirectory?',
cli_name='home',
doc='Path of user home directory',
default_from=lambda uid: '/home/%s' % uid,
),
Param('shell',
Param('loginshell?',
cli_name='shell',
default=u'/bin/sh',
doc='Login shell',
),
@ -109,44 +110,22 @@ class user_add(crud.Add):
ldap = self.api.Backend.ldap
kw['uid'] = uid
kw['dn'] = ldap.get_user_dn(uid)
return ldap.create(**kw)
if servercore.user_exists(user['uid']):
raise errors.Duplicate("user already exists")
if servercore.uid_too_long(user['uid']):
if servercore.uid_too_long(kw['uid']):
raise errors.UsernameTooLong
# dn is set here, not by the user
try:
del user['dn']
except KeyError:
pass
# No need to set empty fields, and they can cause issues when they
# get to LDAP, like:
# TypeError: ('expected a string in the list', None)
for k in user.keys():
if not user[k] or len(user[k]) == 0 or (isinstance(user[k],list) and len(user[k]) == 1 and '' in user[k]):
del user[k]
dn="uid=%s,%s,%s" % (ldap.dn.escape_dn_chars(user['uid']),
user_container,servercore.basedn)
entry = ipaldap.Entry(dn)
# Get our configuration
config = servercore.get_ipa_config()
# Let us add in some missing attributes
if user.get('homedirectory') is None:
user['homedirectory'] = '%s/%s' % (config.get('ipahomesrootdir'), user.get('uid'))
user['homedirectory'] = user['homedirectory'].replace('//', '/')
user['homedirectory'] = user['homedirectory'].rstrip('/')
if user.get('loginshell') is None:
user['loginshell'] = config.get('ipadefaultloginshell')
if user.get('gecos') is None:
user['gecos'] = user['uid']
if kw.get('homedirectory') is None:
kw['homedirectory'] = '%s/%s' % (config.get('ipahomesrootdir'), kw.get('uid'))
kw['homedirectory'] = kw['homedirectory'].replace('//', '/')
kw['homedirectory'] = kw['homedirectory'].rstrip('/')
if kw.get('loginshell') is None:
kw['loginshell'] = config.get('ipadefaultloginshell')
if kw.get('gecos') is None:
kw['gecos'] = kw['uid']
# If uidnumber is blank the the FDS dna_plugin will automatically
# assign the next value. So we don't have to do anything with it.
@ -155,33 +134,27 @@ class user_add(crud.Add):
try:
default_group = servercore.get_entry_by_dn(group_dn, ['dn','gidNumber'])
if default_group:
user['gidnumber'] = default_group.get('gidnumber')
kw['gidnumber'] = default_group.get('gidnumber')
except errors.NotFound:
# Fake an LDAP error so we can return something useful to the user
raise errors.NotFound, "The default group for new users, '%s', cannot be found." % config.get('ipadefaultprimarygroup')
# Fake an LDAP error so we can return something useful to the kw
raise errors.NotFound, "The default group for new kws, '%s', cannot be found." % config.get('ipadefaultprimarygroup')
except Exception, e:
# catch everything else
raise e
if user.get('krbprincipalname') is None:
user['krbprincipalname'] = "%s@%s" % (user.get('uid'), servercore.realm)
if kw.get('krbprincipalname') is None:
kw['krbprincipalname'] = "%s@%s" % (kw.get('uid'), servercore.realm)
# FIXME. This is a hack so we can request separate First and Last
# name in the GUI.
if user.get('cn') is None:
user['cn'] = "%s %s" % (user.get('givenname'),
user.get('sn'))
if kw.get('cn') is None:
kw['cn'] = "%s %s" % (kw.get('givenname'),
kw.get('sn'))
# some required objectclasses
entry.setValues('objectClass', (config.get('ipauserobjectclasses')))
# entry.setValues('objectClass', ['top', 'person', 'organizationalPerson', 'inetOrgPerson', 'inetUser', 'posixAccount', 'krbPrincipalAux'])
kw['objectClass'] = config.get('ipauserobjectclasses')
# fill in our new entry with everything sent by the user
for u in user:
entry.setValues(u, user[u])
result = servercore.add_entry(entry)
return result
return ldap.create(**kw)
api.register(user_add)

View File

@ -8,6 +8,7 @@ import re
import threading
import commands
from ipalib import api
from ipalib import config
from ipa_server import conn
from ipa_server.servercore import context
import ipalib.load_plugins
@ -46,19 +47,21 @@ class LoggingSimpleXMLRPCRequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHa
"""
# this is fine for our test server
uid = commands.getoutput('/usr/bin/id -u')
# uid = commands.getoutput('/usr/bin/id -u')
uid = "500"
krbccache = "FILE:/tmp/krb5cc_" + uid
func = None
try:
# FIXME: don't hardcode host and port
context.conn = conn.IPAConn("localhost", 389, krbccache)
try:
# check to see if a matching function has been registered
func = funcs[method]
except KeyError:
raise Exception('method "%s" is not supported' % method)
(args, kw) = xmlrpc_unmarshal(*params)
# FIXME: don't hardcode host and port
context.conn = conn.IPAConn("localhost", 389, krbccache)
logger.info("calling %s" % method)
return func(*args, **kw)
finally:
# Clean up any per-request data and connections
@ -140,9 +143,14 @@ XMLRPCServer = StoppableXMLRPCServer(("",PORT), LoggingSimpleXMLRPCRequestHandle
XMLRPCServer.register_introspection_functions()
# Get and register all the methods
api.env.server_context = True
api.finalize()
# Initialize our environment
env_dict = config.read_config()
env_dict['server_context'] = True
api.env.update(config.generate_env(env_dict))
# Get and register all the methods
for cmd in api.Command:
logger.info("registering %s" % cmd)
XMLRPCServer.register_function(api.Command[cmd], cmd)