Example #1
0
    def _save_new(self, context):
        model = context['model']
        context['ignore_auth'] = True

        try:
            data_dict = logic.clean_dict(unflatten(
                logic.tuplize_dict(logic.parse_params(request.params))))
            context['message'] = data_dict.get('log_message', '')
            captcha.check_recaptcha(request)

            organization = get_action('inventory_organization_by_inventory_id')(
                context, {'id': data_dict['inventory_organization_id']})

            password = str(random.SystemRandom().random())
            data_dict['password1'] = password
            data_dict['password2'] = password
            data_dict['state'] = model.State.PENDING
            user = get_action('user_create')(context, data_dict)

            data_dict = {
                'id': organization['id'],
                'role': 'editor',
                'username': user['name']
            }
            logic.get_action('organization_member_create')(context, data_dict)
        except NotAuthorized:
            abort(401, _('Unauthorized to create user %s') % '')
        except NotFound, e:
            abort(404, _('User or organization not found'))
Example #2
0
    def _save_new(self, context):
        try:
            data_dict = logic.clean_dict(df.unflatten(
                logic.tuplize_dict(logic.parse_params(request.params))))
            context['message'] = data_dict.get('log_message', '')
            captcha.check_recaptcha(request)

            # Extra: Create username from email
            email = data_dict.get('email', '')
            email_user = email.split('@')[0]
            name = re.sub('[^a-z0-9_\-]', '_', email_user)

            # Append num so it becames unique (search inside deleted as well)
            session = context['session']
            user_names = model.User.search(name, session.query(model.User)).all()
            user_names = map(lambda u: u.name, user_names)
            while name in user_names:
                m = re.match('^(.*?)(\d+)$', name)
                if m:
                    name = m.group(1) + str(int(m.group(2)) + 1)
                else:
                    name = name + '2'

            data_dict['name'] = name
            user = get_action('user_create')(context, data_dict)
        except NotAuthorized:
            abort(401, _('Unauthorized to create user %s') % '')
        except NotFound, e:
            abort(404, _('User not found'))
Example #3
0
 def _save_new(self, context,data_dict):
     try:
         context['message'] = data_dict.get('log_message', '')
         captcha.check_recaptcha(request)
         user = get_action('user_create')(context, data_dict)
     except NotAuthorized:
         abort(401, _('Unauthorized to create user %s') % '')
     except NotFound, e:
         abort(404, _('User not found'))
    def _send_suggestion(self, context):
        try:
            data_dict = logic.clean_dict(unflatten(
                logic.tuplize_dict(logic.parse_params(request.params))))
            context['message'] = data_dict.get('log_message', '')

            c.form = data_dict['name']
            captcha.check_recaptcha(request)

            # return base.render('suggest/form.html')
        except logic.NotAuthorized:
            base.abort(401, _('Not authorized to see this page'))

        except captcha.CaptchaError:
            error_msg = _(u'Bad Captcha. Please try again.')
            h.flash_error(error_msg)
            return self.suggest_form(data_dict)

        errors = {}
        error_summary = {}

        if (data_dict["email"] == ''):
            errors['email'] = [u'Missing Value']
            error_summary['email'] = u'Missing value'

        if (data_dict["name"] == ''):
            errors['name'] = [u'Missing Value']
            error_summary['name'] = u'Missing value'

        if (data_dict["suggestion"] == ''):
            errors['suggestion'] = [u'Missing Value']
            error_summary['suggestion'] = u'Missing value'

        if len(errors) > 0:
            return self.suggest_form(data_dict, errors, error_summary)
        else:
            # #1799 User has managed to register whilst logged in - warn user
            # they are not re-logged in as new user.
            mail_to = config.get('email_to')
            recipient_name = 'CKAN Surrey'
            subject = 'CKAN - Dataset suggestion'

            body = 'Submitted by %s (%s)\n' % (data_dict["name"], data_dict["email"])

            if (data_dict["category"] != ''):
                body += 'Category: %s' % data_dict["category"]

            body += 'Request: %s' % data_dict["suggestion"]

            try:
                mailer.mail_recipient(recipient_name, mail_to,
                                      subject, body)
            except mailer.MailerException:
                raise

            return base.render('suggest/suggest_success.html')
Example #5
0
 def _save_new(self, context):
     try:
         data_dict = logic.clean_dict(unflatten(logic.tuplize_dict(logic.parse_params(request.params))))
         context["message"] = data_dict.get("log_message", "")
         captcha.check_recaptcha(request)
         user = get_action("user_create")(context, data_dict)
     except NotAuthorized:
         abort(401, _("Unauthorized to create user %s") % "")
     except NotFound, e:
         abort(404, _("User not found"))
    def _send_contact(self, context):
        try:
            data_dict = logic.clean_dict(unflatten(
                logic.tuplize_dict(logic.parse_params(request.params))))
            context['message'] = data_dict.get('log_message', '')

            c.form = data_dict['name']
            captcha.check_recaptcha(request)
            #return base.render('suggest/form.html')
        except logic.NotAuthorized:
            base.abort(401, _('Not authorized to see this page'))
        except captcha.CaptchaError:
            error_msg = _(u'Bad Captcha. Please try again.')
            h.flash_error(error_msg)
            return self.contact_form(data_dict)

        errors = {}
        error_summary = {}

        if (data_dict["email"] == ''):

            errors['email'] = [u'Missing Value']
            error_summary['email'] =  u'Missing value'

        if (data_dict["name"] == ''):

            errors['name'] = [u'Missing Value']
            error_summary['name'] =  u'Missing value'


        if (data_dict["content"] == ''):

            errors['content'] = [u'Missing Value']
            error_summary['content'] =  u'Missing value'


        if len(errors) > 0:
            return self.suggest_form(data_dict, errors, error_summary)
        else:
            mail_to = config.get('email_to')
            recipient_name = 'CKAN'
            subject = 'CKAN - Contact/Question from visitor'

            body = 'Submitted by %s (%s)\n' % (data_dict["name"], data_dict["email"])

            body += 'Request: %s' % data_dict["content"]

            try:
                mailer.mail_recipient(recipient_name, mail_to,
                        subject, body)
            except mailer.MailerException:
                raise


            return base.render('contact/success.html')
Example #7
0
File: user.py Project: ITMGR/ckan
 def _save_new(self, context):
     try:
         data_dict = logic.clean_dict(unflatten(
             logic.tuplize_dict(logic.parse_params(request.params))))
         context['message'] = data_dict.get('log_message', '')
         captcha.check_recaptcha(request)
         user = get_action('user_create')(context, data_dict)
     except NotAuthorized:
         abort(403, _('Unauthorized to create user %s') % '')
     except NotFound, e:
         abort(404, _('User not found'))
