def get_user_realname(user): from ckanext.dgu.drupalclient import DrupalClient from HTMLParser import HTMLParser if user.name.startswith('user_d'): user_id = user.name[len('user_d'):] html_parser = HTMLParser() try: dc = DrupalClient() properties = dc.get_user_properties(user_id) except Exception, ex: return user.fullname try: first_name = properties['field_first_name']['und'][0]['safe_value'] first_name = html_parser.unescape(first_name) except: first_name = '' try: surname = properties['field_surname']['und'][0]['safe_value'] surname = html_parser.unescape(surname) except: surname = ''
def test_get_user_properties(self): drupal_config = get_mock_drupal_config() test_user_id = '62' expected_user = drupal_config['test_users'][test_user_id] client = DrupalClient() user = client.get_user_properties(test_user_id) assert user assert isinstance(user, dict) assert_equal(user['name'], expected_user['name']) expected_publishers = expected_user['publishers'] assert_equal(user['publishers'], expected_publishers)
def test_get_user_properties(self): drupal_config = get_mock_drupal_config() test_user_id = '62' expected_user = drupal_config['test_users'][test_user_id] client = DrupalClient() user = client.get_user_properties(test_user_id) assert user assert isinstance(user, dict) assert_equal(user['name'], expected_user['name']) expected_publishers = expected_user['publishers'] assert_equal(user['publishers'], expected_publishers)
def sync(self, write, user): from ckan import model from ckanext.dgu.drupalclient import DrupalClient, DrupalRequestError from ckanext.dgu.authentication.drupal_auth import DrupalUserMapping log = self.log update_keys = set(('email', 'fullname')) drupal = DrupalClient() users = model.Session.query(model.User)\ .filter_by(state='active')\ .filter(model.User.name.like('user_d%')) if user: users = users.filter(model.User.fullname == user) users = users.all() log.info('Drupal users in CKAN: %s', len(users)) for user in users: drupal_user_id = DrupalUserMapping.ckan_user_name_to_drupal_id( user.name) try: drupal_user = drupal.get_user_properties(drupal_user_id) except DrupalRequestError, e: if 'There is no user with ID' in str(e): log.info( stats.add('Removed deleted user', '%s %s' % (drupal_user_id, user.fullname))) if write: user.delete() continue elif 'Access denied for user' in str(e): log.info( stats.add('Removed blocked user', '%s %s' % (drupal_user_id, user.fullname))) if write: user.delete() continue raise DrupalRequestError user_dict = DrupalUserMapping.drupal_user_to_ckan_user(drupal_user) user_changed = False for key in update_keys: if getattr(user, key) != user_dict[key]: log.info( stats.add( 'Updating field %s' % key, '%s %s %s->%s' % (drupal_user_id, user.fullname, getattr( user, key), user_dict[key]))) if write: setattr(user, key, user_dict[key]) user_changed = True if not user_changed: log.info( stats.add('Unchanged user', '%s %s' % (drupal_user_id, user.fullname)))
def sync(self, write, user): from ckan import model from ckanext.dgu.drupalclient import DrupalClient, DrupalRequestError from ckanext.dgu.authentication.drupal_auth import DrupalUserMapping log = self.log update_keys = set(('email', 'fullname')) drupal = DrupalClient() users = model.Session.query(model.User)\ .filter_by(state='active')\ .filter(model.User.name.like('user_d%')) if user: users = users.filter(model.User.fullname == user) users = users.all() log.info('Drupal users in CKAN: %s', len(users)) for user in users: drupal_user_id = DrupalUserMapping.ckan_user_name_to_drupal_id(user.name) try: drupal_user = drupal.get_user_properties(drupal_user_id) except DrupalRequestError, e: if 'There is no user with ID' in str(e): log.info(stats.add('Removed deleted user', '%s %s' % (drupal_user_id, user.fullname))) if write: user.delete() continue elif 'Access denied for user' in str(e): log.info(stats.add('Removed blocked user', '%s %s' % (drupal_user_id, user.fullname))) if write: user.delete() continue raise DrupalRequestError user_dict = DrupalUserMapping.drupal_user_to_ckan_user(drupal_user) user_changed = False for key in update_keys: if getattr(user, key) != user_dict[key]: log.info(stats.add( 'Updating field %s' % key, '%s %s %s->%s' % (drupal_user_id, user.fullname, getattr(user, key), user_dict[key]))) if write: setattr(user, key, user_dict[key]) user_changed = True if not user_changed: log.info(stats.add('Unchanged user', '%s %s' % (drupal_user_id, user.fullname)))
class AuthAPIMiddleware(object): def __init__(self, app, app_conf): self.app = app self.drupal_client = None def __call__(self, environ, start_response): if self.drupal_client is None: self.drupal_client = DrupalClient() # establish from the cookie whether ckan and drupal are signed in ckan_signed_in = [False] drupal_signed_in = [False] for k, v in environ.items(): key = k.lower() if key == 'http_cookie': ckan_signed_in[0] = is_ckan_signed_in(v) drupal_signed_in[0] = drupal_extract_cookie(v) ckan_signed_in = ckan_signed_in[0] drupal_signed_in = drupal_signed_in[0] environ['drupal.uid'] = None environ['drupal.publishers'] = None new_start_response = start_response if drupal_signed_in and not ckan_signed_in: # get info about the user from drupal and store in environ for # use by main CKAN app user_id = self.drupal_client.get_user_id_from_session_id(drupal_signed_in) res = self.drupal_client.get_user_properties(user_id) environ['drupal.uid'] = res['uid'] environ['drupal.publishers'] = res['publishers'] environ['drupal.name'] = res['name'] from ckan import model from ckan.model.meta import Session def munge(username): username.lower().replace(' ', '_') return username # Add the new Drupal user if they don't already exist. query = Session.query(model.User).filter_by(name=unicode(environ['drupal.uid'])) if not query.count(): user = model.User( name=munge(unicode(environ['drupal.uid'])), fullname=unicode(environ['drupal.name']), about=u'Drupal auto-generated user', ) Session.add(user) Session.commit() else: user = query.one() # We want to store values in the user's cookie, so # prepare the response header with this value, # using auth_tkt to sign it. new_header = environ['repoze.who.plugins']['auth_tkt'].remember( environ, { 'repoze.who.userid': environ['drupal.uid'], 'tokens': '', 'userdata': '', } ) # e.g. new_header = [('Set-Cookie', 'bob=ab48fe; Path=/;')] cookie_template = new_header[0][1].split('; ') cookie_string = '' for name, value in [ ('ckan_apikey', user.apikey), ('ckan_display_name', user.fullname), ('ckan_user', user.name), ]: cookie_string += '; %s="%s"'%(name, value) new_cookie = cookie_template[:] new_cookie[0] = '%s="%s"'%(name, value) new_header.append(('Set-Cookie', str('; '.join(new_cookie)))) # Also need these cookies to work too: # ckan_apikey # Value "3a51edc6-6461-46b8-bfe2-57445cbdeb2b" # Host catalogue.dev.dataco.coi.gov.uk # Path / # Secure No # Expires At End Of Session # # # Name ckan_display_name # Value "James Gardner" # Host catalogue.dev.dataco.coi.gov.uk # Path / # Secure No # Expires At End Of Session # # # Name ckan_user # Value "4466" # Host catalogue.dev.dataco.coi.gov.uk # Path / # Secure No # Expires At End Of Session # @@@ Need to add the headers to the request too so that the rest of the stack can sign the user in. #Cookie: __utma=217959684.178461911.1286034407.1286034407.1286178542.2; __utmz=217959684.1286178542.2.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=coi%20london; DRXtrArgs=James+Gardner; DRXtrArgs2=3e174e7f1e1d3fab5ca138c0a023e13a; SESS9854522e7c5dba5831db083c5372623c=4160a72a4d6831abec1ac57d7b5a59eb; auth_tkt="a578c4a0d21bdbde7f80cd271d60b66f4ceabc3f4466!"; ckan_apikey="3a51edc6-6461-46b8-bfe2-57445cbdeb2b"; ckan_display_name="James Gardner"; ckan_user="******" # There is a bug(/feature?) in line 628 of Cookie.py that means # it can't load from unicode strings. This causes Beaker to fail # unless the value here is a string if not environ.get('HTTP_COOKIE'): environ['HTTP_COOKIE'] += str(cookie_string) else: environ['HTTP_COOKIE'] = str(cookie_string[2:]) def cookie_setting_start_response(status, headers, exc_info=None): headers += new_header return start_response(status, headers, exc_info) new_start_response = cookie_setting_start_response return self.app(environ, new_start_response)
class AuthAPIMiddleware(object): def __init__(self, app, app_conf): self.app = app self.drupal_client = None def __call__(self, environ, start_response): if self.drupal_client is None: self.drupal_client = DrupalClient() # establish from the cookie whether ckan and drupal are signed in ckan_signed_in = [False] drupal_signed_in = [False] for k, v in environ.items(): key = k.lower() if key == 'http_cookie': ckan_signed_in[0] = is_ckan_signed_in(v) drupal_signed_in[0] = drupal_extract_cookie(v) ckan_signed_in = ckan_signed_in[0] drupal_signed_in = drupal_signed_in[0] environ['drupal.uid'] = None environ['drupal.publishers'] = None new_start_response = start_response if drupal_signed_in and not ckan_signed_in: # get info about the user from drupal and store in environ for # use by main CKAN app user_id = self.drupal_client.get_user_id_from_session_id( drupal_signed_in) res = self.drupal_client.get_user_properties(user_id) environ['drupal.uid'] = res['uid'] environ['drupal.publishers'] = res['publishers'] environ['drupal.name'] = res['name'] from ckan import model from ckan.model.meta import Session def munge(username): username.lower().replace(' ', '_') return username # Add the new Drupal user if they don't already exist. query = Session.query( model.User).filter_by(name=unicode(environ['drupal.uid'])) if not query.count(): user = model.User( name=munge(unicode(environ['drupal.uid'])), fullname=unicode(environ['drupal.name']), about=u'Drupal auto-generated user', ) Session.add(user) Session.commit() else: user = query.one() # We want to store values in the user's cookie, so # prepare the response header with this value, # using auth_tkt to sign it. new_header = environ['repoze.who.plugins']['auth_tkt'].remember( environ, { 'repoze.who.userid': environ['drupal.uid'], 'tokens': '', 'userdata': '', }) # e.g. new_header = [('Set-Cookie', 'bob=ab48fe; Path=/;')] cookie_template = new_header[0][1].split('; ') cookie_string = '' for name, value in [ ('ckan_apikey', user.apikey), ('ckan_display_name', user.fullname), ('ckan_user', user.name), ]: cookie_string += '; %s="%s"' % (name, value) new_cookie = cookie_template[:] new_cookie[0] = '%s="%s"' % (name, value) new_header.append(('Set-Cookie', str('; '.join(new_cookie)))) # Also need these cookies to work too: # ckan_apikey # Value "3a51edc6-6461-46b8-bfe2-57445cbdeb2b" # Host catalogue.dev.dataco.coi.gov.uk # Path / # Secure No # Expires At End Of Session # # # Name ckan_display_name # Value "James Gardner" # Host catalogue.dev.dataco.coi.gov.uk # Path / # Secure No # Expires At End Of Session # # # Name ckan_user # Value "4466" # Host catalogue.dev.dataco.coi.gov.uk # Path / # Secure No # Expires At End Of Session # @@@ Need to add the headers to the request too so that the rest of the stack can sign the user in. #Cookie: __utma=217959684.178461911.1286034407.1286034407.1286178542.2; __utmz=217959684.1286178542.2.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=coi%20london; DRXtrArgs=James+Gardner; DRXtrArgs2=3e174e7f1e1d3fab5ca138c0a023e13a; SESS9854522e7c5dba5831db083c5372623c=4160a72a4d6831abec1ac57d7b5a59eb; auth_tkt="a578c4a0d21bdbde7f80cd271d60b66f4ceabc3f4466!"; ckan_apikey="3a51edc6-6461-46b8-bfe2-57445cbdeb2b"; ckan_display_name="James Gardner"; ckan_user="******" # There is a bug(/feature?) in line 628 of Cookie.py that means # it can't load from unicode strings. This causes Beaker to fail # unless the value here is a string if not environ.get('HTTP_COOKIE'): environ['HTTP_COOKIE'] += str(cookie_string) else: environ['HTTP_COOKIE'] = str(cookie_string[2:]) def cookie_setting_start_response(status, headers, exc_info=None): headers += new_header return start_response(status, headers, exc_info) new_start_response = cookie_setting_start_response return self.app(environ, new_start_response)