Beispiel #1
0
    def policy(self, policy_id):
        if not authz.is_sysadmin(c.user):
            abort(403, _('Unauthorized'))
        c.policy = GDPRPolicy.get(id=policy_id)
        accepted_policy = GDPRAccept.filter(policy_id=c.policy.id)
        c.accepting_users = []
        for policy in accepted_policy:
            c.accepting_users.append(User.get(policy.user_id))

        c.not_accepting_users = [
            item for item in User.all() if item not in c.accepting_users
        ]

        return toolkit.render('gdpr/policy.html')
Beispiel #2
0
    def login_handler(self):
        params = request.POST
        if 'login' in params and 'password' in params:
            login = params['login'] 
            password = params['password']
           
            # code = subprocess.check_output("python3 " +os.path.dirname(os.path.abspath(__file__))  + "/from_pw_to_token.py '" + login + "' '" + password + "'", shell=True   )
            # print code

            found_ldap = self._ldap_authentication(login, password)
            if found_ldap:
                pylons.session['ckanext-ldap-user'] = str(login)
                pylons.session.save() 
                p.toolkit.redirect_to("/user/"+str(login))
            else:
                try:
                    user_dict = p.toolkit.get_action('user_show')(data_dict={'id':login})
                    usr = User.by_name(user_dict['name'])
                   
                except p.toolkit.ObjectNotFound:
                    usr = None
                    p.toolkit.redirect_to(control='user', action='login')

                if usr and usr.validate_password(password):
                    pylons.session['normal-user'] = str(login) 
                    pylons.session.save()
                    p.toolkit.redirect_to('/user/' + str(login) )
                else:
                    flash_error(error_message)
                    p.toolkit.redirect_to('/user/login')
Beispiel #3
0
    def ssologin_handler(self):
         
        if 'code' in request.GET:
            print 'ESISTE IL CODE'
            user_code = request.GET['code'] 

            user_token = subprocess.check_output("python3 " +  os.path.dirname(os.path.abspath(__file__))   + "/authenticate_code.py " + redirect_login + ' "' + user_code + '"'  ,shell=True )
            print user_token
          
            user_info = subprocess.check_output( "python3 " +  os.path.dirname(os.path.abspath(__file__))   + '/from_token_to_user.py "' + user_token + '"'  ,shell=True  )          
            print user_info        

            user_name = user_info.split("preferred_username':"******"'")[1]
            if self._ldap_auth_from_token(user_name):
                # ldap ha certificato l'utente associato al token... procediamo col login vero e proprio
                pylons.session['ckanext-ldap-user'] = str(user_name)
                pylons.session.save()
                p.toolkit.redirect_to("https://datagate.snap4city.org/user/"+str(user_name) )
            else:
                try:
                    user_dict = p.toolkit.get_action('user_show')(data_dict={'id':user_name})
                    usr = User.by_name(user_dict['name'])                  
                except p.toolkit.ObjectNotFound:
                    usr = None
                    p.toolkit.redirect_to(control='user', action='login')
                if usr:
                    pylons.session['normal-user'] = str(user_name) 
                    pylons.session.save()
                    p.toolkit.redirect_to("https://datagate.snap4city.org/user/"+str(user_name) )
            

        else:
            url = subprocess.check_output("python3 " +  os.path.dirname(os.path.abspath(__file__))   + "/authenticate_url.py " + redirect_login ,shell=True )
            p.toolkit.redirect_to( url)
def user_display_name():
    logged_user = c.userobj
    actor_id = pylons.session.get('ckanext-cas-actorid')
    if actor_id:
        found_user = User.by_name(actor_id)
        if found_user:
            return u'{0} ({1})'.format(logged_user.display_name, found_user.display_name)
    return logged_user.display_name
Beispiel #5
0
def get_regular_user_context():
    user = factories.User()
    auth_user_obj = CkanUser.get(user['id'])
    return {
        'user': user.get('name'),
        'auth_user_obj': auth_user_obj,
        'model': model,
        'session': model.Session,
        'ignore_auth': True,
    }
def convert_id_to_email(ids):
    ids = ids.split(',')
    emails = []

    for id in ids:
        user = User.get(id)

        if user:
            emails.append(user.email)

    return ','.join(emails)
def validate_password(self, password):
    from ckan.model.user import User

    if not password or not self.password:
        return False

    # Is it a Drupal password hash?
    if self.password[:3] in ('$S$', '$H$', '$P$'):
        # yes, upgrade it
        return _verify_password_and_upgrade_from_drupal7(self, password)

    # Fall back to existing logic
    return User.validate_password_original(self, password)