Example #8
0
    def _submit(context):

        try:
            data_dict = logic.clean_dict(unflatten(logic.tuplize_dict(logic.parse_params(request.params))))
            context['message'] = data_dict.get('log_message', '')
            c.form = data_dict['name']
            captcha.check_recaptcha(request)
        except logic.NotAuthorized:
            base.abort(401, _('Not authorized to see this page'))
        except captcha.CaptchaError:
            error_msg = _(u'Bad Captcha. Please try again.')
            h.flash_error(error_msg)

        errors = {}
        error_summary = {}

        if data_dict["email"] == '':
            errors['email'] = [u'Missing Value']
            error_summary['email'] = u'Missing value'

        if data_dict["name"] == '':
            errors['name'] = [u'Missing Value']
            error_summary['name'] = u'Missing value'

        if data_dict["content"] == '':
            errors['content'] = [u'Missing Value']
            error_summary['content'] = u'Missing value'

        if len(errors) == 0:

            body = '%s' % data_dict["content"]
            body += '\n\nSent by:\nName:%s\nEmail: %s\n' % (data_dict["name"], data_dict["email"])
            mail_dict = {
                'recipient_email': config.get("ckanext.contact.mail_to", config.get('email_to')),
                'recipient_name': config.get("ckanext.contact.recipient_name", config.get('ckan.site_title')),
                'subject': config.get("ckanext.contact.subject", 'Contact/Question from visitor'),
                'body': body,
                'headers': {'reply-to': data_dict["email"]}
            }

            # Allow other plugins to modify the mail_dict
            for plugin in p.PluginImplementations(IContact):
                plugin.mail_alter(mail_dict, data_dict)

            try:
                mailer.mail_recipient(**mail_dict)
            except (mailer.MailerException, socket.error):
                h.flash_error(_(u'Sorry, there was an error sending the email. Please try again later'))
            else:
                data_dict['success'] = True
                
        return data_dict, errors, error_summary
 def _save_new(self, context):
     came_from = request.params.get('came_from', '')
     sig = request.params.get('sig', '')
     redirect_url = came_from + '&sig=' + sig if came_from != '' else ''
     redirect_url = str(redirect_url)  #to deal with Unicode objects
     try:
         data_dict = logic.clean_dict(
             unflatten(
                 logic.tuplize_dict(logic.parse_params(request.params))))
         context['message'] = data_dict.get('log_message', '')
         captcha.check_recaptcha(request)
         user = get_action('user_create')(context, data_dict)
     except NotAuthorized:
         abort(403, _('Unauthorized to create user %s') % '')
     except NotFound as e:
         abort(404, _('User not found'))
     except DataError:
         abort(400, _(u'Integrity Error'))
     except captcha.CaptchaError:
         error_msg = _(u'Bad Captcha. Please try again.')
         h.flash_error(error_msg)
         return self.new(data_dict)
     except ValidationError as e:
         errors = e.error_dict
         error_summary = e.error_summary
         return self.new(data_dict, errors, error_summary)
     if not c.user:
         # log the user in programatically
         set_repoze_user(data_dict['name'])
         if redirect_url == '':
             h.redirect_to(controller='user', action='me')
         else:
             log.error("\n\n Redirect URL: %s\n\n" % redirect_url)
             h.redirect_to(redirect_url)
     else:
         # #1799 User has managed to register whilst logged in - warn user
         # they are not re-logged in as new user.
         h.flash_success(
             _('User "%s" is now registered but you are still '
               'logged in as "%s" from before') %
             (data_dict['name'], c.user))
         if authz.is_sysadmin(c.user):
             # the sysadmin created a new user. We redirect him to the
             # activity page for the newly created user
             h.redirect_to(controller='user',
                           action='activity',
                           id=data_dict['name'])
         else:
             return render('user/logout_first.html')
Example #10
0
    def _send_contact(self, context):
        try:
            data_dict = logic.clean_dict(unflatten(
                logic.tuplize_dict(logic.parse_params(request.params))))
            context['message'] = data_dict.get('log_message', '')

            c.form = data_dict['name']
            captcha.check_recaptcha(request)
            # return base.render('suggest/form.html')
        except logic.NotAuthorized:
            base.abort(401, _('Not authorized to see this page'))
        except captcha.CaptchaError:
            error_msg = _(u'Bad Captcha. Please try again.')
            h.flash_error(error_msg)
            return self.contact_form(data_dict)

        errors = {}
        error_summary = {}

        if (data_dict["email"] == ''):
            errors['email'] = [u'Missing Value']
            error_summary['email'] = u'Missing value'

        if (data_dict["name"] == ''):
            errors['name'] = [u'Missing Value']
            error_summary['name'] = u'Missing value'

        if (data_dict["content"] == ''):
            errors['content'] = [u'Missing Value']
            error_summary['content'] = u'Missing value'

        if len(errors) > 0:
            return self.suggest_form(data_dict, errors, error_summary)
        else:
            mail_to = config.get('email_to')
            recipient_name = 'CKAN Surrey'
            subject = 'CKAN - Contact/Question from visitor'

            body = 'Submitted by %s (%s)\n' % (data_dict["name"], data_dict["email"])

            body += 'Request: %s' % data_dict["content"]

            try:
                mailer.mail_recipient(recipient_name, mail_to,
                                      subject, body)
            except mailer.MailerException:
                raise

            return base.render('contact/success.html')
Example #11
0
    def _send_request(self, context):

        try:
            data_dict = logic.clean_dict(unflatten(
                logic.tuplize_dict(logic.parse_params(request.params))))

            captcha.check_recaptcha(request)

        except logic.NotAuthorized:
            toolkit.abort(401, _('Not authorized to see this page'))
        except captcha.CaptchaError:
            error_msg = _('Bad Captcha. Please try again.')
            h.flash_error(error_msg)
            return self.restricted_request_access_form(
                package_id=data_dict.get('package_name'),
                resource_id=data_dict.get('resource'),
                data=data_dict)

        try:
            pkg = toolkit.get_action('package_show')(
                context, {'id': data_dict.get('package_name')})
            data_dict['pkg_dict'] = pkg
        except toolkit.ObjectNotFound:
            toolkit.abort(404, _('Dataset not found'))
        except Exception:
            toolkit.abort(404, _('Exception retrieving dataset to send mail'))

        # Validation
        errors = {}
        error_summary = {}

        if (data_dict['message'] == ''):
            msg = _('Missing Value')
            errors['message'] = [msg]
            error_summary['message'] = msg

        if len(errors) > 0:
            return self.restricted_request_access_form(
                data=data_dict,
                errors=errors,
                error_summary=error_summary,
                package_id=data_dict.get('package-name'),
                resource_id=data_dict.get('resource'))

        success = self._send_request_mail(data_dict)

        return render(
            'restricted/restricted_request_access_result.html',
            extra_vars={'data': data_dict, 'pkg_dict': pkg, 'success': success})
Example #12
0
    def request(self, data=None, errors=None, error_summary=None):
        ''' The functionality of sending emails with new user requests has been deprecated.
            Deprecated since hdx 0.3.5
        '''

        context = {
            'model': model,
            'session': model.Session,
            'user': c.user,
            'request': 'request' in request.params
        }
        # try:
        #    check_access('request_register', context)
        # except NotAuthorized:
        #    abort(401, _('Unauthorized to request new registration.'))

        if context['request'] and not data:
            data = logic.clean_dict(
                unflatten(
                    logic.tuplize_dict(logic.parse_params(request.params))))
            errors = dict()
            error_summary = dict()

            self._validate_form(data, errors)
            try:
                captcha.check_recaptcha(request)
            except captcha.CaptchaError:
                error_msg = _(u'Bad Captcha. Please try again.')
                error_summary['captcha'] = error_msg
                errors['captcha'] = [error_msg]

            if errors == {}:
                name = data['fullname']
                email = data['email']
                org = data['org']
                reason = data['reason']

                h.log.info(
                    'Request access for {name} ({email}) of {org} with reason: {reason}'
                    .format(name=name, email=email, org=org, reason=reason))
                try:
                    # send_mail(name, email, org, reason)
                    h.flash_success(
                        _('We will check your request and we will send you an email!'
                          ))
                    h.redirect_to('/')
                except mailer.MailerException, e:
                    error_summary['sendError'] = _(
                        'Could not send request for access: %s') % unicode(e)
