def identify(self):
        '''Identify which user (if any) is logged-in via WAAD.

        CKAN calls this on each page load.

        If a logged-in user is found, set toolkit.c.user to be their user name.

        '''
        user = pylons.session.get('ckanext-oauth2waad-user')
        if user:
            toolkit.c.user = user
            endpoint = _waad_auth_token_endpoint()
            try:
                _refresh_access_token_if_expiring(pylons.session,
                                                  _waad_client_id(),
                                                  _waad_resource(), endpoint)
            except CannotRefreshAccessTokenError:
                domain_name = _get_domain_name_from_url(endpoint)
                logout_url = toolkit.url_for(controller='user',
                                             action='logout')
                message = toolkit._(
                    "Refreshing your Windows Azure Active Directory OAuth 2.0 "
                    "access token with {domain} failed. Some functionality "
                    "may not be available. You can try "
                    '<a href="{logout}">logging out</a> and logging in again '
                    "to fix the issue.").format(domain=domain_name,
                                                logout=logout_url)
                helpers.flash(message,
                              category='alert-error',
                              allow_html=True,
                              ignore_duplicate=True)
Exemple #2
0
    def get(self, id):
        context = {
            u'model': model,
            u'session': model.Session,
            u'user': id,
            u'keep_email': True
        }

        g.reset_key = request.params.get(u'key')
        try:
            check_access(u'user_update', context, {
                'id': id,
                'reset_key': g.reset_key,
            })
        except NotAuthorized:
            msg = _(
                u'The link you accessed is either invalid or has expired. Please request another reset link. '
                u'If the problem persists please '
                u'<a href="/faq#auto-faq-Contact-How_do_I_contact_the_HDX_team_-a">contact us</a>.'
            )
            h.flash(msg, category='alert-error', allow_html=True)
            return _forgot_password()

        try:
            user_dict = get_action(u'user_show')(context, {u'id': id})
        except NotFound:
            abort(404, _(u'User not found'))

        return render(u'user/perform_reset.html', {u'user_dict': user_dict})
Exemple #3
0
    def identify(self):
        '''Identify which user (if any) is logged-in via WAAD.

        CKAN calls this on each page load.

        If a logged-in user is found, set toolkit.c.user to be their user name.

        '''
        user = pylons.session.get('ckanext-oauth2waad-user')
        if user:
            toolkit.c.user = user
            endpoint = _waad_auth_token_endpoint()
            try:
                _refresh_access_token_if_expiring(pylons.session,
                                                  _waad_client_id(),
                                                  _waad_resource(),
                                                  endpoint)
            except CannotRefreshAccessTokenError:
                domain_name = _get_domain_name_from_url(endpoint)
                logout_url = toolkit.url_for(controller='user',
                                             action='logout')
                message = toolkit._(
                    "Refreshing your Windows Azure Active Directory OAuth 2.0 "
                    "access token with {domain} failed. Some functionality "
                    "may not be available. You can try "
                    '<a href="{logout}">logging out</a> and logging in again '
                    "to fix the issue.").format(domain=domain_name,
                                                logout=logout_url)
                helpers.flash(message, category='alert-error', allow_html=True,
                              ignore_duplicate=True)
