Beispiel #1
0
 def _get_user_validation_schema(self):
     # Update the user schema to allow user creation
     user_schema = schema.default_user_schema()
     user_schema['id'] = [toolkit.get_validator('not_empty'), unicode]
     user_schema['name'] = [toolkit.get_validator('not_empty'), unicode]
     user_schema['email'] = [toolkit.get_validator('ignore_missing'), unicode]
     return user_schema
Beispiel #2
0
    def validate_user_create(data_dict, context):

        is_password_mismatch = False
        _schema = schema.default_user_schema()
        session = context['session']
        data = data_dict.copy()
        data = PublisherCreateWithUserView.resolve_form_field_name_conflict(
            data, {
                "user_name": "name",
                "user_image_url": "image_url",
                "user_image_upload": "image_upload"
            })

        if data['password1'] == data['password2']:
            data['password'] = data['password1']
        else:
            is_password_mismatch = True

        data, errors = dict_fns.validate(data, _schema, context)
        session.rollback()

        if errors:
            if is_password_mismatch:
                errors['password'] = [
                    u'Password and confirm password are not same'
                ]
            return errors

        return dict()
Beispiel #3
0
    def identify(self):
        """
        Map the SAML2 identity to the CKAN user.

        This does work around saml2 authorization.
        c.user contains the saml2 id of the logged in user we need to
        convert this to represent the ckan user.
        """
        # Can we find the user?
        c = p.toolkit.c
        environ = p.toolkit.request.environ
        user = environ.get('REMOTE_USER', '')
        if user:
            # we need to get the actual user info from the saml2auth client
            if not self.saml_identify:
                plugins = environ['repoze.who.plugins']
                saml_plugin = plugins.get('saml2auth')
                if not saml_plugin:
                    # saml2 repoze plugin not set up
                    return
                saml_client = saml_plugin.saml_client
                self.saml_identify = saml_client.users.get_identity
            try:
                saml_info = self.saml_identify(user)[0]
            except KeyError:
                # we don't know the user stale cookies
                saml_info = None

            # If we are here but no info then we need to clean up
            if not saml_info:
                delete_cookies()
                h.redirect_to(controller='user', action='logged_out')

            c.user = saml_info['name'][0]
            c.userobj = model.User.get(c.user)

            if c.userobj is None:
                # Create the user
                data_dict = {
                    'password': self.make_password(),
                }
                self.update_data_dict(data_dict, self.user_mapping, saml_info)
                # Update the user schema to allow user creation
                user_schema = schema.default_user_schema()
                user_schema['id'] = [p.toolkit.get_validator('not_empty')]
                user_schema['name'] = [p.toolkit.get_validator('not_empty')]

                context = {'schema': user_schema, 'ignore_auth': True}
                user = p.toolkit.get_action('user_create')(context, data_dict)
                c.userobj = model.User.get(c.user)

            # previous 'user' in repoze.who.identity check is broken.
            # use referer check as an temp alternative.
            if not environ.get('HTTP_REFERER'):
                if self.organization_mapping['name'] in saml_info:
                    self.create_organization(saml_info)
Beispiel #4
0
def default_user_schema():
    # changes from core:
    # - username can be uppercase
    # - email is not required
    schema = core_schema.default_user_schema()
    schema['name'] = [navl_validators.not_empty,
                      core_validators.user_name_validator,
                      unicode]
    schema['email'] = [navl_validators.default(u''),
                       unicode]
    return schema
