Example #1
0
    def logged_in(self):
        # we need to set the language via a redirect
        lang = session.pop("lang", None)
        session.save()
        came_from = request.params.get("came_from", "")

        # we need to set the language explicitly here or the flash
        # messages will not be translated.
        i18n.set_lang(lang)

        if c.user:
            context = None
            data_dict = {"id": c.user}

            user_dict = get_action("user_show")(context, data_dict)

            h.flash_success(_("%s is now logged in") % user_dict["display_name"])
            if came_from:
                return h.redirect_to(str(came_from))
            return self.me()
        else:
            err = _("Login failed. Bad username or password.")
            if g.openid_enabled:
                err += _(" (Or if using OpenID, it hasn't been associated " "with a user account.)")
            if h.asbool(config.get("ckan.legacy_templates", "false")):
                h.flash_error(err)
                h.redirect_to(locale=lang, controller="user", action="login", came_from=came_from)
            else:
                return self.login(error=err)
    def logged_in(self):
        # redirect if needed
        came_from = request.params.get('came_from', '')

        if c.user:
            context = None
            data_dict = {'id': c.user}

            user_dict = get_action('user_show')(context, data_dict)

            user_ref = c.userobj.get_reference_preferred_for_uri()

            if h.url_is_local(came_from) and came_from != '/':
                return h.redirect_to(str(came_from))

            h.redirect_to(locale=None, controller='user', action='dashboard_datasets',
                      id=user_ref)
        else:
            err = _('Login failed. Wrong email or password.')
            if h.asbool(config.get('ckan.legacy_templates', 'false')):
                h.flash_error(err)
                h.redirect_to(controller='user',
                              action='login', came_from=came_from)
            else:
                return self.login(error=err)
Example #3
0
    def logged_in(self):
        came_from = request.params.get('came_from', '')

        if c.user:
            context = None
            data_dict = {'id': c.user, 'link_wotkit': True}
            try:
                user_dict = get_action('user_show')(context, data_dict)
            except logic.NotAuthorized as e:
                return self.login(error=str(e))

            h.flash_success(_("%s is now logged in") %
                            user_dict['display_name'])
            if came_from and "logged_in" not in came_from:
                """Mark: HACK redirect to ignore the base URL /data. 
                This used to use url_for, but doing so always appends the /data path which we won't want
                Thus had to change it to redirect_to
                """
                return routes.redirect_to(str(came_from))
            return self.me()
        else:
            err = _('Login failed. Bad username or password.')
            if g.openid_enabled:
                err += _(' (Or if using OpenID, it hasn\'t been associated '
                         'with a user account.)')
            if h.asbool(config.get('ckan.legacy_templates', 'false')):
                h.flash_error(err)
                h.redirect_to(locale=lang, controller='user',
                              action='login', came_from=came_from)
            else:
                return self.login(error=err)
Example #4
0
    def read(self, id=None):
        context = {
            'model': model,
            'session': model.Session,
            'user': c.user or c.author,
            'for_view': True
        }
        data_dict = {'id': id, 'user_obj': c.userobj}
        try:
            check_access('user_show', context, data_dict)
        except NotAuthorized:
            abort(401, _('Not authorized to see this page'))

        context['with_related'] = True

        self._setup_template_variables(context, data_dict)

        # The legacy templates have the user's activity stream on the user
        # profile page, new templates do not.
        if h.asbool(config.get('ckan.legacy_templates', False)):
            c.user_activity_stream = get_action('user_activity_list_html')(
                context, {
                    'id': c.user_dict['id']
                })

        return render('user/read.html')
Example #5
0
    def logged_in(self):
        # redirect if needed
        came_from = request.params.get('came_from', '')
        if h.url_is_local(came_from):
            return h.redirect_to(str(came_from))

        if c.user:
            context = None
            data_dict = {'id': c.user}

            user_dict = get_action('user_show')(context, data_dict)

            return self.me()
        else:
            err = _('Login failed. Bad username or password.')
            if g.openid_enabled:
                err += _(' (Or if using OpenID, it hasn\'t been associated '
                         'with a user account.)')
            if h.asbool(config.get('ckan.legacy_templates', 'false')):
                h.flash_error(err)
                h.redirect_to(controller='user',
                              action='login',
                              came_from=came_from)
            else:
                return self.login(error=err)