Exemple #4
0
    def update_dqs(self, dqs_uuid):
        """
        """
        package, context = self._get_pkg_by_dqs_uuid(dqs_uuid)
        if request.method == 'POST':
            bit_dqs = 0
            for name, value in request.POST.items():
                if not name.startswith('q-'):
                    continue
                idx = int(name[2:])
                bit_dqs |= 1 << idx
            user = logic.get_action('get_site_user')({
                'ignore_auth': True
            }, None)
            context = {'model': model, 'user': user['name']}
            package = logic.get_action('package_patch')(context, {
                'id': package['id'],
                'bit_dqs': bit_dqs
            })
            allow_send_emails = asbool(
                config.get('ckan.ksa_dqs_allow_emails_send', 'False'))
            notif_emails = config.get('ckan.ksa_dqs_admin_emails', '').split()
            if len(notif_emails) > 0 and allow_send_emails:
                site_url = config.get('ckan.site_url', '')
                url = site_url + '/dataset/' + package['name']
                notif_names = 'admin'
                subject = 'DQS Updated for {0}'.format(package.get('title'))
                msg = '''The DQS for {title} dataset has been updated: {url}'''\
                    .format(title=package.get('title'), url=url)

                try:
                    for email in notif_emails:
                        mailer.mail_recipient(notif_names, email, subject, msg)
                except mailer.MailerException as e:
                    h.flash("Email error: {0}".format(e.message),
                            allow_html=False)

            data = {
                'id':
                dqs_uuid,
                'name':
                'Data Quality Statement',
                'format':
                'PDF',
                'package_id':
                package['id'],
                'url':
                h.url_for('ksa_export_dqs', dqs_uuid=dqs_uuid, qualified=True)
            }
            self._resource_create(context, data)
            return h.redirect_to('update_dataset_dqs', dqs_uuid=dqs_uuid)

        questionnaire_data = questionnaire.data
        if h.lang() == 'ar':
            questionnaire_data = questionnaire_ar.data

        extra_vars = {'pkg_dict': package, 'questionnaire': questionnaire_data}
        return base.render('package/update_dqs.html', extra_vars=extra_vars)
Exemple #5
0
def notice_show(context, data_dict):
    """ return the stored notice
    """
    try:
        model = context['model']
        notice = model.get_system_info('cdrc.site_notice.text')
        notice_type = model.get_system_info('cdrc.site_notice.type')
        if len(notice) > 0 and len(notice_type) > 0:
            h.flash(notice, notice_type)
    except:
        pass
    return ''
Exemple #6
0
 def issues_for_organization(self, org_id):
     """
     Display a page containing a list of all issues for a given organization
     """
     self._before_org(org_id)
     try:
         template_params = issues_for_org(org_id, request.GET)
     except toolkit.ValidationError, e:
         msg = toolkit._(u'Validation error: {0}').format(e.error_summary)
         log.warning(msg + u' - Issues for org: %s', org_id)
         h.flash(msg, category='alert-error')
         return p.toolkit.redirect_to('issues_for_organization',
                                      org_id=org_id)
 def issues_for_organization(self, org_id):
     """
     Display a page containing a list of all issues for a given organization
     """
     self._before_org(org_id)
     try:
         template_params = issues_for_org(org_id, request.GET)
     except toolkit.ValidationError, e:
         msg = toolkit._("Validation error: {0}".format(e.error_summary))
         log.warning(msg + ' - Issues for org: %s', org_id)
         h.flash(msg, category='alert-error')
         return p.toolkit.redirect_to('issues_for_organization',
                                      org_id=org_id)
Exemple #8
0
def issues_for_organization(org_id):
    """
    Display a page containing a list of all issues for a given organization
    """
    _before_org(org_id)
    try:
        template_params = issues_for_org(org_id, request.args)
    except toolkit.ValidationError as e:
        msg = toolkit._("Validation error: {0}".format(e.error_summary))
        log.warning(msg + ' - Issues for org: %s', org_id)
        h.flash(msg, category='alert-error')
        return p.toolkit.redirect_to('issues.issues_for_organization',
                                     org_id=org_id)
    print(template_params)
    return render("issues/organization_issues.html",
                  extra_vars=template_params)

    # TO DELETE
    g.org = model.Group.get(org_id)

    q = """
        SELECT table_id
        FROM member
        WHERE group_id='{gid}'
            AND table_name='package'
            AND state='active'
    """.format(gid=g.org.id)
    results = model.Session.execute(q)

    dataset_ids = [x['table_id'] for x in results]
    issues = model.Session.query(issuemodel.Issue)\
        .filter(issuemodel.Issue.dataset_id.in_(dataset_ids))\
        .order_by(issuemodel.Issue.created.desc())

    g.results = collections.defaultdict(list)
    for issue in issues:
        g.results[issue.package].append(issue)
    g.package_set = sorted(set(g.results.keys()), key=lambda x: x.title)
    print(g.package_set)
    return render("issues/organization_issues.html",
                  extra_vars=template_params)