Beispiel #5
0
    def identify(self):
        ''' This does work around saml2 authorization.
        c.user contains the saml2 id of the logged in user we need to
        convert this to represent the ckan user. '''

        # Can we find the user?
        c = p.toolkit.c
        environ = p.toolkit.request.environ
        user = environ.get('REMOTE_USER', '')
        if user:
            # we need to get the actual user info from the saml2auth client
            if not self.saml_identify:
                plugins = environ['repoze.who.plugins']
                saml_plugin = plugins.get('saml2auth')
                if not saml_plugin:
                    # saml2 repoze plugin not set up
                    return
                saml_client = saml_plugin.saml_client
                self.saml_identify = saml_client.users.get_identity
            try:
                saml_info = self.saml_identify(user)[0]
            except KeyError:
                # we don't know the user stale cookies
                saml_info = None

            # If we are here but no info then we need to clean up
            if not saml_info:
                delete_cookies()
                h.redirect_to(controller='user', action='logged_out')

            c.user = saml_info['name'][0]
            c.userobj = model.User.get(c.user)

            if c.userobj is None:
                # Create the user
                data_dict = {
                    'password': self.make_password(),
                }
                self.update_data_dict(data_dict, self.user_mapping, saml_info)
                # Update the user schema to allow user creation
                user_schema = schema.default_user_schema()
                user_schema['id'] = [p.toolkit.get_validator('not_empty')]
                user_schema['name'] = [p.toolkit.get_validator('not_empty')]

                context = {'schema': user_schema, 'ignore_auth': True}
                user = p.toolkit.get_action('user_create')(context, data_dict)
                c.userobj = model.User.get(c.user)

            # previous 'user' in repoze.who.identity check is broken.
            # use referer check as an temp alternative.
            if not environ.get('HTTP_REFERER'):
                if self.organization_mapping['name'] in saml_info:
                    self.create_organization(saml_info)
Beispiel #6
0
def custom_create_user_schema(form_schema=False):

    schema = default_user_schema()

    schema['password'] = [custom_user_password_validator,
                          toolkit.get_validator('user_password_not_empty'),
                          toolkit.get_validator('ignore_missing'),
                          unicode]

    if form_schema:
        schema['password1'] = [toolkit.get_validator('user_both_passwords_entered'),
                               custom_user_password_validator,
                               toolkit.get_validator('user_passwords_match'),
                               unicode]
        schema['password2'] = [unicode]

    return schema
Beispiel #7
0
def _create_user(data_dict, role):
    keys = {}
    keys['id'] = role + '.UPVSIdentityID'
    keys['name'] = role + '.Username'
    keys['email'] = role + '.Email'
    keys['fullname'] = role + '.FormattedName'
    userobj = model.User.get(data_dict[keys['id']])
    user_create_dict = {}
    for key, value in keys.iteritems():
        attr_value = data_dict.get(value, '')
        if attr_value:
            user_create_dict[key] = attr_value
        elif value.endswith('Username'):
            user_create_dict[key] = data_dict[keys['id']]
    user_schema = default_schema.default_user_schema()
    user_schema['id'] = [toolkit.get_validator('not_empty'), unicode]
    user_schema['name'] = [toolkit.get_validator('not_empty'), unicode]
    user_schema['email'] = [toolkit.get_validator('ignore_missing'), unicode]
    user_schema['password'] = [
        toolkit.get_validator('ignore_missing'), unicode
    ]
    context = {
        'schema': user_schema,
        'ignore_auth': True,
        'model': model,
        'session': model.Session
    }

    if userobj:
        if (user_create_dict.get('name', '') != '' and userobj.name != user_create_dict.get('name', '')) or \
           (user_create_dict.get('email', '') != '' and userobj.email != user_create_dict.get('email', '')) or \
           (user_create_dict.get('fullname','') != '' and userobj.fullname != user_create_dict.get('fullname','')):
            if data_dict.get(keys['name'], ''):
                del user_create_dict['name']
            user_schema['name'] = [
                toolkit.get_validator('ignore_missing'), unicode
            ]
            toolkit.get_action('user_update')(context, user_create_dict)
    else:
        user_create_dict['password'] = make_password()
        toolkit.get_action('user_create')(context, user_create_dict)
    userobj = model.User.get(user_create_dict['id'])
    return userobj