Example #6
0
    def edit(self, id=None, data=None, errors=None, error_summary=None):
        context = {'save': 'save' in request.params,
                   'schema': self._edit_form_to_db_schema(),
                   'model': model, 'session': model.Session,
                   'user': c.user, 'auth_user_obj': c.userobj
                   }
        if id is None:
            if c.userobj:
                id = c.userobj.id
            else:
                abort(400, _('No user specified'))
        data_dict = {'id': id}

        try:
            check_access('user_update', context, data_dict)
        except NotAuthorized:
            abort(401, _('Unauthorized to edit a user.'))

        if (context['save']) and not data:
            return self._save_edit(id, context)

        try:
            old_data = get_action('user_show')(context, data_dict)

            schema = self._db_to_edit_form_schema()
            if schema:
                old_data, errors = \
                    dictization_functions.validate(old_data, schema, context)

            c.display_name = old_data.get('display_name')
            c.user_name = old_data.get('name')

            data = data or old_data

        except NotAuthorized:
            abort(401, _('Unauthorized to edit user %s') % '')
        except NotFound:
            abort(404, _('User not found'))

        user_obj = context.get('user_obj')

        if not (authz.is_sysadmin(c.user)
                or c.user == user_obj.name):
            abort(401, _('User %s not authorized to edit %s') %
                  (str(c.user), id))

        errors = errors or {}
        vars = {'data': data, 'errors': errors, 'error_summary': error_summary}

        self._setup_template_variables({'model': model,
                                        'session': model.Session,
                                        'user': c.user or c.author},
                                       data_dict)

        c.is_myself = True
        c.show_email_notifications = h.asbool(
                config.get('ckan.activity_streams_email_notifications'))
        c.form = render(self.edit_user_form, extra_vars=vars)

        return render('user/edit.html')
Example #7
0
    def logged_in(self):
        # we need to set the language via a redirect
        lang = session.pop('lang', None)
        session.save()
        came_from = request.params.get('came_from', '')

        # we need to set the language explicitly here or the flash
        # messages will not be translated.
        i18n.set_lang(lang)

        if c.user:
            context = None
            data_dict = {'id': c.user}

            user_dict = get_action('user_show')(context, data_dict)

            h.flash_success(_("%s is now logged in") %
                            user_dict['display_name'])
            if came_from:
                return h.redirect_to(str(came_from))
            return self.me()
        else:
            err = _('Login failed. Bad username or password.')
            if g.openid_enabled:
                err += _(' (Or if using OpenID, it hasn\'t been associated '
                         'with a user account.)')
            if h.asbool(config.get('ckan.legacy_templates', 'false')):
                h.flash_error(err)
                h.redirect_to(locale=lang, controller='user',
                              action='login', came_from=came_from)
            else:
                return self.login(error=err)
Example #8
0
    def edit(self, id=None, data=None, errors=None, error_summary=None):
        context = {'save': 'save' in request.params,
                   'schema': self._edit_form_to_db_schema(),
                   'model': model, 'session': model.Session,
                   'user': c.user, 'auth_user_obj': c.userobj
                   }
        if id is None:
            if c.userobj:
                id = c.userobj.id
            else:
                abort(400, _('No user specified'))
        data_dict = {'id': id}

        try:
            check_access('user_update', context, data_dict)
        except NotAuthorized:
            abort(401, _('Unauthorized to edit a user.'))

        if (context['save']) and not data:
            return self._save_edit(id, context)

        try:
            old_data = get_action('user_show')(context, data_dict)

            schema = self._db_to_edit_form_schema()
            if schema:
                old_data, errors = \
                    dictization_functions.validate(old_data, schema, context)

            c.display_name = old_data.get('display_name')
            c.user_name = old_data.get('name')

            data = data or old_data

        except NotAuthorized:
            abort(401, _('Unauthorized to edit user %s') % '')
        except NotFound:
            abort(404, _('User not found'))

        user_obj = context.get('user_obj')

        if not (authz.is_sysadmin(c.user)
                or c.user == user_obj.name):
            abort(401, _('User %s not authorized to edit %s') %
                  (str(c.user), id))

        errors = errors or {}
        vars = {'data': data, 'errors': errors, 'error_summary': error_summary}

        self._setup_template_variables({'model': model,
                                        'session': model.Session,
                                        'user': c.user or c.author},
                                       data_dict)

        c.is_myself = True
        c.show_email_notifications = h.asbool(
                config.get('ckan.activity_streams_email_notifications'))
        c.form = render(self.edit_user_form, extra_vars=vars)

        return render('user/edit.html')