Example #13
0
    def post(self):
        context = self._prepare()
        try:
            data_dict = logic.clean_dict(
                dictization_functions.unflatten(
                    logic.tuplize_dict(logic.parse_params(request.form))))
        except dictization_functions.DataError:
            base.abort(400, _(u'Integrity Error'))

        context[u'message'] = data_dict.get(u'log_message', u'')
        try:
            captcha.check_recaptcha(request)
        except captcha.CaptchaError:
            error_msg = _(u'Bad Captcha. Please try again.')
            h.flash_error(error_msg)
            return self.get(data_dict)

        try:
            logic.get_action(u'user_create')(context, data_dict)
        except logic.NotAuthorized:
            base.abort(403, _(u'Unauthorized to create user %s') % u'')
        except logic.NotFound:
            base.abort(404, _(u'User not found'))
        except logic.ValidationError as e:
            errors = e.error_dict
            error_summary = e.error_summary
            return self.get(data_dict, errors, error_summary)

        if g.user:
            # #1799 User has managed to register whilst logged in - warn user
            # they are not re-logged in as new user.
            h.flash_success(
                _(u'User "%s" is now registered but you are still '
                  u'logged in as "%s" from before') %
                (data_dict[u'name'], g.user))
            if authz.is_sysadmin(g.user):
                # the sysadmin created a new user. We redirect him to the
                # activity page for the newly created user
                return h.redirect_to(u'user.activity', id=data_dict[u'name'])
            else:
                return base.render(u'user/logout_first.html')

        # log the user in programatically
        resp = h.redirect_to(u'user.me')
        set_repoze_user(data_dict[u'name'], resp)
        return resp
Example #14
0
    def post(self):
        context = self._prepare()
        try:
            data_dict = logic.clean_dict(
                dictization_functions.unflatten(
                    logic.tuplize_dict(logic.parse_params(request.form))))
        except dictization_functions.DataError:
            base.abort(400, _(u'Integrity Error'))

        context[u'message'] = data_dict.get(u'log_message', u'')
        try:
            captcha.check_recaptcha(request)
        except captcha.CaptchaError:
            error_msg = _(u'Bad Captcha. Please try again.')
            h.flash_error(error_msg)
            return self.get(data_dict)

        try:
            logic.get_action(u'user_create')(context, data_dict)
        except logic.NotAuthorized:
            base.abort(403, _(u'Unauthorized to create user %s') % u'')
        except logic.NotFound:
            base.abort(404, _(u'User not found'))
        except logic.ValidationError as e:
            errors = e.error_dict
            error_summary = e.error_summary
            return self.get(data_dict, errors, error_summary)

        if g.user:
            # #1799 User has managed to register whilst logged in - warn user
            # they are not re-logged in as new user.
            h.flash_success(
                _(u'User "%s" is now registered but you are still '
                  u'logged in as "%s" from before') % (data_dict[u'name'],
                                                       g.user))
            if authz.is_sysadmin(g.user):
                # the sysadmin created a new user. We redirect him to the
                # activity page for the newly created user
                return h.redirect_to(u'user.activity', id=data_dict[u'name'])
            else:
                return base.render(u'user/logout_first.html')

        # log the user in programatically
        resp = h.redirect_to(u'user.me')
        set_repoze_user(data_dict[u'name'], resp)
        return resp
    def _send_organization_request(self, context):

        try:
            data_dict = logic.clean_dict(
                unflatten(
                    logic.tuplize_dict(logic.parse_params(request.params))))

            captcha.check_recaptcha(request)

        except logic.NotAuthorized:
            toolkit.abort(401, _('Not authorized to see this page'))
        except captcha.CaptchaError:
            error_msg = _('Bad Captcha. Please try again.')
            h.flash_error(error_msg)
            return self.restricted_request_organization_form(data=data_dict)

        # Validation
        errors = {}
        error_summary = {}

        text_fields = [
            "organization_name",
            "organization_web",
            "organization_description",
            "reason",
        ]

        for field in text_fields:
            if data_dict.get(field, '') == '':
                msg = _('Missing Value')
                errors[field] = [msg]
                error_summary[field] = msg

        if len(errors) > 0:
            return self.restricted_request_organization_form(
                data=data_dict, errors=errors, error_summary=error_summary)

        success = self._send_organization_request_mail(data_dict)

        return render('restricted/restricted_request_organization_result.html',
                      extra_vars={
                          'data': data_dict,
                          'pkg_dict': {},
                          'success': success
                      })
Example #16
0
    def _save_new(self, context):
        print(request.params)
        try:
            data_dict = logic.clean_dict(
                unflatten(
                    logic.tuplize_dict(logic.parse_params(request.params))))

            self._validate_academic_email(request.params['email'])
            self._validate_eula_accept(data_dict)

            context['message'] = data_dict.get('log_message', '')
            captcha.check_recaptcha(request)

            user = get_action('user_create')(context, data_dict)
            self._after_signup(user)

        except NotAuthorized:
            abort(403, _('Unauthorized to create user %s') % '')
        except NotFound, e:
            abort(404, _('User not found'))
    def request(self, data=None, errors=None, error_summary=None):
        ''' The functionality of sending emails with new user requests has been deprecated.
            Deprecated since hdx 0.3.5
        '''

        context = {'model': model, 'session': model.Session,
                   'user': c.user,
                   'request': 'request' in request.params}
        #try:
        #    check_access('request_register', context)
        #except NotAuthorized:
        #    abort(401, _('Unauthorized to request new registration.'))

        if context['request'] and not data:
            data = logic.clean_dict(unflatten(
                logic.tuplize_dict(logic.parse_params(request.params))))
            errors = dict()
            error_summary = dict()

            self._validate_form(data, errors)
            try:
                captcha.check_recaptcha(request)
            except captcha.CaptchaError:
                error_msg = _(u'Bad Captcha. Please try again.')
                error_summary['captcha'] = error_msg
                errors['captcha'] = [error_msg]

            if errors == {}:
                name = data['fullname']
                email = data['email']
                org = data['org']
                reason = data['reason']

                h.log.info('Request access for {name} ({email}) of {org} with reason: {reason}'.format(name = name, email = email, org = org, reason=reason))
                try:
                    send_mail(name, email, org, reason)
                    h.flash_success(_('We will check your request and we will send you an email!'))
                    h.redirect_to('/')
                except mailer.MailerException, e:
                    error_summary['sendError'] = _('Could not send request for access: %s') % unicode(e)
Example #18
0
File: user.py Project: gsueur/ckan
 def _save_new(self, context):
     try:
         data_dict = logic.clean_dict(unflatten(
             logic.tuplize_dict(logic.parse_params(request.params))))
         context['message'] = data_dict.get('log_message', '')
         captcha.check_recaptcha(request)
         user = get_action('user_create')(context, data_dict)
     except NotAuthorized:
         abort(403, _('Unauthorized to create user %s') % '')
     except NotFound as e:
         abort(404, _('User not found'))
     except DataError:
         abort(400, _(u'Integrity Error'))
     except captcha.CaptchaError:
         error_msg = _(u'Bad Captcha. Please try again.')
         h.flash_error(error_msg)
         return self.new(data_dict)
     except ValidationError as e:
         errors = e.error_dict
         error_summary = e.error_summary
         return self.new(data_dict, errors, error_summary)
     if not c.user:
         # log the user in programatically
         set_repoze_user(data_dict['name'])
         h.redirect_to(controller='user', action='me')
     else:
         # #1799 User has managed to register whilst logged in - warn user
         # they are not re-logged in as new user.
         h.flash_success(_('User "%s" is now registered but you are still '
                         'logged in as "%s" from before') %
                         (data_dict['name'], c.user))
         if authz.is_sysadmin(c.user):
             # the sysadmin created a new user. We redirect him to the
             # activity page for the newly created user
             h.redirect_to(controller='user',
                           action='activity',
                           id=data_dict['name'])
         else:
             return render('user/logout_first.html')