Exemple #9
0
def validate():
    """
    For Manual Validation
    """
    context = {}
    resource_id = toolkit.request.form.get("resource_id")
    try:
        toolkit.check_access('manual_validation', context)
    except toolkit.NotAuthorized:
        toolkit.abort(
            403,
            toolkit._('User %r not authorized to edit %s') %
            (context.user, resource_id))
    if not resource_id:
        toolkit.abort(404, toolkit._('Resource not found'))
    data_dict = {"id": resource_id, "manual_validation": "validated"}
    try:
        toolkit.get_action("resource_update")(context, data_dict)
    except logic.NotFound:
        toolkit.abort(404, toolkit._('Resource not found'))

    h.flash(toolkit._("Resource sucesfully validated"))
    return toolkit.redirect_to("/")
    def login(self):
        '''Handle request to the WAAD redirect_uri.'''
        params = pylons.request.params
        waad_auth_code = params.get('code')

        if not waad_auth_code:
            toolkit.abort(401)

        if not _csrf_check(pylons.request, pylons.response, _csrf_secret()):
            toolkit.abort(401)

        try:
            details = _get_user_details_from_waad(waad_auth_code,
                                                  _waad_client_id(),
                                                  _waad_redirect_uri(),
                                                  _waad_resource(),
                                                  _waad_auth_token_endpoint())
        except InvalidAccessTokenResponse as exc:
            message = toolkit._(
                "Error getting user details from Windows Azure AD: {error}".
                format(error=exc))
            helpers.flash(message,
                          category='alert-error',
                          allow_html=True,
                          ignore_duplicate=True)
            toolkit.redirect_to(controller='user', action='login')

        try:
            user = _log_the_user_in(session=pylons.session, **details)
        except CouldNotCreateUserException as exc:
            message = toolkit._(
                "Creating your CKAN user account failed: {error}".format(
                    error=exc))
            helpers.flash(message,
                          category='alert-error',
                          allow_html=True,
                          ignore_duplicate=True)
            toolkit.redirect_to(controller='user', action='login')
        except CouldNotFindUserException as exc:
            message = toolkit._("The CKAN account for your Windows Azure AD "
                                "user does not exist")
            helpers.flash(message,
                          category='alert-error',
                          allow_html=True,
                          ignore_duplicate=True)
            toolkit.redirect_to(controller='user', action='login')

        toolkit.redirect_to(controller='user',
                            action='dashboard',
                            id=user['name'])
Exemple #11
0
    def login(self):
        '''Handle request to the WAAD redirect_uri.'''
        params = pylons.request.params
        waad_auth_code = params.get('code')

        if not waad_auth_code:
            toolkit.abort(401)

        if not _csrf_check(pylons.request, pylons.response, _csrf_secret()):
            toolkit.abort(401)

        try:
            details = _get_user_details_from_waad(
                waad_auth_code, _waad_client_id(), _waad_redirect_uri(),
                _waad_resource(), _waad_auth_token_endpoint())
        except InvalidAccessTokenResponse as exc:
            message = toolkit._(
                "Error getting user details from Windows Azure AD: {error}"
                .format(error=exc))
            helpers.flash(message, category='alert-error', allow_html=True,
                            ignore_duplicate=True)
            toolkit.redirect_to(controller='user', action='login')

        try:
            user = _log_the_user_in(session=pylons.session, **details)
        except CouldNotCreateUserException as exc:
            message = toolkit._(
                "Creating your CKAN user account failed: {error}".format(
                    error=exc))
            helpers.flash(message, category='alert-error', allow_html=True,
                            ignore_duplicate=True)
            toolkit.redirect_to(controller='user', action='login')
        except CouldNotFindUserException as exc:
            message = toolkit._(
                "The CKAN account for your Windows Azure AD "
                "user does not exist"
            )
            helpers.flash(message, category='alert-error', allow_html=True,
                            ignore_duplicate=True)
            toolkit.redirect_to(controller='user', action='login')

        toolkit.redirect_to(controller='user', action='dashboard',
                            id=user['name'])