Example #9
0
    def logged_in(self):
        # redirect if needed
        came_from = request.params.get('came_from', '')
        #FIXME uggly fix
        # did this change for /euodp path, the uggly fix is still to be fixed
        if '/user/logged_in' not in came_from and h.url_is_local(came_from):
            return h.redirect_to(str(came_from))
        if c.user:
            context = None
            data_dict = {'id': c.user}

            user_dict = get_action('user_show')(context, data_dict)

            h.flash_success(
                _("%s is now logged in") % user_dict['display_name'])
            return self.me()
        else:
            err = _('Login failed. Bad username or password.')
            if g.openid_enabled:
                err += _(' (Or if using OpenID, it hasn\'t been associated '
                         'with a user account.)')
            if h.asbool(config.get('ckan.legacy_templates', 'false')):
                log.error('[DB] logged_in not c.user' + came_from)
                h.flash_error(err)
                h.redirect_to(controller='user',
                              action='login',
                              came_from=came_from)
            else:
                return self.login(error=err)
Example #10
0
    def logged_in(self):
        # redirect if needed
        came_from = request.params.get('came_from', '')
        if self._sane_came_from(came_from):
            return h.redirect_to(str(came_from))

        if c.user:
            context = None
            data_dict = {'id': c.user}

            user_dict = get_action('user_show')(context, data_dict)

            h.flash_success(_("%s is now logged in") %
                            user_dict['display_name'])
            # LAit customization
            return render('_home.html')
        else:
            err = _('Login failed. Bad username or password.')
            if g.openid_enabled:
                err += _(' (Or if using OpenID, it hasn\'t been associated '
                         'with a user account.)')
            if h.asbool(config.get('ckan.legacy_templates', 'false')):
                h.flash_error(err)
                h.redirect_to(controller='user',
                              action='login', came_from=came_from)
            else:
                return self.login(error=err)
Example #11
0
File: user.py Project: tbalaz/dghr
    def logged_in(self):
        # redirect if needed
        came_from = request.params.get('came_from', '')
        if self._sane_came_from(came_from):
            return h.redirect_to(str(came_from))

        if c.user:
            context = None
            data_dict = {'id': c.user}

            user_dict = get_action('user_show')(context, data_dict)

            h.flash_success(
                _("%s is now logged in") % user_dict['display_name'])
            return self.me()
        else:
            err = _('Login failed. Bad username or password.')
            if g.openid_enabled:
                err += _(' (Or if using OpenID, it hasn\'t been associated '
                         'with a user account.)')
            if h.asbool(config.get('ckan.legacy_templates', 'false')):
                h.flash_error(err)
                h.redirect_to(
                    controller='user', action='login', came_from=came_from)
            else:
                return self.login(error=err)