Beispiel #8
0
 def _create_user(self, data_dict, role):
     keys = {}
     keys['id'] = role + '.UPVSIdentityID'
     keys['name'] = role + '.Username'
     keys['email'] =role + '.Email'
     keys['fullname'] = role + '.FormattedName'
     userobj = model.User.get(data_dict[keys['id']][0])
     user_create_dict = {}
     for key, value in keys.iteritems():
         attr_value = data_dict.get(value, ['',])[0]
         if attr_value:
             user_create_dict[key] = attr_value
         elif value.endswith('Username'):
             user_create_dict[key] = data_dict[keys['id']][0]
     user_schema = schema.default_user_schema()
     user_schema['id'] = [toolkit.get_validator('not_empty'), unicode]
     user_schema['name'] = [toolkit.get_validator('not_empty'), unicode]
     user_schema['email'] = [toolkit.get_validator('ignore_missing'), unicode]
     user_schema['password'] = [toolkit.get_validator('ignore_missing'), unicode]
     context = {'schema' : user_schema,
                'ignore_auth': True,
                'model' : model,
                'session' : model.Session}
     log.info('actual user: %s' , userobj)
     log.info('new user: %s', user_create_dict)
     if userobj:
         same_name = userobj.name == user_create_dict.get('name', None)
         same_email = userobj.email == user_create_dict.get('email', None)
         same_fullname = userobj.fullname == user_create_dict.get('fullname', None)
         log.info('compare result: %s, %s, %s', same_name, same_email, same_fullname)
         if unicode(userobj.name) != unicode(user_create_dict.get('name', None)) or \
            userobj.email != user_create_dict.get('email', None) or \
            unicode(userobj.fullname) != unicode(user_create_dict.get('fullname',None)):
             if data_dict.get(keys['name'], ''):
                 del user_create_dict['name']
             user_schema['name'] = [toolkit.get_validator('ignore_missing'), unicode]
             toolkit.get_action('user_update')(context, user_create_dict)
     else:
         user_create_dict['password'] = make_password()
         toolkit.get_action('user_create')(context, user_create_dict)
     userobj = model.User.get(user_create_dict['id'])
     return userobj
Beispiel #9
0
def user_create(context, data_dict):
    '''Creates a new user'''

    model = context['model']
    schema = context.get('schema') or default_user_schema()
    session = context['session']

    check_access('user_create', context, data_dict)

    data, errors = validate(data_dict, schema, context)

    if errors:
        session.rollback()
        raise ValidationError(errors, group_error_summary(errors))

    user = user_dict_save(data, context)

    # Flush the session to cause user.id to be initialised, because
    # activity_create() (below) needs it.
    session.flush()

    activity_create_context = {
        'model': model,
        'user': context['user'],
        'defer_commit': True,
        'session': session
    }
    activity_dict = {
            'user_id': user.id,
            'object_id': user.id,
            'activity_type': 'new user',
            }
    activity_create(activity_create_context, activity_dict, ignore_auth=True)

    if not context.get('defer_commit'):
        model.repo.commit()

    context['user'] = user
    context['id'] = user.id
    log.debug('Created user %s' % str(user.name))
    return user_dictize(user, context)
Beispiel #10
0
def emailasusername_new_user_schema(unicode_safe, user_both_passwords_entered,
                                    user_password_validator,
                                    user_passwords_match, email_exists,
                                    not_empty, email_validator):
    emailasusername_schema = schema.default_user_schema()
    emailasusername_schema['fullname'] = [not_empty, unicode_safe]
    emailasusername_schema['password1'] = [
        text_type, user_both_passwords_entered, user_password_validator,
        user_passwords_match
    ]
    emailasusername_schema['password2'] = [text_type]
    emailasusername_schema['email'] = [unicode_safe, email_validator]
    emailasusername_schema['email1'] = [
        not_empty, unicode_safe, email_validator, email_exists
    ]
    if config_require_user_email_input_confirmation():
        emailasusername_schema['email1'] += [
            user_emails_match, user_both_emails_entered
        ]
        emailasusername_schema['email2'] = [not_empty]
    return emailasusername_schema
Beispiel #11
0
def user_create(context, data_dict):
    '''Creates a new user'''

    model = context['model']
    user = context['user']
    schema = context.get('schema') or default_user_schema()

    check_access('user_create', context, data_dict)

    data, errors = validate(data_dict, schema, context)

    if errors:
        model.Session.rollback()
        raise ValidationError(errors, group_error_summary(errors))

    user = user_dict_save(data, context)

    model.repo.commit()        
    context['user'] = user
    context['id'] = user.id
    log.debug('Created user %s' % str(user.name))
    return user_dictize(user, context)