Example #19
0
    def _save_new(self, context):
        try:
            data_dict = logic.clean_dict(unflatten(
                logic.tuplize_dict(logic.parse_params(request.params))))

            context['message'] = data_dict.get('log_message', '')
            captcha.check_recaptcha(request)
            user = get_action('user_create')(context, data_dict)
            for times in range(3):
                msg = h.get_billing_api("api/RegisterAndSession/register", request_type='post', ckan_user_id=user.get('id'),
                                       ckan_user_name=user.get('name'), role=user.get('sysadmin'))
                decoded = json.loads(msg)
                if decoded['msg'] == 'error':
                    log.debug('register as %r failed %r times - initial the  session failed', user.get('name'), times)
                elif decoded['msg'] == 'success':
                    break
                else:
                    log.debug('register as %r failed %r times - api/RegisterAndSession/register return wrong data', user.get('name'), times)

        except NotAuthorized:
            abort(403, _('Unauthorized to create user %s') % '')
        except NotFound, e:
            abort(404, _('User not found'))
Example #20
0
    def _submit(context):
        try:
            data_dict = logic.clean_dict(
                unflatten(
                    logic.tuplize_dict(logic.parse_params(request.params))))
            context['message'] = data_dict.get('log_message', '')
            c.form = data_dict['name']
            captcha.check_recaptcha(request)
        except logic.NotAuthorized:
            base.abort(401, _('Not authorized to see this page'))
        except captcha.CaptchaError:
            error_msg = _(u'Bad Captcha. Please try again.')
            h.flash_error(error_msg)

        errors = {}
        error_summary = {}

        if data_dict["email"] == '':
            errors['email'] = [_(u'Missing value')]
            error_summary[_(u'email')] = _(u'Missing value')

        if data_dict["name"] == '':
            errors['name'] = [_(u'Missing Value')]
            error_summary[_(u'name')] = _(u'Missing value')

        if data_dict["content"] == '':
            errors['content'] = [_(u'Missing value')]
            error_summary[_(u'request')] = _(u'Missing value')

        if len(errors) == 0:
            global author_email_address
            global report_referrer
            global report_resource_name
            global report_organization_name
            global report_dataset_name

            if report_organization_name is None:
                report_organization_name = ""
            if report_dataset_name is None:
                report_dataset_name = ""
            if report_dataset_name is None:
                report_dataset_name = ""

            if "form" in request.GET:
                if "link" in request.GET.getone('form'):
                    report_mail_title = _(
                        u'Report Broken Link - Government Data')
                    report_mail_secondary_title = _(
                        u'A broken link report is recieved')
            else:
                report_mail_title = _(u'Report - Government Data')
                report_mail_secondary_title = _(u'A report is recieved')
            body = _('Hello') + ","
            body += '\n' + report_mail_secondary_title
            body += '\n' + _(
                u'First name and surname') + ": " + data_dict["name"]
            body += '\n' + _(u'Email') + ": " + data_dict["email"]
            body += '\n' + _(u'Data ID') + ': ' + data_dict["id"]
            body += '\n' + _(u'Link to data') + ': ' + report_referrer
            body += '\n' + _(u'Message') + ': ' + data_dict["content"]
            body += '\n' + _(u'Organization') + ': ' + report_organization_name
            body += '\n' + _(u'Dataset') + ': ' + report_dataset_name
            body += '\n' + _(u'Resource') + ': ' + report_resource_name
            body += '\n\n' + _(u'Best Regards')
            body += '\n' + _(u'Government Data Site')

            mail_dict = {
                #added it to send it to the maintainer of the data
                'recipient_email':
                config.get('email_to'),
                'recipient_name':
                config.get("ckanext.report.recipient_name",
                           config.get('ckan.site_title')),
                'subject':
                config.get("ckanext.report.subject", report_mail_title),
                'body':
                body,
                'headers': {
                    'reply-to': data_dict["email"]
                }
            }

            mail_dict_author = {
                #added it to send it to the author of the data
                'recipient_email':
                author_email_address,
                'recipient_name':
                config.get("ckanext.report.recipient_name",
                           config.get('ckan.site_title')),
                'subject':
                config.get("ckanext.report.subject", report_mail_title),
                'body':
                body,
                'headers': {
                    'reply-to': data_dict["email"]
                }
            }

            # Allow other plugins to modify the mail_dict
            for plugin in p.PluginImplementations(Ireport):
                plugin.mail_alter(mail_dict, data_dict)
                plugin.mail_alter(mail_dict_author, data_dict)
            try:
                #sending email
                custom_mailer.mail_recipient(**mail_dict)
                if author_email_address:
                    custom_mailer.mail_recipient(**mail_dict_author)
            except (mailer.MailerException, socket.error):
                h.flash_error(
                    _(u'Sorry, there was an error sending the email. Please try again later'
                      ))
            else:
                data_dict['success'] = True

        return data_dict, errors, error_summary
Example #21
0
    def _send_contact(self, context):
        try:
            data_dict = logic.clean_dict(
                unflatten(
                    logic.tuplize_dict(logic.parse_params(request.params))))
            context['message'] = data_dict.get('log_message', '')

            c.form = data_dict['name']
            captcha.check_recaptcha(request)
            #return base.render('suggest/form.html')
        except logic.NotAuthorized:
            base.abort(401,
                       _('Vous n\'êtes pas autorisé à accéder à cette page'))
        except captcha.CaptchaError:
            error_msg = _(u'Mauvais code captcha. Veuillez réessayer.')
            h.flash_error(error_msg)
            return self.contact_form(data_dict)

        errors = {}
        error_summary = {}

        if (data_dict["email"] == ''):

            errors['email'] = [u'Valeur manquante']
            error_summary['email'] = u'Valeur manquante'

        if (data_dict["name"] == ''):

            errors['name'] = [u'Valeur manquante']
            error_summary['name'] = u'Valeur manquante'

        if (data_dict["content"] == ''):

            errors['content'] = [u'Valeur manquante']
            error_summary['content'] = u'Valeur manquante'

        if len(errors) > 0:
            return self.suggest_form(data_dict, errors, error_summary)
        else:

            if data_dict['organization'] == 'all':
                mail_to = config.get('email_to')
            else:
                mail_to = logic.get_action('organization_show')(
                    {}, {
                        'id': data_dict['organization']
                    })['email']

            recipient_name = 'Données Québec'.decode('utf8')
            subject = 'Question/commentaire d\'un visiteur'.decode('utf8')

            body = 'Soumis par %s (%s)\n'.decode('utf8') % (data_dict["name"],
                                                            data_dict["email"])

            body += 'Demande: %s'.decode('utf8') % data_dict["content"]

            try:
                mailer.mail_recipient(recipient_name, mail_to, subject, body)
            except mailer.MailerException:
                raise

            return base.render('contact/success.html')
