Exemple #1
0
    def create_survey_session(self, title, account=None, **params):
        """Create a new survey session.

        :param title: title for the new survey session.
        :type title: unicode
        :rtype: :py:class:`cls.survey_session_model` instance
        """
        if account is None:
            account = get_current_account()

        session = Session()
        sector = self.context.aq_parent
        country = sector.aq_parent
        zodb_path = "%s/%s/%s" % (country.id, sector.id, self.context.id)
        survey_session = self.survey_session_model(
            title=title,
            zodb_path=zodb_path,
            account_id=account.id,
            group_id=account.group_id,
        )
        for key in params:
            setattr(survey_session, key, params[key])
        session.add(survey_session)
        session.refresh(account)
        session.flush()  # flush so we get a session id
        return survey_session
Exemple #2
0
    def handleSave(self, action):
        flash = IStatusMessage(self.request).addStatusMessage
        (data, errors) = self.extractData()
        if errors:
            for error in errors:
                flash(error.message, "notice")
            return

        user = get_current_account()
        if not data["new_password"]:
            flash(_("There were no changes to be saved."), "notice")
            return
        login_view = api.content.get_view(
            name="login",
            context=self.context,
            request=self.request,
        )
        error = login_view.check_password_policy(data["new_password"])
        if error:
            raise WidgetActionExecutionError("new_password", Invalid(error))
        if not user.verify_password(data["old_password"]):
            raise WidgetActionExecutionError("old_password",
                                             Invalid(_("Invalid password")))
        user.password = data["new_password"]
        flash(_("Your password was successfully changed."), "success")
Exemple #3
0
    def transferGuestSession(self):
        """Transfer session(s) from guest account to an existing user account

        The guest account is expected to go the login form as an authenticated user.

        For this reason we can know from the session plugin who he is even
        if during the request process we are now logged in as a new user.
        """
        plugin = self.context.acl_users.session
        old_credentials = plugin.authenticateCredentials(
            plugin.extractCredentials(self.request))
        if old_credentials is None:
            # We came here as anonymous user, no need to proceed
            return

        old_authenticated_account_id = old_credentials[0]

        if (Session.query(model.Account).filter(
                model.Account.account_type == config.GUEST_ACCOUNT,
                model.Account.id == old_authenticated_account_id,
        ).first()) is None:
            # We check that the previously authenticated user was actually
            # a guest account that has been converted.
            # This prevents that a regular logged in user A logs in as B
            # and then all the sessions are transferred to B
            return

        new_account = get_current_account()
        sessions = Session.query(model.SurveySession).filter(
            model.SurveySession.account_id == old_authenticated_account_id)
        for session in sessions:
            session.account_id = new_account.id
Exemple #4
0
 def handleSave(self, action):
     flash = IStatusMessage(self.request).addStatusMessage
     (data, errors) = self.extractData()
     if errors:
         for error in errors:
             flash(error.message, "notice")
         return
     user = get_current_account()
     user.first_name = data["first_name"]
     user.last_name = data["last_name"]
Exemple #5
0
    def __call__(self):
        webhelpers = api.content.get_view(name="webhelpers",
                                          context=self.context,
                                          request=self.request)
        self.came_from = webhelpers.get_came_from(
            default=aq_inner(self.context).absolute_url())

        self.account = get_current_account()
        if self.request.environ["REQUEST_METHOD"] == "POST":
            self.account.tc_approved = CONDITIONS_VERSION

            self.request.response.redirect(self.came_from)
        return self.index()
Exemple #6
0
    def handleDelete(self, action):
        (data, errors) = self.extractData()
        if errors:
            return

        user = get_current_account()
        if not user.verify_password(data["password"]):
            raise WidgetActionExecutionError("password",
                                             Invalid(_("Invalid password")))

        Session.delete(user)
        self.logout()
        self.request.response.redirect(self.request.client.absolute_url())