Beispiel #12
0
def default_update_user_schema(ignore_missing, name_validator,
                               user_name_validator, unicode_safe,
                               user_password_validator, boolean_validator):
    schema = schema_.default_user_schema()

    schema['name'] = [
        ignore_missing, name_validator, user_name_validator, unicode_safe
    ]
    schema['password'] = [
        user_password_validator, ignore_missing, unicode_safe
    ]

    schema['user-terms-agree'] = [
        boolean_validator,
    ]
    schema['uploader-terms-agree'] = [
        boolean_validator,
    ]
    schema["allow_marketting_emails"] = [
        boolean_validator,
    ]

    return schema
Beispiel #13
0
def user_create(context, data_dict):
    '''Creates a new user'''

    model = context['model']
    user = context['user']
    schema = context.get('schema') or default_user_schema()

    check_access('user_create', context, data_dict)

    data, errors = validate(data_dict, schema, context)

    if errors:
        model.Session.rollback()
        raise ValidationError(errors, group_error_summary(errors))

    user = user_dict_save(data, context)

    if not context.get('defer_commit'):
        model.repo.commit()
    context['user'] = user
    context['id'] = user.id
    log.debug('Created user %s' % str(user.name))
    return user_dictize(user, context)
from ckan.lib.base import c, request, abort, h
from ckan.lib.uploader import Upload
from ckan.plugins import toolkit

from .user_creation import helpers as user_creation_helpers

import plugin
from authenticator import unlock_account, LOGIN_THROTTLE_EXPIRY

LOG = getLogger(__name__)

LOGGED_IN = UserController.logged_in
PACKAGE_EDIT = PackageController._save_edit
RESOURCE_EDIT = PackageController.resource_edit

DEFAULT_USER_SCHEMA = schemas.default_user_schema()
USER_NEW_FORM_SCHEMA = schemas.user_new_form_schema()
USER_EDIT_FORM_SCHEMA = schemas.user_edit_form_schema()
DEFAULT_UPDATE_USER_SCHEMA = schemas.default_update_user_schema()
RESOURCE_SCHEMA = schemas.default_resource_schema()

UPLOAD = Upload.upload
if storage_enabled:
    STORAGE_DOWNLOAD = StorageController.file
RESOURCE_DOWNLOAD = PackageController.resource_download

EMAIL_REGEX = re.compile(r"[^@]+@[^@]+\.[^@]+")


def configure(config):
    global password_min_length
Beispiel #15
0
    def identify(self):
        ''' This does work around saml2 authorization.
        c.user contains the saml2 id of the logged in user we need to
        convert this to represent the ckan user. '''

        # Can we find the user?
        c = p.toolkit.c
        environ = p.toolkit.request.environ
        log.info('---environ---')
        log.info(environ)
        user = environ.get('REMOTE_USER', '')
        log.info('user')
        log.info(user)
        #log.info("repoze.who.identity: '%s'" % environ.get("repoze.who.identity", ""))
        i = environ.get("repoze.who.identity", "")
        if i:
        #    log.info(dir(i))
            log.info(i.viewkeys())
        #    log.info(i['repoze.who.userid'])
            log.info(i['user'])
            log.info(i.get('userdata', 'no user data'))
        if not user:
            user = environ.get("repoze.who.identity", "")
            log.info("repoze.who.identity: '%s'" % user)
        if user:
            # we need to get the actual user info from the saml2auth client
            if not self.saml_identify:
                plugins = environ['repoze.who.plugins']
                saml_plugin = plugins.get('saml2auth')
                if not saml_plugin:
                    # saml2 repoze plugin not set up
                    return
                saml_client = saml_plugin.saml_client
                self.saml_identify = saml_client.users.get_identity

            identity = environ.get("repoze.who.identity", {})
            user_data = identity.get("user", {})
            # If we are here but no info then we need to clean up
            if not user_data:
                delete_cookies()
                h.redirect_to(controller='user', action='logged_out')
            
            log.info('---getting name---')
            c.user = user_data['actor_username'][0]
            c.userobj = model.User.get(c.user)

            if c.userobj is None:
                # Create the user
                data_dict = {
                    'password': self.make_password(),
                    'name' : user_data['actor_username'][0],
                    'email' : user_data['actor_email'][0],
                    'fullname' : user_data['actor_formatted_name'][0],
                    'id' : user_data['actor_upvs_identity_id'][0]
                }
                #self.update_data_dict(data_dict, self.user_mapping, saml_info)
                # Update the user schema to allow user creation
                user_schema = schema.default_user_schema()
                log.info('---schema---')
                log.info(user_schema)
                user_schema['id'] = [p.toolkit.get_validator('not_empty')]
                user_schema['name'] = [p.toolkit.get_validator('not_empty')]
                user_schema['email'] = [p.toolkit.get_validator('ignore_missing')]

                context = {'schema' : user_schema, 'ignore_auth': True}
                user = p.toolkit.get_action('user_create')(context, data_dict)
                c.userobj = model.User.get(c.user)