Exemple #12
0
 def test_upload_form(self):
     if request.method == 'POST':
         h.flash('Thanks for uploading data', 'alert-info')
         redirect(toolkit.url_for('/dataset'))
     return render('tests/upload-form.html')
def _home_handle_error(package_id, exc):
    msg = toolkit._("Validation error: {0}".format(exc.error_summary))
    h.flash(msg, category='alert-error')
    return p.toolkit.redirect_to('issues_home', package_id=package_id)
    def account_requests_management(self):
        ''' Approve or reject an account request
        '''
        action = request.params['action']
        user_id = request.params['id']
        user_name = request.params['name']
        user = model.User.get(user_id)

        context = {
            'model': model,
            'user': c.user,
            'session': model.Session,
        }
        activity_create_context = {
            'model': model,
            'user': user_name,
            'defer_commit': True,
            'ignore_auth': True,
            'session': model.Session
        }
        activity_dict = {'user_id': c.userobj.id, 'object_id': user_id}
        list_admin_emails = tk.aslist(
            config.get('ckanext.accessrequests.approver_email')
        )
        if action == 'forbid':
            object_id_validators['reject new user'] = user_id_exists
            activity_dict['activity_type'] = 'reject new user'
            logic.get_action('activity_create')(
                activity_create_context, activity_dict
            )
            org = logic.get_action('organization_list_for_user')({
                'user': user_name
            }, {
                "permission": "read"
            })
            if org:
                logic.get_action('organization_member_delete')(
                    context, {
                        "id": org[0]['id'],
                        "username": user_name
                    }
                )
            logic.get_action('user_delete')(context, {'id': user_id})
            msg = (
                "Your account request for {0} has been rejected by {1}"
                "\n\nFor further clarification "
                "as to why your request has been "
                "rejected please contact the NSW Flood Data Portal ({2})"
            )
            mailer.mail_recipient(
                user.fullname, user.email, 'Account request',
                msg.format(
                    config.get('ckan.site_title'), c.userobj.fullname,
                    c.userobj.email
                )
            )
            msg = ("User account request for {0} "
                   "has been rejected by {1}"
                   ).format(user.fullname or user_name, c.userobj.fullname)
            for admin_email in list_admin_emails:
                try:
                    mailer.mail_recipient(
                        'Admin', admin_email, 'Account request feedback', msg
                    )
                except mailer.MailerException as e:
                    h.flash(
                        "Email error: {0}".format(e.message), allow_html=False
                    )
        elif action == 'approve':
            user_org = request.params['org']
            user_role = request.params['role']
            object_id_validators['approve new user'] = user_id_exists
            activity_dict['activity_type'] = 'approve new user'
            logic.get_action('activity_create')(
                activity_create_context, activity_dict
            )
            org_display_name, org_role = assign_user_to_org(
                user_id, user_org, user_role, context
            )
            # Send invitation to complete registration
            msg = (
                "User account request for {0} "
                "(Organization : {1}, Role: {2}) "
                "has been approved by {3}"
            ).format(
                user.fullname or user_name, org_display_name, org_role,
                c.userobj.fullname
            )
            for admin_email in list_admin_emails:
                try:
                    mailer.mail_recipient(
                        'Admin', admin_email, 'Account request feedback', msg
                    )
                except mailer.MailerException as e:
                    h.flash(
                        "Email error: {0}".format(e.message), allow_html=False
                    )
            try:
                org_dict = tk.get_action('organization_show')(context, {'id': user_org})
                user.name = user.name
                mailer.send_invite(user, org_dict, user_role)
            except Exception as e:
                log.error('Error emailing invite to user: %s', e)
                abort(500, _('Error: couldn' 't email invite to user'))

        response.status = 200
        return render('user/account_requests_management.html')
    def _save_new_pending(self, context):
        errors = {}
        error_summary = {}
        params = request.params
        password = str(binascii.b2a_hex(os.urandom(15)))
        data = dict(
            fullname=params['fullname'],
            name=params['name'],
            password1=password,
            password2=password,
            state=model.State.PENDING,
            email=params['email'],
            organization_request=params['organization-for-request'],
            reason_to_access=params['reason-to-access'],
            role=params['role']
        )

        try:
            # captcha.check_recaptcha(request)
            user_dict = logic.get_action('user_create')(context, data)
            if params['organization-for-request']:
                organization = model.Group.get(data['organization_request'])
                sys_admin = model.Session.query(model.User).filter(
                    sqlalchemy.and_(
                        model.User.sysadmin == True,  # noqa
                        model.User.state == 'active'
                    )
                ).first().name
                logic.get_action('organization_member_create')({
                    "user": sys_admin
                }, {
                    "id": organization.id,
                    "username": user_dict['name'],
                    "role": data['role'] if data['role'] else 'member'
                })
                role = data['role'].title() if data['role'] else 'Member'
            else:
                organization = None
            msg = (
                "A request for a new user account has been submitted:"
                "\nUsername: {}"
                "\nName: {}\nEmail: {}\nOrganisation: {}\nRole: {}"
                "\nReason for access: {}"
                "\nThis request can be approved or rejected at {}"
            ).format(
                data['name'], data['fullname'], data['email'],
                organization.display_name if organization else None,
                role if organization else None, data['reason_to_access'],
                g.site_url + h.url_for(
                    controller=(
                        'ckanext.accessrequests.controller'
                        ':AccessRequestsController'
                    ),
                    action='account_requests'
                )
            )
            list_admin_emails = tk.aslist(
                config.get('ckanext.accessrequests.approver_email')
            )
            for admin_email in list_admin_emails:
                try:
                    mailer.mail_recipient(
                        'Admin', admin_email, 'Account request', msg
                    )
                except mailer.MailerException as e:
                    h.flash(
                        "Email error: {0}".format(e.message), allow_html=False
                    )
            h.flash_success(
                'Your request for access to the {0} has been submitted.'.
                format(config.get('ckan.site_title'))
            )
        except ValidationError as e:
            # return validation failures to the form
            if e.error_dict:
                errors = e.error_dict
                error_summary = e.error_summary
            return self.request_account(data, errors, error_summary)
        except CaptchaError:
            errors['Captcha'] = [_(u'Bad Captcha. Please try again.')]
            error_summary['Captcha'] = 'Bad Captcha. Please try again.'
            return self.request_account(data, errors, error_summary)

        h.redirect_to('/')
def _dataset_handle_error(dataset_id, exc):
    msg = toolkit._("Validation error: {0}".format(exc.error_summary))
    h.flash(msg, category='alert-error')
    return p.toolkit.redirect_to('issues_dataset', dataset_id=dataset_id)
 def test_upload_form(self):
     if request.method == 'POST':
         h.flash('Thanks for uploading data', 'alert-info')
         redirect(toolkit.url_for('/dataset'))
     return render('tests/upload-form.html')
Exemple #18
0
def _dataset_handle_error(dataset_id, exc):
    msg = toolkit._(u'Validation error: {0}').format(exc.error_summary)
    h.flash(msg, category='alert-error')
    return p.toolkit.redirect_to('issues_dataset', dataset_id=dataset_id)
Exemple #19
0
def _home_handle_error(package_id, exc):
    msg = toolkit._("Validation error: {0}".format(exc.error_summary))
    h.flash(msg, category='alert-error')
    return p.toolkit.redirect_to('issues_home', package_id=package_id)