Example #12
0
    def read(self, id=None):
        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author, 'auth_user_obj': c.userobj,
                   'for_view': True}
        data_dict = {'id': id,
                     'user_obj': c.userobj}

        context['with_related'] = True

        self._setup_template_variables(context, data_dict)

        c.user_dict['datasets'] = []

        # find datasets for requested id

        userobj = model.User.get(c.user_dict['id'])

        user_dataset_q = (model.Session.query(model.Package)
                          .join(model.PackageRole)
                          .filter_by(user=userobj, role=model.Role.ADMIN)
                          .order_by(None))

        # if signed in, find datasets for organizations where user is admin
        if c.userobj and c.userobj.name == id:
                orgs = h.organizations_available('admin')
                org_ids = []
                for org in orgs:
                    org_ids.append(org['id'])
                if len(org_ids):
                    org_dataset_q = (model.Session.query(model.Package)
                                     .join(model.PackageRole)
                                     .filter_by(role=model.Role.ADMIN)
                                     .filter(model.Package.owner_org.in_(org_ids))
                                     .join(model.User)
                                     .filter(model.User.name != 'harvest')
                                     .filter(model.User.name != 'default')
                                     .order_by(None))

                    dataset_q = user_dataset_q.union(org_dataset_q)
                else:
                    dataset_q = user_dataset_q
        else:
            dataset_q = user_dataset_q

        # get datasets, access rights are checked during package_show
        for dataset in dataset_q:
            try:
                dataset_dict = get_action('package_show')(
                    context, {'id': dataset.id})
            except NotAuthorized:
                continue
            c.user_dict['datasets'].append(dataset_dict)

        # The legacy templates have the user's activity stream on the user
        # profile page, new templates do not.
        if h.asbool(config.get('ckan.legacy_templates', False)):
            c.user_activity_stream = get_action('user_activity_list_html')(
                context, {'id': c.user_dict['id']})

        return render('user/read.html')
def _create_or_update_pdf_thumbnail(context,pkg_dict_or_resource):
  pdf_url=pkg_dict_or_resource['url']
  filename, file_extension = os.path.splitext(pdf_url)

  if ".pdf" != file_extension.lower() or pkg_dict_or_resource['name'] == "PDF Thumbnail":
   return

  enabled_pdf_preview = h.asbool(config.get("ckan.odm_nav_concept.generate_pdf_preview", False))
  if enabled_pdf_preview:

    try:

      pdf=Image(filename=pdf_url+"[0]")
      pdf.format='png'
      pdf.resize(135,201)
      temp_dir = os.path.abspath(tempfile.mkdtemp())
      temp_img=temp_dir+'/'+pkg_dict_or_resource['id']+'.png'
      pdf.save(filename=temp_img)
      params = {'package_id':pkg_dict_or_resource['package_id'],'upload':temp_img, 'url':'N/A','format':'PNG','mimetype_inner':'image/png','name':'PDF Thumbnail'}
      ckan_url = config.get("ckan.site_url", "")
      userobj = context['auth_user_obj']
      ckan_auth = userobj.apikey

      if context['resource'].name == "PDF Thumbnail":
        resource_id=context['resource'].id
        params['id']=resource_id
        requests.post(ckan_url + 'api/3/action/resource_update',verify=False,data=params,headers={"X-CKAN-API-Key": ckan_auth},files=[('upload', file(params["upload"]))])
      else:
        requests.post(ckan_url + 'api/3/action/resource_create',verify=False,data=params,headers={"X-CKAN-API-Key": ckan_auth},files=[('upload', file(params["upload"]))])

      if os.path.exists(temp_img):
        os.remove(temp_img)

    except Exception, e:
      log.error("Could not generate PDF thumbnail", e)
Example #14
0
    def read(self, id=None):
        context = {
            'model': model,
            'session': model.Session,
            'user': c.user or c.author,
            'auth_user_obj': c.userobj,
            'for_view': True
        }
        data_dict = {
            'id': id,
            'user_obj': c.userobj,
            'include_datasets': True,
            'include_num_followers': True
        }

        context['with_related'] = True

        self._setup_template_variables(context, data_dict)

        # The legacy templates have the user's activity stream on the user
        # profile page, new templates do not.
        if h.asbool(config.get('ckan.legacy_templates', False)):
            c.user_activity_stream = get_action('user_activity_list_html')(
                context, {
                    'id': c.user_dict['id']
                })

        return render('user/read.html')