Beispiel #8
0
    def crawl(self):
        site_url = config.get('ckan.site_url')
        crawl_url_blacklist_regex = re.compile(r'/activity/')
        crawl_content_type_whitelist_regex = re.compile(r'text/html')
        url_regex = re.compile(
            r'href="((http[s]?://|/)(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)"'
        )
        site_map = {}
        to_crawl = [site_url]
        while to_crawl:
            next_crawl = to_crawl.pop(0)
            new_crawl = crawl(next_crawl, site_url, site_map,
                              crawl_url_blacklist_regex,
                              crawl_content_type_whitelist_regex, url_regex)
            to_crawl += new_crawl

        external_urls = get_external_children(site_url, site_map)
        url_errors = {}
        for url in sorted(external_urls):
            try:
                urlopen(url)
            except HTTPError as e:
                referrers = find_referrers(url, site_map)
                url_errors[url] = referrers
            except URLError as e:
                referrers = find_referrers(url, site_map)
                url_errors[url] = referrers

        for url, referrers in url_errors.iteritems():
            result = LinkValidationResult()
            result.type = u'error'
            result.url = url
            result.referrers = []

            for referrer_url in referrers:
                referrer = LinkValidationReferrer()
                referrer.result_id = result.id
                referrer.url = referrer_url
                result.referrers.append(referrer)

            model.Session.add(result)
        model.Session.commit()

        if url_errors:
            from ckan.model.user import User
            admin = User.get('admin')
            mailer.mail_user(
                admin, 'URL errors',
                '\n\n'.join('%s\n%s' % (u, '\n'.join('  - %s' % r for r in rs))
                            for u, rs in url_errors.iteritems()))
Beispiel #9
0
 def login_handler(self):
     """Action called when login in via the LDAP login form"""
     params = request.POST
     if 'login' in params and 'password' in params:
         login = params['login']
         password = params['password']
         try:
             ldap_user_dict = _find_ldap_user(login)
         except MultipleMatchError as e:
             # Multiple users match. Inform the user and try again.
             return self._login_failed(notice=str(e))
         if ldap_user_dict and _check_ldap_password(ldap_user_dict['cn'],
                                                    password):
             try:
                 user_name = _get_or_create_ldap_user(ldap_user_dict)
             except UserConflictError as e:
                 return self._login_failed(error=str(e))
             return self._login_success(user_name)
         elif ldap_user_dict:
             # There is an LDAP user, but the auth is wrong. There could be a CKAN user of the
             # same name if the LDAP user had been created later - in which case we have a
             # conflict we can't solve.
             if config['ckanext.ldap.ckan_fallback']:
                 exists = _ckan_user_exists(login)
                 if exists['exists'] and not exists['is_ldap']:
                     return self._login_failed(error=_(
                         'Username conflict. Please contact the site administrator.'
                     ))
             return self._login_failed(error=_('Bad username or password.'))
         elif config['ckanext.ldap.ckan_fallback']:
             # No LDAP user match, see if we have a CKAN user match
             try:
                 user_dict = p.toolkit.get_action('user_show')(data_dict={
                     'id': login
                 })
                 # We need the model to validate the password
                 user = User.by_name(user_dict['name'])
             except p.toolkit.ObjectNotFound:
                 user = None
             if user and user.validate_password(password):
                 return self._login_success(user.name)
             else:
                 return self._login_failed(
                     error=_('Bad username or password.'))
         else:
             return self._login_failed(error=_('Bad username or password.'))
     return self._login_failed(
         error=_('Please enter a username and password'))
Beispiel #10
0
    def policy_csv(self):
        if not authz.is_sysadmin(c.user):
            abort(403, _('Unauthorized'))

        with io.BytesIO() as csvfile:
            fieldnames = ['user_id', 'username', 'email']

            gdpr = GDPR.get()
            policies = GDPRPolicy.filter(gdpr_id=gdpr.id)
            for policy in policies:
                fieldname = 'policy_id_{}'.format(policy.id)
                if policy.required:
                    fieldname += '*'
                fieldnames.append(fieldname)

            writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
            writer.writeheader()

            for user in User.all():
                csv_dict = {
                    'user_id': user.id,
                    'username': user.name,
                    'email': user.email
                }

                policies = GDPRPolicy.filter(gdpr_id=gdpr.id)
                for policy in policies:
                    user_accept = GDPRAccept.get(policy_id=policy.id,
                                                 user_id=user.id)
                    accepted = False
                    if user_accept is not None:
                        accepted = True

                    fieldname = 'policy_id_{}'.format(policy.id)
                    if policy.required:
                        fieldname += '*'
                    csv_dict[fieldname] = accepted

                writer.writerow(csv_dict)

            response.headers['Content-type'] = 'text/csv'
            return csvfile.getvalue()
 def login_handler(self):
     """Action called when login in via the LDAP login form"""
     came_from = request.params.get('came_from', '')
     params = request.POST
     if 'login' in params and 'password' in params:
         login = params['login']
         password = params['password']
         try:
             ldap_user_dict = _find_ldap_user(login)
         except MultipleMatchError as e:
             # Multiple users match. Inform the user and try again.
             return self._login_failed(notice=str(e))
         if ldap_user_dict and _check_ldap_password(ldap_user_dict['cn'], password):
             try:
                 user_name = _get_or_create_ldap_user(ldap_user_dict)
             except UserConflictError as e:
                 return self._login_failed(error=str(e))
             return self._login_success(user_name, came_from=came_from)
         elif ldap_user_dict:
             # There is an LDAP user, but the auth is wrong. There could be a CKAN user of the
             # same name if the LDAP user had been created later - in which case we have a
             # conflict we can't solve.
             if config['ckanext.ldap.ckan_fallback']:
                 exists = _ckan_user_exists(login)
                 if exists['exists'] and not exists['is_ldap']:
                     return self._login_failed(error=_('Username conflict. Please contact the site administrator.'))
             return self._login_failed(error=_('Bad username or password.'))
         elif config['ckanext.ldap.ckan_fallback']:
             # No LDAP user match, see if we have a CKAN user match
             try:
                 user_dict = _get_user_dict(login)
                 # We need the model to validate the password
                 user = User.by_name(user_dict['name'])
             except p.toolkit.ObjectNotFound:
                 user = None
             if user and user.validate_password(password):
                 return self._login_success(user.name, came_from=came_from)
             else:
                 return self._login_failed(error=_('Bad username or password.'))
         else:
             return self._login_failed(error=_('Bad username or password.'))
     return self._login_failed(error=_('Please enter a username and password'))