Example #22
0
    def _send_suggestion(self, context):
        try:
            data_dict = logic.clean_dict(
                unflatten(
                    logic.tuplize_dict(logic.parse_params(request.params))))
            context['message'] = data_dict.get('log_message', '')

            c.form = data_dict['name']
            captcha.check_recaptcha(request)

            #return base.render('suggest/form.html')
        except logic.NotAuthorized:
            base.abort(401,
                       _('Vous n\'êtes pas autorisé à accéder à cette page'))

        except captcha.CaptchaError:
            error_msg = _(u'Mauvais code captcha. Essayez de nouveau')
            h.flash_error(error_msg)
            return self.suggest_form(data_dict)

        errors = {}
        error_summary = {}

        if (data_dict["email"] == ''):

            errors['email'] = [u'Valeur manquante']
            error_summary['email'] = u'Valeur manquante'

        if (data_dict["name"] == ''):

            errors['name'] = [u'Valeur manquante']
            error_summary['name'] = u'Valeur manquante'

        if (data_dict["suggestion"] == ''):

            errors['suggestion'] = [u'Valeur manquante']
            error_summary['suggestion'] = u'Valeur manquante'

        if len(errors) > 0:
            return self.suggest_form(data_dict, errors, error_summary)
        else:
            # #1799 User has managed to register whilst logged in - warn user
            # they are not re-logged in as new user.

            if data_dict['organization'] == 'all':
                mail_to = config.get('email_to')
            else:
                mail_to = logic.get_action('organization_show')(
                    {}, {
                        'id': data_dict['organization']
                    })['email']

            recipient_name = 'Données Quebec'.decode('utf8')
            subject = 'Suggestion de jeu de données'.decode('utf8')

            body = 'Soumis par %s (%s)\n' % (data_dict["name"],
                                             data_dict["email"])

            if (data_dict["category"] != ''):
                body += 'Catégorie de données: %s'.decode(
                    'utf8') % data_dict["category"]

            body += 'Nature de la demande: %s'.decode(
                'utf8') % data_dict["suggestion"]

            if (data_dict["usage"] != ''):
                body += 'Utilisation visée: %s'.decode(
                    'utf8') % data_dict["usage"]

            try:
                mailer.mail_recipient(recipient_name, mail_to, subject, body)
            except mailer.MailerException:
                raise

            return base.render('suggest/suggest_success.html')
Example #23
0
    def _submit(context):

        try:
            data_dict = logic.clean_dict(
                unflatten(
                    logic.tuplize_dict(logic.parse_params(request.params))))
            context['message'] = data_dict.get('log_message', '')
            c.form = data_dict['name']
            captcha.check_recaptcha(request)
        except logic.NotAuthorized:
            base.abort(401, _('Not authorized to see this page'))
        except captcha.CaptchaError:
            error_msg = _(u'Bad Captcha. Please try again.')
            h.flash_error(error_msg)

        errors = {}
        error_summary = {}

        if data_dict["email"] == '':
            errors['email'] = [_(u'Missing value')]
            error_summary[_('email')] = _(u'Missing value')

        if data_dict["name"] == '':
            errors['name'] = [_(u'Missing value')]
            error_summary[_('Contact Name')] = _(u'Missing value')

        if data_dict["content"] == '':
            errors['content'] = [_(u'Missing value')]
            error_summary[_('request')] = _(u'Missing value')

        if c.contact_title == _('Data Request'):
            body_title = _('A data request form is recieved')
            mail_subject = _('Data Request - Government Data')
        else:
            body_title = _('A contact form is recieved')
            mail_subject = _('Contact - Government Data')

        if len(errors) == 0:

            body = _('Hello') + ","
            body += '\n' + body_title
            body += '\n' + _(
                u'First name and surname') + ":" + data_dict["name"]
            body += '\n' + _(u'Email') + ":" + data_dict["email"]
            body += '\n' + _(u'Message') + ':' + data_dict["content"]
            body += '\n\n' + _(u'Best Regards')
            body += '\n' + _(u'Government Data Site')

            mail_dict = {
                'recipient_email':
                config.get('email_to'),
                'recipient_name':
                config.get("ckanext.contact.recipient_name",
                           config.get('ckan.site_title')),
                'subject':
                config.get("ckanext.contact.subject", mail_subject),
                'body':
                body,
                'headers': {
                    'reply-to': data_dict["email"]
                }
            }

            # Allow other plugins to modify the mail_dict
            for plugin in p.PluginImplementations(IContact):
                plugin.mail_alter(mail_dict, data_dict)

            try:
                custom_mailer.mail_recipient(**mail_dict)
            except (mailer.MailerException, socket.error):
                h.flash_error(
                    _(u'Sorry, there was an error sending the email. Please try again later'
                      ))
            else:
                data_dict['success'] = True

        return data_dict, errors, error_summary
Example #24
0
    def post(self):
        if toolkit.c.user:
            return toolkit.abort(
                403,
                "You can't create a new user account while already logged in")

        context = self._prepare()
        try:
            data_dict = logic.clean_dict(
                dictization_functions.unflatten(
                    logic.tuplize_dict(logic.parse_params(
                        toolkit.request.form))))
        except dictization_functions.DataError:
            toolkit.abort(400, _(u'Integrity Error'))

        context[u'message'] = data_dict.get(u'log_message', u'')
        try:
            captcha.check_recaptcha(toolkit.request)
        except captcha.CaptchaError:
            error_msg = _(u'Bad Captcha. Please try again.')
            toolkit.h.flash_error(error_msg)
            return self.get(data_dict)

        try:
            domain = toolkit.request.form['email'].split('@')[1]
        except IndexError:
            error_message = 'Please enter an email address'
            return self.get(data_dict, {'email': [error_message]},
                            {'email': error_message})

        if domain in get_internal_domains():
            error_message = (
                'Users with an @{domain} email may not register for a partner account. '
                .format(domain=domain) +
                'Log in to {site} using {email} and use your Active Directory password to access RIDL'
                .format(site=toolkit.config.get('ckan.site_url'),
                        email=toolkit.request.form['email']))
            return self.get(data_dict, {'email': [error_message]},
                            {'email': error_message})

        if not data_dict.get('container'):
            error_message = "A region must be specified"
            return self.get(data_dict, {'container': [error_message]},
                            {'container': error_message})

        context['defer_commit'] = True
        data_dict['state'] = context['model'].State.PENDING
        deposit = get_data_deposit()
        containers = [data_dict.get('container'), deposit['id']]
        data_dict['default_containers'] = containers

        try:
            model.Session.begin_nested()
            user = toolkit.get_action(u'user_create')(context, data_dict)

            access_request_data_dict = {
                'object_id': user['id'],
                'object_type': 'user',
                'message': data_dict['message'],
                'role': 'member',
                'data': {
                    'default_containers': containers,
                    'user_request_type': USER_REQUEST_TYPE_NEW
                }
            }
            toolkit.get_action(u'access_request_create')({
                'user': user['id'],
                'ignore_auth': True,
                'defer_commit': True
            }, access_request_data_dict)

            model.Session.commit()
        except toolkit.NotAuthorized:
            model.Session.rollback()
            toolkit.abort(403, _(u'Unauthorized to create user %s') % u'')
        except toolkit.ObjectNotFound:
            model.Session.rollback()
            toolkit.abort(404, _(u'User not found'))
        except toolkit.ValidationError as e:
            model.Session.rollback()
            errors = e.error_dict
            error_summary = e.error_summary
            return self.get(data_dict, errors, error_summary)
        except:
            model.Session.rollback()
            raise

        recipients = mailer.get_user_account_request_access_email_recipients(
            containers)
        for recipient in recipients:
            subj = mailer.compose_user_request_access_email_subj()
            body = mailer.compose_request_access_email_body(
                'user', recipient, user, user, data_dict['message'])
            toolkit.enqueue_job(mailer.mail_user_by_id,
                                [recipient['name'], subj, body])

        return toolkit.render(u'user/account_created.html',
                              {'email': data_dict['email']})