Example #15
0
    def edit(self, id=None, data=None, errors=None, error_summary=None):
        context = {
            "save": "save" in request.params,
            "schema": self._edit_form_to_db_schema(),
            "model": model,
            "session": model.Session,
            "user": c.user,
            "auth_user_obj": c.userobj,
        }
        if id is None:
            if c.userobj:
                id = c.userobj.id
            else:
                abort(400, _("No user specified"))
        data_dict = {"id": id}

        try:
            check_access("user_update", context, data_dict)
        except NotAuthorized:
            abort(401, _("Unauthorized to edit a user."))

        if (context["save"]) and not data:
            return self._save_edit(id, context)

        try:
            old_data = get_action("user_show")(context, data_dict)

            schema = self._db_to_edit_form_schema()
            if schema:
                old_data, errors = dictization_functions.validate(old_data, schema, context)

            c.display_name = old_data.get("display_name")
            c.user_name = old_data.get("name")

            data = data or old_data

        except NotAuthorized:
            abort(401, _("Unauthorized to edit user %s") % "")
        except NotFound:
            abort(404, _("User not found"))

        user_obj = context.get("user_obj")

        if not (authz.is_sysadmin(c.user) or c.user == user_obj.name):
            abort(401, _("User %s not authorized to edit %s") % (str(c.user), id))

        errors = errors or {}
        vars = {"data": data, "errors": errors, "error_summary": error_summary}

        self._setup_template_variables(
            {"model": model, "session": model.Session, "user": c.user or c.author}, data_dict
        )

        c.is_myself = True
        c.show_email_notifications = h.asbool(config.get("ckan.activity_streams_email_notifications"))
        c.form = render(self.edit_user_form, extra_vars=vars)

        return render("user/edit.html")
Example #16
0
    def read_contact_info(self, id=None):
        context = {
            'model': model,
            'session': model.Session,
            'user': c.user or c.author,
            'auth_user_obj': c.userobj,
            'for_view': True,
            'return_minimal': True,
            'save': 'save' in request.params
        }
        data_dict = {'id': id, 'user_obj': c.userobj}

        context['with_related'] = True

        self._setup_user_template_variables(context, data_dict)

        if context['save']:
            request.POST.pop('save')
            data = ecportal_logic.transform_to_data_dict(request.POST)

            credential_validator = Validator({
                'contact_mailbox': [email]
                #'contact_phone_number': [IntPhoneNumberRule]
            })
            errors = {}
            succeed = credential_validator.validate(data, results=errors)

            if succeed is True:
                contact_info = Package_contact_info.get_by_user(c.userobj.id)
                if not contact_info:
                    contact_info = Package_contact_info(c.userobj.id)

                contact_info.from_dict(data)
                contact_info.save()
                h.flash_success(_('ecodp.user.save.success'))
            elif errors:
                h.flash_error(_('ecodp.user.save.error'))

            c.user_dict.update(data)

            c.errors = errors

        # The legacy templates have the user's activity stream on the user
        # profile page, new templates do not.
        if h.asbool(config.get('ckan.legacy_templates', False)):
            c.user_activity_stream = get_action('user_activity_list_html')(
                context, {
                    'id': c.user_dict['id']
                })

        #vars = {'data': {}, 'errors': {}, 'error_summary': {}}
        #c.form = base.render('user/edit_contact_info_form.html', extra_vars=vars)
        return base.render('user/read_contact_info.html')
  def after_create(self, context, pkg_dict_or_resource):

    dataset_type = context['package'].type if 'package' in context else pkg_dict_or_resource['type']
    if dataset_type == 'laws_record':
      log.debug('after_create: %s', pkg_dict_or_resource['name'])

      review_system = h.asbool(config.get("ckanext.issues.review_system", False))
      if review_system:
        if 'type' in pkg_dict_or_resource:
          odm_laws_helper.create_default_issue_laws_record(pkg_dict_or_resource)

        if 'url_type' in pkg_dict_or_resource:
          _create_or_update_pdf_thumbnail(context,pkg_dict_or_resource)
