Implement user-find and user-add backend functions so they work over XML-RPC

Change port to 8880 to not conflict with a running IPA v1 instance
Encode incoming values from unicode as utf-8 before sending to LDAP
This commit is contained in:
Rob Crittenden 2008-10-04 01:50:59 -04:00
parent 3ffbaac64c
commit 7e4b0a072e
7 changed files with 113 additions and 20 deletions

View File

@ -33,7 +33,8 @@ import struct
import ldap.sasl import ldap.sasl
from ldap.controls import LDAPControl,DecodeControlTuples,EncodeControlTuples from ldap.controls import LDAPControl,DecodeControlTuples,EncodeControlTuples
from ldap.ldapobject import SimpleLDAPObject from ldap.ldapobject import SimpleLDAPObject
import ipautil from ipa_server import ipautil
# Global variable to define SASL auth # Global variable to define SASL auth
sasl_auth = ldap.sasl.sasl({},'GSSAPI') sasl_auth = ldap.sasl.sasl({},'GSSAPI')
@ -108,7 +109,11 @@ class Entry:
"""Convert the attrs and values to a list of 2-tuples. The first element """Convert the attrs and values to a list of 2-tuples. The first element
of the tuple is the attribute name. The second element is either a of the tuple is the attribute name. The second element is either a
single value or a list of values.""" single value or a list of values."""
return self.data.items() r = []
for i in self.data.iteritems():
n = ipautil.utf8_encode_values(i[1])
r.append((i[0], n))
return r
def __str__(self): def __str__(self):
"""Convert the Entry to its LDIF representation""" """Convert the Entry to its LDIF representation"""

View File

@ -188,3 +188,14 @@ def get_gsserror(e):
secondary = e[0][1] secondary = e[0][1]
return (primary[0], secondary[0]) return (primary[0], secondary[0])
def utf8_encode_value(value):
if isinstance(value,unicode):
return value.encode('utf-8')
return value
def utf8_encode_values(values):
if isinstance(values,list) or isinstance(values,tuple):
return map(utf8_encode_value, values)
else:
return utf8_encode_value(values)

View File

@ -31,6 +31,8 @@ krbctx = krbV.default_context()
realm = krbctx.default_realm realm = krbctx.default_realm
basedn = ipautil.realm_to_suffix(realm) basedn = ipautil.realm_to_suffix(realm)
DefaultUserContainer = "cn=users,cn=accounts"
def convert_entry(ent): def convert_entry(ent):
entry = dict(ent.data) entry = dict(ent.data)
entry['dn'] = ent.dn entry['dn'] = ent.dn

View File

@ -35,7 +35,7 @@ class xmlrpc(Backend):
def get_client(self): def get_client(self):
# FIXME: The server uri should come from self.api.env.server_uri # FIXME: The server uri should come from self.api.env.server_uri
return xmlrpclib.ServerProxy('http://localhost:8080', allow_none=True) return xmlrpclib.ServerProxy('http://localhost:8888', allow_none=True)
def forward_call(self, name, *args, **kw): def forward_call(self, name, *args, **kw):
""" """
@ -45,5 +45,6 @@ class xmlrpc(Backend):
command = getattr(client, name) command = getattr(client, name)
params = xmlrpc_marshal(*args, **kw) params = xmlrpc_marshal(*args, **kw)
return command(*params) return command(*params)
# return command(*args, **kw)
api.register(xmlrpc) api.register(xmlrpc)

View File