Example #25
0
    def _submit(context):
        try:
            data_dict = logic.clean_dict(unflatten(logic.tuplize_dict(logic.parse_params(request.params))))
            context['message'] = data_dict.get('log_message', '')
            c.form = data_dict['name']
            captcha.check_recaptcha(request)
        except logic.NotAuthorized:
            base.abort(401, _('Not authorized to see this page'))
        except captcha.CaptchaError:
            error_msg = _(u'Bad Captcha. Please try again.')
            h.flash_error(error_msg)

        errors = {}
        error_summary = {}

        if data_dict["email"] == '':
            errors['email'] = [_(u'Missing value')]
            error_summary[_(u'email')] = _(u'Missing value')

        if data_dict["name"] == '':
            errors['name'] = [_(u'Missing Value')]
            error_summary[_(u'name')] = _(u'Missing value')

        if data_dict["content"] == '':
            errors['content'] = [_(u'Missing value')]
            error_summary[_(u'request')] = _(u'Missing value')

        if len(errors) == 0:
            global author_email_address
            #global report_referrer
            global report_resource_name
            global report_organization_name
            global report_dataset_name

            if report_organization_name is None:
                report_organization_name = ""
            if report_dataset_name is None:
                report_dataset_name = ""
            if report_dataset_name is None:
                report_dataset_name = ""

            if "form" in request.GET:
                if "link" in request.GET.getone('form'):
                    report_mail_title = _(u'Report Broken Link - Government Data')
                    report_mail_secondary_title = _(u'A broken link report is recieved')
            else:
                report_mail_title = _(u'Report - Government Data')
                report_mail_secondary_title = _(u'A report is recieved')
            body = _('Hello')+","
            body += '\n'+report_mail_secondary_title
            body += '\n'+_(u'First name and surname')+": "+data_dict["name"]
            body += '\n'+_(u'Email')+": "+data_dict["email"]
            body += '\n'+_(u'Data ID')+': '+data_dict["id"]
            body += '\n'+_(u'Link to data')+': '+report_referrer
            body += '\n'+_(u'Message')+': '+data_dict["content"]
            body += '\n'+_(u'Organization')+': '+report_organization_name
            body += '\n'+_(u'Dataset')+': '+report_dataset_name
            body += '\n'+_(u'Resource')+': '+report_resource_name
            body += '\n\n'+_(u'Best Regards')
            body += '\n'+_(u'Government Data Site')

            mail_dict = {
                #added it to send it to the maintainer of the data
                'recipient_email': config.get('email_to'),
                'recipient_name': config.get("ckanext.report.recipient_name", config.get('ckan.site_title')),
                'subject': config.get("ckanext.report.subject", report_mail_title),
                'body': body,
                'headers': {'reply-to': data_dict["email"]}
            }

            mail_dict_author = {
                #added it to send it to the author of the data
                'recipient_email': author_email_address,
                'recipient_name': config.get("ckanext.report.recipient_name", config.get('ckan.site_title')),
                'subject': config.get("ckanext.report.subject", report_mail_title),
                'body': body,
                'headers': {'reply-to': data_dict["email"]}
            }

            # Allow other plugins to modify the mail_dict
            for plugin in p.PluginImplementations(IReport):
                plugin.mail_alter(mail_dict, data_dict)
                plugin.mail_alter(mail_dict_author, data_dict)
            try:
                #sending email
                custom_mailer.mail_recipient(**mail_dict)
                if author_email_address:
                    custom_mailer.mail_recipient(**mail_dict_author)
            except (mailer.MailerException, socket.error):
                h.flash_error(_(u'Sorry, there was an error sending the email. Please try again later'))
            else:
                data_dict['success'] = True

        return data_dict, errors, error_summary
Example #26
0
    def _prepare_and_send(self, pkg_id, recipient_id, subject, prefix_template, suffix):
        """
        Sends a message by email from the logged in user to the appropriate
        contact address of the given dataset.

        The prefix template should have formatting placeholders for the following arguments:
        {sender_name}, {sender_email}, {package_title}, {data_pid}

        :param pkg_id: package id
        :type pkg_id: string
        :param recipient_id: id of the recipient, as returned by utils.get_package_contacts
        :type recipient_id: string
        :param subject: the subject of the message
        :type subject: string
        :param prefix_template: the template for the prefix to be automatically included before the user message
        :type prefix_template: unicode
        :param suffix: an additional note to be automatically included after the user message
        :type suffix: unicode
        """

        url = h.url_for(controller='package', action='read', id=pkg_id)

        if asbool(config.get('kata.contact_captcha')):
            try:
                captcha.check_recaptcha(request)
            except captcha.CaptchaError:
                h.flash_error(_(u'Bad Captcha. Please try again.'))
                redirect(url)

        if not request.params.get('accept_logging'):
            h.flash_error(_(u"Message not sent as logging wasn't permitted"))
            return redirect(url)

        if asbool(config.get('kata.disable_contact')):
            h.flash_error(_(u"Sending contact emails is prohibited for now. Please try again later or contact customer "
u"service."))
            return redirect(url)

        package = Package.get(pkg_id)
        package_title = package.title if package.title else package.name

        sender_addr = request.params.get('from_address')
        sender_name = request.params.get('from_name')
        recipient = self._get_contact_email(pkg_id, recipient_id)

        if not recipient:
            abort(404, _('Recipient not found'))

        user_msg = request.params.get('msg', '')

        ct = int(time.time())
        try:
            check = self.crypto.decrypt(base64.b64decode(request.params.get('check_this_out')))
            check = re.sub(' ', '', check)
        except TypeError:
            h.flash_error(_(u"Message not sent. Couldn't confirm human interaction (spam bot control)"))
            return redirect(url)

        hp = request.params.get('hp')

        if hp or not check or (ct - int(check) < 20) or (ct - int(check) > 1200):
            h.flash_error(_(u"Message not sent. Couldn't confirm human interaction (spam bot control)"))
            return redirect(url)

        if sender_addr and sender_name and \
                isinstance(sender_name, basestring) and len(sender_name) >= 3:
            if user_msg:
                prefix = prefix_template.format(
                    sender_name=sender_name,
                    sender_email=sender_addr,
                    package_title=package_title,
                    data_pid=utils.get_primary_data_pid_from_package(package)
                )

                log.info(u"Message {m} sent from {a} ({b}) to {r} about {c}, IP: {d}"
                         .format(m=user_msg, a=sender_name, b=sender_addr, r=recipient, c=pkg_id,
                                 d=request.environ.get('REMOTE_ADDR', 'No remote address')))

                full_msg = u"{a}{b}{c}".format(a=prefix, b=user_msg, c=suffix)
                self._send_message(subject, full_msg, recipient.get('email'), recipient.get('name'))
                h.flash_success(_(u"Message sent"))
            else:
                h.flash_error(_(u"No message"))
        else:
            h.flash_error(_(u"Message not sent. Please, provide reply address and name. Name must contain \
at least three letters."))

        return redirect(url)