Example #18
0
    def read(self, id):
        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author, 'for_view': True}

        data_dict = {'id': id}
        try:
            c.tag = logic.get_action('tag_show')(context, data_dict)
        except logic.NotFound:
            base.abort(404, _('Tag not found'))

        if h.asbool(config.get('ckan.legacy_templates', False)):
            return base.render('tag/read.html')
        else:
            h.redirect_to(controller='package', action='search', tags=c.tag.get('name'))
Example #19
0
def activity_create(context, activity_dict, ignore_auth=False):
    '''Create a new activity stream activity.

    You must be a sysadmin to create new activities.

    :param user_id: the name or id of the user who carried out the activity,
        e.g. ``'seanh'``
    :type user_id: string
    :param object_id: the name or id of the object of the activity, e.g.
        ``'my_dataset'``
    :param activity_type: the type of the activity, this must be an activity
        type that CKAN knows how to render, e.g. ``'new package'``,
        ``'changed user'``, ``'deleted group'`` etc. (for a full list see
        ``activity_renderers`` in ``ckan/logic/action/get.py``
    :type activity_type: string
    :param data: any additional data about the activity
    :type data: dictionary

    :returns: the newly created activity
    :rtype: dictionary

    '''
    if not h.asbool(config.get('ckan.activity_streams_enabled', 'true')):
        return

    model = context['model']

    # Any revision_id that the caller attempts to pass in the activity_dict is
    # ignored and overwritten here.
    if getattr(model.Session, 'revision', None):
        activity_dict['revision_id'] = model.Session.revision.id
    else:
        activity_dict['revision_id'] = None

    if not ignore_auth:
        _check_access('activity_create', context, activity_dict)

    schema = context.get('schema') or ckan.logic.schema.default_create_activity_schema()
    data, errors = _validate(activity_dict, schema, context)
    if errors:
        raise ValidationError(errors)

    activity = model_save.activity_dict_save(activity_dict, context)

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

    log.debug("Created '%s' activity" % activity.activity_type)
    return model_dictize.activity_dictize(activity, context)
Example #20
0
File: tag.py Project: code4sac/ckan
    def read(self, id):
        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author, 'for_view': True}

        data_dict = {'id': id}
        try:
            c.tag = logic.get_action('tag_show')(context, data_dict)
        except logic.NotFound:
            base.abort(404, _('Tag not found'))

        if h.asbool(config.get('ckan.legacy_templates', False)):
            return base.render('tag/read.html')
        else:
            h.redirect_to(controller='package', action='search',
                          tags=c.tag.get('name'))
Example #21
0
    def read(self, id=None):
        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author, 'for_view': True}
        data_dict = {'id': id,
                     'user_obj': c.userobj}

        context['with_related'] = True

        self._setup_template_variables(context, data_dict)

        # The legacy templates have the user's activity stream on the user
        # profile page, new templates do not.
        if h.asbool(config.get('ckan.legacy_templates', False)):
            c.user_activity_stream = get_action('user_activity_list_html')(
                context, {'id': c.user_dict['id']})

        return render('user/read.html')
Example #22
0
    def read(self, id=None):
        context = {"model": model, "session": model.Session, "user": c.user or c.author, "for_view": True}
        data_dict = {"id": id, "user_obj": c.userobj}
        try:
            check_access("user_show", context, data_dict)
        except NotAuthorized:
            abort(401, _("Not authorized to see this page"))

        context["with_related"] = True

        self._setup_template_variables(context, data_dict)

        # The legacy templates have the user's activity stream on the user
        # profile page, new templates do not.
        if h.asbool(config.get("ckan.legacy_templates", False)):
            c.user_activity_stream = get_action("user_activity_list_html")(context, {"id": c.user_dict["id"]})

        return render("user/read.html")