Exemple #7
0
    def handleSave(self, action):
        flash = IStatusMessage(self.request).addStatusMessage

        (data, errors) = self.extractData()
        if errors:
            return
        url = self.context.absolute_url()

        user = get_current_account()
        if not user.verify_password(data["password"]):
            raise WidgetActionExecutionError("password",
                                             Invalid(_("Invalid password")))

        settings_url = "%s/account-settings" % url
        if not data["loginname"] or data["loginname"].strip(
        ) == user.loginname:
            self.request.response.redirect(settings_url)
            flash(_("There were no changes to be saved."), "notice")
            return

        login = data["loginname"].strip().lower()
        existing = Session.query(Account.id).filter(Account.loginname == login)
        if existing.count():
            raise WidgetActionExecutionError(
                "loginname",
                Invalid(_("This email address is not available.")))

        self.initiateRequest(user, login)

        flash(
            _(
                "email_change_pending",
                default=(
                    "Please confirm your new email address by clicking on "
                    "the link in the email that will be sent in a few "
                    'minutes to "${email}". Please note that the new '
                    "email address is also your new login name."),
                mapping={"email": data["loginname"]},
            ),
            "warning",
        )
        self.request.response.redirect("%s/" % url)
Exemple #8
0
    def __call__(self):
        self.verify_view_permission()
        if self.webhelpers.redirectOnSurveyUpdate():
            return

        session = self.context.session
        if self.request.method == "POST":
            session.report_comment = self.request.form.get("comment")

            url = "%s/@@report_company" % self.context.absolute_url()
            if (getattr(session, "company", None) is not None
                    and getattr(session.company, "country") is not None):
                url = "%s/@@report_view" % self.context.absolute_url()

            user = get_current_account()
            if getattr(user, "account_type", None) == config.GUEST_ACCOUNT:
                url = "%s/@@register_session?came_from=%s" % (
                    self.context.absolute_url(),
                    quote(url, ""),
                )
            return self.request.response.redirect(url)

        utils.setLanguage(self.request, self.survey, self.survey.language)
        return super(Report, self).__call__()
Exemple #9
0
def approvedTermsAndConditions(account=None):
    if account is None:
        account = get_current_account()
    return account.tc_approved is not None and account.tc_approved == CONDITIONS_VERSION
Exemple #10
0
    def __call__(self):
        context = aq_inner(self.context)
        self.errors = {}

        form = self.request.form

        came_from = self.webhelpers.get_came_from(
            default=self.webhelpers.country_url)
        self.setLanguage(came_from)

        account = get_current_account()
        self.allow_guest_accounts = api.portal.get_registry_record(
            "euphorie.allow_guest_accounts", default=False)
        lang = api.portal.get_current_language()

        self.show_whofor = False if lang in ("fr", ) else True
        self.show_what_to_do = False if lang in ("fr", ) else True
        self.show_how_long = False if lang in ("fr", ) else True
        self.show_why_register = True
        self.show_prepare = False if lang in ("fr", ) else True

        if self.request.method == "POST":
            if form.get("action") == "login":
                if (isinstance(account, model.Account)
                        and account.getUserName() == form.get("__ac_name",
                                                              "").lower()):
                    self.transferGuestSession()
                    self.login(account,
                               bool(self.request.form.get("remember")))
                    v_url = urlsplit(self.request.URL +
                                     "/success").path.replace("@@", "")
                    trigger_extra_pageview(self.request, v_url)
                else:
                    self.error = True

            elif form.get("action") == "register":
                account = self._tryRegistration()
                if account:
                    pas = getToolByName(self.context, "acl_users")
                    pas.updateCredentials(
                        self.request,
                        self.request.response,
                        account.getUserName(),
                        account.password,
                    )
                else:
                    self.error = True

            if not self.error:
                if api.portal.get_registry_record(
                        "euphorie.terms_and_conditions", default=False
                ) and not approvedTermsAndConditions(account):
                    self.request.RESPONSE.redirect(
                        "{0}/terms-and-conditions?{1}".format(
                            context.absolute_url(),
                            urlencode({"came_from": came_from}),
                        ))
                else:
                    self.request.RESPONSE.redirect(came_from)
                return

        self.reset_password_request_url = "{0}/@@reset_password_request?{1}".format(
            context.absolute_url(),
            urlencode({"came_from": came_from}),
        )
        self.register_url = "{0}/@@login#registration?{1}".format(
            context.absolute_url(),
            urlencode({"came_from": came_from}),
        )
        self.tryout_url = "{0}/@@tryout?{1}".format(
            context.absolute_url(),
            urlencode({"came_from": came_from}),
        )

        return self.index()