Example #27
0
    def _submit(context):

        errors = {}
        error_summary = {}

        try:
            data_dict = \
                logic.clean_dict(unflatten(logic.tuplize_dict(
                    logic.parse_params(
                        toolkit.request.params))))
            context['message'] = data_dict.get('log_message', '')
            toolkit.c.form = data_dict['name']
            captcha.check_recaptcha(toolkit.request)
        except logic.NotAuthorized:
            abort(401, toolkit._('Not authorized to see this page'))
        except captcha.CaptchaError:
            #error_msg = toolkit._(u'Bad Captcha. Please try again.')
            #toolkit.h.flash_error(error_msg)
            errors['captcha'] = [u'Bad Captcha']
            error_summary['captcha'] = u'Bad Captcha. Please try again.'

        if data_dict["email"] == '':
            errors['email'] = [u'Missing Value']
            error_summary['email'] = u'Missing value'

        if data_dict["name"] == '':
            errors['name'] = [u'Missing Value']
            error_summary['name'] = u'Missing value'

        if data_dict["content"] == '':
            errors['content'] = [u'Missing Value']
            error_summary['content'] = u'Missing value'

        if len(errors) == 0:

            recipient_email = config.get("ckanext.contact.mail_to",
                                              config.get('email_to'))
            recipient_name = config.get("ckanext.contact.recipient_name",
                                             config.get('ckan.site_title'))

            if "author_email" in data_dict:
                recipient_email = data_dict["author_email"]
                recipient_name = ''

            body = '%s' % data_dict["content"]
            body += '\n\nSent by:\nName:%s\nEmail: %s\n' % (data_dict["name"],
                                                            data_dict["email"])
            mail_dict = {
                'recipient_email': recipient_email,
                'recipient_name': recipient_name,
                'subject': config.get("ckanext.contact.subject",
                                      'Contact/Question from visitor'),
                'body': body,
                'headers': {'reply-to': data_dict["email"]}
            }

            # Allow other plugins to modify the mail_dict
            for plugin in p.PluginImplementations(IContact):
                plugin.mail_alter(mail_dict, data_dict)

            try:
                mailer.mail_recipient(**mail_dict)
            except (mailer.MailerException, socket.error):
                toolkit.h.flash_error(
                    toolkit._(u'Sorry, there was an error sending the email. Please try again later'))
            else:
                data_dict['success'] = True

        return data_dict, errors, error_summary
Example #28
0
    def _send_suggestion(self, context):
        try:
            data_dict = logic.clean_dict(
                unflatten(
                    logic.tuplize_dict(logic.parse_params(request.params))))
            context['message'] = data_dict.get('log_message', '')

            c.form = data_dict['name']
            captcha.check_recaptcha(request)

            #return base.render('suggest/form.html')
        except logic.NotAuthorized:
            base.abort(401, _('Not authorized to see this page'))

        except captcha.CaptchaError:
            error_msg = _(u'Bad Captcha. Please try again.')
            h.flash_error(error_msg)
            return self.suggest_form(data_dict)

        errors = {}
        error_summary = {}

        if (data_dict["email"] == ''):

            errors['email'] = [u'Missing Value']
            error_summary['email'] = u'Missing value'

        if (data_dict["name"] == ''):

            errors['name'] = [u'Missing Value']
            error_summary['name'] = u'Missing value'

        if (data_dict["summary"] == ''):

            errors['summary'] = [u'Missing Value']
            error_summary['summary'] = u'Missing value'

        if (data_dict["description"] == ''):

            errors['description'] = [u'Missing Value']
            error_summary['description'] = u'Missing value'

        if len(errors) > 0:
            return self.suggest_form(data_dict, errors, error_summary)
        else:
            # #1799 User has managed to register whilst logged in - warn user
            # they are not re-logged in as new user.
            mail_to = config.get('contact_email_to')
            recipient_name = 'OGP Team'
            subject = 'OGPSuggest - %s' % (data_dict["summary"])

            body = 'Submitted by %s (%s)\n' % (data_dict["name"],
                                               data_dict["email"])

            if (data_dict["summary"] != ''):
                body += 'Summary: %s \n' % data_dict["summary"]

            body += 'Request: %s' % data_dict["description"]

            try:
                mailer.mail_recipient(recipient_name, mail_to, subject, body)
            except mailer.MailerException:
                raise

            return base.render('suggest/suggest_success.html')
Example #29
0
    def _prepare_and_send(self, pkg_id, recipient_id, subject, prefix_template, suffix):
        """
        Sends a message by email from the logged in user to the appropriate
        contact address of the given dataset.

        The prefix template should have formatting placeholders for the following arguments:
        {sender_name}, {sender_email}, {package_title}, {package_id}

        :param pkg_id: package id
        :type pkg_id: string
        :param recipient_id: id of the recipient, as returned by utils.get_package_contacts
        :type recipient_id: string
        :param subject: the subject of the message
        :type subject: string
        :param prefix_template: the template for the prefix to be automatically included before the user message
        :type prefix_template: unicode
        :param suffix: an additional note to be automatically included after the user message
        :type suffix: unicode
        """

        url = h.url_for(controller='package', action='read', id=pkg_id)

        if asbool(config.get('kata.contact_captcha')):
            try:
                captcha.check_recaptcha(request)
            except captcha.CaptchaError:
                h.flash_error(_(u'Bad Captcha. Please try again.'))
                redirect(url)

        if not request.params.get('accept_logging'):
            h.flash_error(_(u"Message not sent as logging wasn't permitted"))
            return redirect(url)

        if asbool(config.get('kata.disable_contact')):
            h.flash_error(_(u"Sending contact emails is prohibited for now. Please try again later or contact customer "
u"service."))
            return redirect(url)

        package = Package.get(pkg_id)
        package_title = package.title if package.title else package.name

        sender_addr = request.params.get('from_address')
        sender_name = request.params.get('from_name')
        recipient = self._get_contact_email(pkg_id, recipient_id)

        if not recipient:
            abort(404, _('Recipient not found'))

        user_msg = request.params.get('msg', '')

        if request.params.get('hp'):
            h.flash_error(_(u"Message not sent. Couldn't confirm human interaction (spam bot control)"))
            return redirect(url)

        if sender_addr and sender_name and \
                isinstance(sender_name, basestring) and len(sender_name) >= 3:
            if user_msg:
                prefix = prefix_template.format(
                    sender_name=sender_name,
                    sender_email=sender_addr,
                    package_title=package_title,
                    package_id=pkg_id
                    # above line was: metadata_pid=utils.get_primary_data_pid_from_package(package)
                )

                log.info(u"Message {m} sent from {a} ({b}) to {r} about {c}, IP: {d}"
                         .format(m=user_msg, a=sender_name, b=sender_addr, r=recipient, c=pkg_id,
                                 d=request.environ.get('REMOTE_ADDR', 'No remote address')))

                full_msg = u"{a}{b}{c}".format(a=prefix, b=user_msg, c=suffix)
                self._send_message(subject, full_msg, recipient.get('email'), recipient.get('name'))
                h.flash_success(_(u"Message sent"))
            else:
                h.flash_error(_(u"No message"))
        else:
            h.flash_error(_(u"Message not sent. Please, provide reply address and name. Name must contain \
at least three letters."))

        return redirect(url)