Example #23
0
File: tag.py Project: govro/ckan
    def read(self, id):
        context = {
            "model": model,
            "session": model.Session,
            "user": c.user,
            "auth_user_obj": c.userobj,
            "for_view": True,
        }

        data_dict = {"id": id}
        try:
            c.tag = logic.get_action("tag_show")(context, data_dict)
        except logic.NotFound:
            base.abort(404, _("Tag not found"))

        if h.asbool(config.get("ckan.legacy_templates", False)):
            return base.render("tag/read.html")
        else:
            h.redirect_to(controller="package", action="search", tags=c.tag.get("name"))
Example #24
0
    def read(self, id=None):
        context = {
            "model": model,
            "session": model.Session,
            "user": c.user or c.author,
            "auth_user_obj": c.userobj,
            "for_view": True,
        }
        data_dict = {"id": id, "user_obj": c.userobj, "include_datasets": True, "include_num_followers": True}

        context["with_related"] = True

        self._setup_template_variables(context, data_dict)

        # The legacy templates have the user's activity stream on the user
        # profile page, new templates do not.
        if h.asbool(config.get("ckan.legacy_templates", False)):
            c.user_activity_stream = get_action("user_activity_list_html")(context, {"id": c.user_dict["id"]})

        return render("user/read.html")
Example #25
0
    def logged_in(self):
        came_from = http_request.params.get('came_from', '')
        if h.url_is_local(came_from):
            return h.redirect_to(str(came_from))

        if c.user:
            context = None
            data_dict = {'id': c.user}

            user_dict = get_action('user_show')(context, data_dict)
            user_ref = c.userobj.get_reference_preferred_for_uri()
            return h.redirect_to('/')
        else:
            err = 'Login failed. Bad username or password.'
            if  h.asbool(config.get('ckan.legacy_templates', 'false')):
                h.flash_error(err)
                h.redirect_to(controller='user',
                              action='login', came_from=came_from)
            else:
                return self.login(error=err)
Example #26
0
    def logged_in(self):
        # redirect if needed
        came_from = request.params.get("came_from", "")
        if h.url_is_local(came_from):
            return h.redirect_to(str(came_from))

        if c.user:
            context = None
            data_dict = {"id": c.user}

            user_dict = get_action("user_show")(context, data_dict)

            return self.me()
        else:
            err = _("Login failed. Bad username or password.")
            if h.asbool(config.get("ckan.legacy_templates", "false")):
                h.flash_error(err)
                h.redirect_to(controller="user", action="login", came_from=came_from)
            else:
                return self.login(error=err)
Example #27
0
File: user.py Project: abetam/ckan
    def logged_in(self):
        # redirect if needed
        came_from = request.params.get('came_from', '')
        if h.url_is_local(came_from):
            return h.redirect_to(str(came_from))

        if c.user:
            context = None
            data_dict = {'id': c.user}

            user_dict = get_action('user_show')(context, data_dict)

            return self.me()
        else:
            err = _('Login failed. Bad username or password.')
            if h.asbool(config.get('ckan.legacy_templates', 'false')):
                h.flash_error(err)
                h.redirect_to(controller='user',
                              action='login', came_from=came_from)
            else:
                return self.login(error=err)
Example #28
0
    def logged_in(self):
        # redirect if needed
        came_from = request.params.get('came_from', '')
        if self._sane_came_from(came_from):
            return h.redirect_to(str(came_from))

        if c.user:
            context = None
            data_dict = {'id': c.user}

            user_dict = get_action('user_show')(context, data_dict)

            if 'created' in user_dict:
                time_passed = datetime.datetime.now(
                ) - dateutil.parser.parse(user_dict['created'])
            else:
                time_passed = None
            if not user_dict['activity'] and time_passed and time_passed.days < 3:
                #/dataset/new
                contribute_url = h.url_for(controller='package', action='new')
                # message = ''' Now that you've registered an account , you can <a href="%s">start adding datasets</a>.
                #    If you want to associate this dataset with an organization, either click on "My Organizations" below
                #    to create a new organization or ask the admin of an existing organization to add you as a member.''' % contribute_url
                #h.flash_success(_(message), True)
                return h.redirect_to(controller='user', action='dashboard_organizations')
            else:
                h.flash_success(_("%s is now logged in") %
                                user_dict['display_name'])
                return self.me()
        else:
            err = _('Login failed. Bad username or password.')
            if g.openid_enabled:
                err += _(' (Or if using OpenID, it hasn\'t been associated '
                         'with a user account.)')
            if h.asbool(config.get('ckan.legacy_templates', 'false')):
                h.flash_error(err)
                h.redirect_to(controller='user',
                              action='login', came_from=came_from)
            else:
                return self.login(error=err)