Exemple #11
0
    def _tryRegistration(self):
        if not self.webhelpers.allow_self_registration:
            raise Unauthorized("No self registration allowed.")
        form = self.request.form
        loginname = form.get("email")
        if not loginname:
            self.errors["email"] = _("error_missing_email",
                                     default="Please enter your email address")
        elif not EMAIL_RE.match(loginname):
            self.errors["email"] = _(
                "error_invalid_email",
                default="Please enter a valid email address")
        if not form.get("password1"):
            self.errors["password"] = _("error_missing_password",
                                        default="Please enter a password")
        elif form.get("password1") != form.get("password2"):
            self.errors["password"] = _("error_password_mismatch",
                                        default="Passwords do not match")
        else:
            policy_error = self.check_password_policy(form.get("password1"))
            if policy_error:
                self.errors["password"] = policy_error
        if not form.get("terms"):
            self.errors["terms"] = _(
                "error_terms_not_accepted",
                default=
                "An accout can only be created for you if you accept the "
                "terms and conditions.",
            )

        if self.errors:
            return False

        # Check honeypot fields
        if form.get("user_name") or form.get("user_email"):
            return False

        session = Session()
        loginname = loginname.lower()
        account = (session.query(model.Account).filter(
            model.Account.loginname == loginname).count())
        if account:
            self.errors["email"] = _(
                "error_email_in_use",
                default="An account with this email address already exists.",
            )
            return False

        pm = getToolByName(self.context, "portal_membership")
        if pm.getMemberById(loginname) is not None:
            self.errors["email"] = _(
                "error_email_in_use",
                default="An account with this email address already exists.",
            )
            return False

        account = get_current_account()
        if account and account.account_type == config.GUEST_ACCOUNT:
            account.loginname = loginname
            account.password = form.get("password1")
            account.account_type = config.CONVERTED_ACCOUNT
            account.created = datetime.datetime.now()
            account.tc_approved = 1
            account.first_name = form.get("first_name")
            account.last_name = form.get("last_name")
            msg = _(
                "An account was created for you with email address ${email}",
                mapping={"email": loginname},
            )
            api.portal.show_message(msg, self.request, "success")
        else:
            account = model.Account(
                loginname=loginname,
                password=form.get("password1"),
                tc_approved=1,
                first_name=form.get("first_name"),
                last_name=form.get("last_name"),
            )
            Session().add(account)
        log.info("Registered new account %s", loginname)
        v_url = urlsplit(self.request.URL + "/success").path.replace("@@", "")
        trigger_extra_pageview(self.request, v_url)
        return account
Exemple #12
0
 def account(self):
     """The currently authenticated account"""
     return get_current_account()
Exemple #13
0
 def get_current_account(self):
     return get_current_account()
Exemple #14
0
 def getContent(self):
     user = get_current_account()
     directlyProvides(user, EmailChangeSchema)
     return user
Exemple #15
0
 def getContent(self):
     user = get_current_account()
     directlyProvides(user, PreferencesSchema)
     return user
Exemple #16
0
 def reset_date(self):
     """Reset the session date to now"""
     session = self.context.session
     session.published = datetime.now()
     session.last_publisher = get_current_account()
     return self.redirect()