Beispiel #12
0
    def _ldap_authentication(self, un, password ): 
        l = ldap.initialize(self.ldapServerAddress)
        try: 
            username = '******' + un + ',' + self.baseDn
            i = l.bind_s(username, password) 
            x = l.search_s(self.baseDn, ldap.SCOPE_SUBTREE, 'uid='+un)
            l.unbind()

            try:
                user_dict = p.toolkit.get_action('user_show')(data_dict={'id':un})
                usr = User.by_name(user_dict['name'])
                                
                if usr.state == 'deleted':
                   usr.activate()
                   ckan.model.Session.commit()                 
                  
            except p.toolkit.ObjectNotFound:
                usr = None

            if usr is None: 
                ldap_dataTuple  = x[0] # dovrebbe esserci un solo utente con quell'id
                print ldap_dataTuple
                email = "*****@*****.**" 
                if "email" in ldap_dataTuple[1].keys():
                    email =ldap_dataTuple[1]["email"]
                elif "mail" in ldap_dataTuple[1].keys():
                    email = ldap_dataTuple[1]["mail"]                
      		
                user_dict_from_ldap = {'name':str(un), 'email':email, 'password':str(uuid.uuid4())}
                print "USER CREATE....................................................."
                try:
                    print str(p.toolkit.get_action('user_create')(context={'ignore_auth':True}, data_dict=user_dict_from_ldap))
                except ValidationError:
                    print "VALIDATION ERROR"          

            #p.toolkit.redirect_to('/user/' +str(un))  
            return True 

        except ldap.LDAPError: 
            # l.unbind()
            return False
def request_create(context, data_dict):
    '''Create new request data.

    :param sender_name: The name of the sender who request data.
    :type sender_name: string

    :param organization: The sender's organization.
    :type organization: string

    :param email_address: The sender's email_address.
    :type email_address: string

    :param message_content: The content of the message.
    :type message_content: string

    :param package_id: The id of the package the data belongs to.
    :type package_id: string

    :returns: the newly created request data
    :rtype: dictionary

    '''

    check_access('requestdata_request_create', context, data_dict)

    data, errors = df.validate(data_dict, schema.request_create_schema(),
                               context)

    if errors:
        raise toolkit.ValidationError(errors)

    sender_name = data.get('sender_name')
    organization = data.get('organization')
    email_address = data.get('email_address')
    message_content = data.get('message_content')
    package_id = data.get('package_id')

    package = toolkit.get_action('package_show')(context, {'id': package_id})

    sender_user_id = User.get(context['user']).id

    maintainers = package['maintainer'].split(',')

    data = {
        'sender_name': sender_name,
        'sender_user_id': sender_user_id,
        'organization': organization,
        'email_address': email_address,
        'message_content': message_content,
        'package_id': package_id
    }

    requestdata = ckanextRequestdata(**data)
    requestdata.save()
    maintainers_list = []
    is_hdx = helpers.is_hdx_portal()

    for id in maintainers:
        try:
            if is_hdx:
                main_ids = toolkit.get_action('user_show')(context, {'id': id})
                user = User.get(main_ids['id'])
            else:
                user = User.get(id)
            data = ckanextMaintainers()
            data.maintainer_id = user.id
            data.request_data_id = requestdata.id
            data.email = user.email
            maintainers_list.append(data)
        except NotFound:
            pass

    out = ckanextMaintainers.insert_all(maintainers_list, requestdata.id)

    return out