Example #29
0
 def _syndicate(self, dataset):
     return (not dataset.private and
             asbool(dataset.extras.get(get_syndicate_flag(), 'false')))
Example #30
0
        if not (new_authz.is_sysadmin(c.user)
                or c.user == user_obj.name):
            abort(401, _('User %s not authorized to edit %s') %
                  (str(c.user), id))

        errors = errors or {}
        vars = {'data': data, 'errors': errors, 'error_summary': error_summary}

        self._setup_template_variables({'model': model,
                                        'session': model.Session,
                                        'user': c.user or c.author},
                                       data_dict)

        c.is_myself = True
        c.show_email_notifications = h.asbool(
            config.get('ckan.activity_streams_email_notifications'))
        c.form = render(self.edit_user_form, extra_vars=vars)

        return render('user/edit.html')

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

            # MOAN: Do I really have to do this here?
            if 'activity_streams_email_notifications' not in data_dict:
                data_dict['activity_streams_email_notifications'] = False
    def edit(self, id=None, data=None, errors=None, error_summary=None):
        context = {'save': 'save' in request.params,
                   'schema': self._edit_form_to_db_schema(),
                   'model': model, 'session': model.Session,
                   'user': c.user, 'auth_user_obj': c.userobj
                   }
        if id is None:
            if c.userobj:
                id = c.userobj.id
            else:
                abort(400, _('No user specified'))
        data_dict = {'id': id}

        try:
            check_access('user_update', context, data_dict)
        except NotAuthorized:
            abort(401, _('Unauthorized to edit a user.'))

        # Custom handling if user in organization
        action_ctx = context.copy()
        action_ctx['user'] = id
        c.in_organization = bool(logic.get_action('organization_list_for_user')(action_ctx, {}))

        to_json = convert_to_json('about')
        not_empty = tk.get_validator('not_empty')
        context['schema'].update({
            'official_position': [not_empty, to_json],
            'official_phone': [not_empty, to_json]
        })

        # End of custom handling

        if (context['save']) and not data:
            return self._save_edit(id, context)

        try:
            if not data:
                data = get_action('user_show')(context, data_dict)

                schema = self._db_to_edit_form_schema()
                if schema:
                    data, errors = df.validate(data, schema, context)

                c.display_name = data.get('display_name')
                c.user_name = data.get('name')

        except NotAuthorized:
            abort(401, _('Unauthorized to edit user %s') % '')
        except NotFound:
            abort(404, _('User not found'))

        user_obj = context.get('user_obj')

        if not (new_authz.is_sysadmin(c.user)
                or c.user == user_obj.name):
            abort(401, _('User %s not authorized to edit %s') %
                  (str(c.user), id))

        errors = errors or {}
        vars = {'data': data, 'errors': errors, 'error_summary': error_summary}

        self._setup_template_variables({'model': model,
                                        'session': model.Session,
                                        'user': c.user or c.author},
                                       data_dict)

        c.is_myself = True
        c.show_email_notifications = h.asbool(
            config.get('ckan.activity_streams_email_notifications'))
        c.form = render(self.edit_user_form, extra_vars=vars)

        return render('user/edit.html')
Example #32
0
 def _syndicate(self, dataset):
     return (not dataset.private
             and asbool(dataset.extras.get(get_syndicate_flag(), 'false')))
Example #33
0
def is_organization_preserved():
    return asbool(config.get('ckan.syndicate.replicate_organization', False))