Example #30
0
    def _submit():
        try:
            data_dict = logic.clean_dict(
                unflatten(
                    logic.tuplize_dict(logic.parse_params(request.params))))
            c.form = data_dict['name']
            captcha.check_recaptcha(request)
        except logic.NotAuthorized:
            base.abort(401, _('Not authorized to see this page'))
        except captcha.CaptchaError:
            error_msg = _(u'Bad Captcha. Please try again.')
            h.flash_error(error_msg)

        errors = {}
        error_summary = {}

        if data_dict["email"] == '':
            errors['email'] = [u'Missing Value']
            error_summary['email'] = u'Missing value'

        if data_dict["name"] == '':
            errors['name'] = [u'Missing Value']
            error_summary['name'] = u'Missing value'

        if data_dict["content"] == '':
            errors['content'] = [u'Missing Value']
            error_summary['content'] = u'Missing value'

        if len(errors) == 0:
            # TODO param:to fallback
            dataset = data_dict.get('dataset', None)
            to = config.get('ckanext.montreal.contact_mail_to')
            subject = u"E-mail from contact form: {category}".format(
                category=data_dict['category'])
            file = data_dict.get('attachment', None)
            content = """Sent by:{newline}
                             Name: {name}{newline}
                             Email: {email}{newline}""".format(
                name=data_dict['name'],
                email=data_dict['email'],
                newline='</br>')

            if dataset:
                content += "Affected dataset/resource: {dataset}{newline}".format(
                    dataset=dataset, newline='</br>')

            content += "{newline}Message:{newline}{content}".format(
                newline='</br>', content=data_dict['content'])

            try:
                emailer.send_email(content=content,
                                   to=to,
                                   subject=subject,
                                   file=file)
            except Exception as e:
                log.error(e)
                h.flash_error(
                    _(u'Sorry, there was an error sending the email. Please try again later'
                      ))
            else:
                data_dict['success'] = True

        return data_dict, errors, error_summary
    def _send_contact(self, context):
        try:
            data_dict = logic.clean_dict(unflatten(
                logic.tuplize_dict(logic.parse_params(request.params))))
            context['message'] = data_dict.get('log_message', '')

            c.form = data_dict['name']
            captcha.check_recaptcha(request)
            #return base.render('suggest/form.html')
        except logic.NotAuthorized:
            base.abort(401, _('Vous n\'êtes pas autorisé à accéder à cette page'))
        except captcha.CaptchaError:
            error_msg = _(u'Mauvais code captcha. Veuillez réessayer.')
            h.flash_error(error_msg)
            return self.contact_form(data_dict)

        errors = {}
        error_summary = {}

        if (data_dict["email"] == ''):

            errors['email'] = [u'Valeur manquante']
            error_summary['email'] =  u'Valeur manquante'

        if (data_dict["name"] == ''):

            errors['name'] = [u'Valeur manquante']
            error_summary['name'] =  u'Valeur manquante'


        if (data_dict["content"] == ''):

            errors['content'] = [u'Valeur manquante']
            error_summary['content'] =  u'Valeur manquante'


        if len(errors) > 0:
            return self.suggest_form(data_dict, errors, error_summary)
        else:

            if data_dict['organization'] == 'all':
                mail_to = config.get('email_to')
            else:
                mail_to = logic.get_action('organization_show')( {},
                                    {'id': data_dict['organization']})['email']
                                    
            recipient_name = 'Données Québec'.decode('utf8')
            subject = 'Question/commentaire d\'un visiteur'.decode('utf8')

            body = 'Soumis par %s (%s)\n'.decode('utf8') % (data_dict["name"], data_dict["email"])

            body += 'Demande: %s'.decode('utf8') % data_dict["content"]

            try:
                mailer.mail_recipient(recipient_name, mail_to,
                        subject, body)
            except mailer.MailerException:
                raise


            return base.render('contact/success.html')
    def _send_suggestion(self, context):
        try:
            data_dict = logic.clean_dict(unflatten(
                logic.tuplize_dict(logic.parse_params(request.params))))
            context['message'] = data_dict.get('log_message', '')

            c.form = data_dict['name']
            captcha.check_recaptcha(request)

            #return base.render('suggest/form.html')
        except logic.NotAuthorized:
            base.abort(401, _('Vous n\'êtes pas autorisé à accéder à cette page'))

        except captcha.CaptchaError:
            error_msg = _(u'Mauvais code captcha. Essayez de nouveau')
            h.flash_error(error_msg)
            return self.suggest_form(data_dict)


        errors = {}
        error_summary = {}

        if (data_dict["email"] == ''):

            errors['email'] = [u'Valeur manquante']
            error_summary['email'] =  u'Valeur manquante'

        if (data_dict["name"] == ''):

            errors['name'] = [u'Valeur manquante']
            error_summary['name'] =  u'Valeur manquante'


        if (data_dict["suggestion"] == ''):

            errors['suggestion'] = [u'Valeur manquante']
            error_summary['suggestion'] =  u'Valeur manquante'


        if len(errors) > 0:
            return self.suggest_form(data_dict, errors, error_summary)
        else:
            # #1799 User has managed to register whilst logged in - warn user
            # they are not re-logged in as new user.

            if data_dict['organization'] == 'all':
                mail_to = config.get('email_to')
            else:
                mail_to = logic.get_action('organization_show')( {},
                                    {'id': data_dict['organization']})['email']

            recipient_name = 'Données Quebec'.decode('utf8')
            subject = 'Suggestion de jeu de données'.decode('utf8')

            body = 'Soumis par %s (%s)\n' % (data_dict["name"], data_dict["email"])

            if (data_dict["category"] != ''):
                body += 'Catégorie de données: %s'.decode('utf8') % data_dict["category"]

            body += 'Nature de la demande: %s'.decode('utf8') % data_dict["suggestion"]

            if (data_dict["usage"] != ''):
                body += 'Utilisation visée: %s'.decode('utf8') % data_dict["usage"]

            try:
                mailer.mail_recipient(recipient_name, mail_to,
                        subject, body)
            except mailer.MailerException:
                raise


            return base.render('suggest/suggest_success.html')
def passwordless_request_reset():
    '''
    Request a new user token
    '''
    log.debug(" ** REQUEST_RESET")

    before_request()

    context = {
        'model': model,
        'session': model.Session,
        'user': g.user,
        'auth_user_obj': toolkit.c.userobj
    }

    log.debug("request_reset got {1} request from {0}".format(
        request.remote_addr, request.method))

    try:
        check_access('request_reset', context)
    except NotAuthorized:
        abort(401, _('Unauthorized to request a token.'))

    if toolkit.c.user or g.user:
        # Don't offer the reset form if already logged in
        return render('user/logout_first.html')

    if request.method == 'POST':

        # Get the params that were posted
        form_params = toolkit.request.form
        params = {}
        for k, v in form_params.items():
            if v:
                params[k] = v

        # get the url params too
        for k, v in toolkit.request.args.items():
            if v:
                params[k] = v

        log.debug('request_rest: params = ' + str(params))

        email = params.get('email')
        came_from = params.get('came_from')

        # prepare extra vars
        extra_vars = {'email': email}
        if came_from:
            extra_vars['came_from'] = came_from

        if params:
            # error if no mail
            if not util.check_email(email):
                error_msg = _(u'Please introduce a valid mail.')
                h.flash_error(error_msg)
                return render('user/request_reset.html', extra_vars=extra_vars)

            # Check captcha
            try:
                captcha.check_recaptcha(request)
            except captcha.CaptchaError:
                error_msg = _(u'Bad Captcha. Please try again.')
                h.flash_error(error_msg)
                return render('user/request_reset.html', extra_vars=extra_vars)

            # call action
            try:
                result = toolkit.get_action('passwordless_perform_reset')(
                    context, {
                        'email': email
                    })
                log.debug(result)
                h.flash_success(
                    _('Please check your inbox for an access token.'))

            except toolkit.ValidationError as e:
                error_msg = _(u'Reset failed {0}. Please try again.'.format(
                    str(e)))
                h.flash_error(error_msg)
                return render('user/request_reset.html', extra_vars=extra_vars)
            except toolkit.NotAuthorized:
                return render('user/logout_first.html')
            except logic.NotFound as e:
                error_msg = _(
                    u'Reset failed, problem retrieving the user associated to the email {0}.'
                    .format(e))
                h.flash_error(error_msg)
                return render('user/request_reset.html', extra_vars=extra_vars)
            except mailer.MailerException as e:
                h.flash_error(_('Could not send token link: %s') % str(e))

        log.debug("controller redirecting: user.login, email =  " +
                  str(email) + ", came_from = " + str(came_from))
        return toolkit.h.redirect_to('user.login',
                                     email=email,
                                     came_from=came_from)

    return render('user/request_reset.html')