def user_schema():
    user_name_validator = get_validator('user_name_validator')
    schema = default_user_schema()
    schema['name'] = [not_empty, url_name_validator, user_name_validator, unicode]
    return schema
def user_create(original_action, context, data_dict):
    modified_schema = context.get('schema') or schema.default_user_schema()
    context['schema'] = user_creation_helpers.add_custom_validator_to_user_schema(modified_schema)
    return original_action(context, data_dict)
Beispiel #18
0
    def _create_or_update_user(self, user_name, saml_info, name_id):
        """Create or update the subject's user account and return the user
        object"""
        data_dict = {}
        user_id = ''
        user_schema = schema.default_update_user_schema()

        is_new_user = False
        userobj = model.User.get(user_name)
        if userobj is None:
            is_new_user = True
            user_schema = schema.default_user_schema()
        else:
            if userobj.is_deleted():
                # If account exists and is deleted, reactivate it. Assumes
                # only the IAM driving the IdP will deprovision user
                # accounts and wouldn't allow a user to authenticate for
                # this app if they shouldn't have access.
                log.debug("Reactivating user")
                userobj.activate()
                userobj.commit()

            data_dict = p.toolkit.get_action('user_show')(data_dict={
                'id': user_name,
            })
            user_id = data_dict['id']

        # Merge SAML assertions into data_dict according to
        # user_mapping
        update_user = self.update_data_dict(data_dict, self.user_mapping,
                                            saml_info)

        # Remove validation of the values from id and name fields
        user_schema['id'] = [p.toolkit.get_validator('not_empty')]
        user_schema['name'] = [p.toolkit.get_validator('not_empty')]
        context = {'schema': user_schema, 'ignore_auth': True}
        if is_new_user:
            email = _take_from_saml_or_user('email', saml_info, data_dict)
            new_user_username = _get_random_username_from_email(email)

            name_id_from_saml2_NameID = config.get(
                'saml2.name_id_from_saml2_NameID', False)
            if not name_id_from_saml2_NameID:
                name_id = _take_from_saml_or_user('id', saml_info, data_dict)
            data_dict['name'] = new_user_username
            data_dict['id'] = str(uuid.uuid4())
            log.debug("Creating user: %s", data_dict)
            data_dict['password'] = self.make_password()
            new_user = p.toolkit.get_action('user_create')(context, data_dict)
            assign_default_role(context, new_user_username)
            model.Session.add(SAML2User(id=new_user['id'], name_id=name_id))
            model.Session.commit()
            return model.User.get(new_user_username)
        elif update_user:
            if saml2_is_update_user_allowed():
                log.debug("Updating user: %s", data_dict)
                user_data_dict = copy.copy(data_dict)
                user_data_dict['id'] = user_id
                p.toolkit.get_action('user_update')(context, user_data_dict)

        return model.User.get(user_name)
Beispiel #19
0
def reqaccess_new_form_schema():
    schema = default_user_schema()

    return schema