@ -25,7 +25,10 @@ from ipalib import frontend
from ipalib import crud from ipalib import crud
from ipalib.frontend import Param from ipalib.frontend import Param
from ipalib import api from ipalib import api
from ipa_server import servercore
from ipa_server import ipaldap
import ldap
from ipa_server.context import context
# Command to get the idea how plugins will interact with api.env # Command to get the idea how plugins will interact with api.env
class envtest(frontend.Command): class envtest(frontend.Command):
@ -71,7 +74,79 @@ api.register(user)
class user_add(crud.Add): class user_add(crud.Add):
'Add a new user.' 'Add a new user.'
def execute(self, *args, **kw): def execute(self, *args, **kw):
return 1 """args[0] = uid of the user to add
kw{container} is the location in the DIT to add the user, not
required
kw otherwise contains all the attributes
"""
# FIXME: ug, really?
if not kw.get('container'):
user_container = servercore.DefaultUserContainer
else:
user_container = kw['container']
del kw['container']
user = kw
if not isinstance(user, dict):
# FIXME, need proper error
raise SyntaxError
user['uid'] = args[0]
# 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)
# Let us add in some missing attributes
# FIXME, get config
# 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']
# FIXME: add to default group
user['gidNumber'] = "500"
if user.get('krbprincipalname') is None:
user['krbprincipalname'] = "%s@%s" % (user.get('uid'), self.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'))
# some required objectclasses
# FIXME
# entry.setValues('objectClass', (config.get('ipauserobjectclasses')))
entry.setValues('objectClass', ['top', 'person', 'organizationalPerson', 'inetOrgPerson', 'inetUser', 'posixAccount', 'krbPrincipalAux'])
# fill in our new entry with everything sent by the user
for u in user:
entry.setValues(u, user[u])
result = context.conn.getConn().addEntry(entry)
return result
api.register(user_add) api.register(user_add)
@ -87,10 +162,14 @@ api.register(user_mod)
class user_find(crud.Find): class user_find(crud.Find):
'Search the users.' 'Search the users.'
# def execute(self, *args, **kw): def execute(self, *args, **kw):
# uid=args[0] uid=args[0]
# result = servercore.get_sub_entry(servercore.basedn, "uid=%s" % uid, ["*"]) result = servercore.get_sub_entry(servercore.basedn, "uid=%s" % uid, ["*"])
# return result return result
def forward(self, *args, **kw):
result = super(crud.Find, self).forward(*args, **kw)
for a in result:
print a, ": ", res[a]
api.register(user_find) api.register(user_find)

View File

@ -43,7 +43,7 @@ class Dispatch(object):
return self.__cmd(*args, **kw) return self.__cmd(*args, **kw)
server = SimpleXMLRPCServer(('localhost', 8080), allow_none=True) server = SimpleXMLRPCServer(('localhost', 8880), allow_none=True)
server.register_introspection_functions() server.register_introspection_functions()
for cmd in api.Command(): for cmd in api.Command():
server.register_function(Dispatch(cmd), cmd.name) server.register_function(Dispatch(cmd), cmd.name)

View File

@ -1,8 +1,6 @@
#!/usr/bin/env python #!/usr/bin/env python
import sys import sys
sys.path.insert(0, "..")
sys.path.insert(0, ".")
import SimpleXMLRPCServer import SimpleXMLRPCServer
import logging import logging
import xmlrpclib import xmlrpclib
@ -10,9 +8,10 @@ import re
import threading import threading
import commands import commands
from ipalib import api from ipalib import api
import conn from ipa_server import conn
from ipa_server.servercore import context from ipa_server.servercore import context
import ipalib.load_plugins import ipalib.load_plugins
from ipalib.util import xmlrpc_unmarshal
import traceback import traceback
PORT=8888 PORT=8888
@ -59,12 +58,8 @@ class LoggingSimpleXMLRPCRequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHa
func = funcs[method] func = funcs[method]
except KeyError: except KeyError:
raise Exception('method "%s" is not supported' % method) raise Exception('method "%s" is not supported' % method)
if len(params) > 1 and isinstance(params[-1], dict): (args, kw) = xmlrpc_unmarshal(*params)
kw = params[-1] return func(*args, **kw)
params = params[:-1]
return func(*params, **kw)
else:
return func(*params)
finally: finally:
# Clean up any per-request data and connections # Clean up any per-request data and connections
# for k in context.__dict__.keys(): # for k in context.__dict__.keys():
@ -109,7 +104,6 @@ class LoggingSimpleXMLRPCRequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHa
# Log client request # Log client request
logger.info('Client request: \n%s\n' % data) logger.info('Client request: \n%s\n' % data)
# response = self.server._marshaled_dispatch(
response = self._marshaled_dispatch( response = self._marshaled_dispatch(
data, getattr(self, '_dispatch', None)) data, getattr(self, '_dispatch', None))
@ -147,6 +141,7 @@ XMLRPCServer = StoppableXMLRPCServer(("",PORT), LoggingSimpleXMLRPCRequestHandle
XMLRPCServer.register_introspection_functions() XMLRPCServer.register_introspection_functions()
# Get and register all the methods # Get and register all the methods
api.env.server_context = True
api.finalize() api.finalize()
for cmd in api.Method: for cmd in api.Method:
logger.info("registering %s" % cmd) logger.info("registering %s" % cmd)