def _validate_subscription(self, **kw): """ Validate add/edit subscription for authorized and anonymous users """ if (kw['notif_type'] not in self.available_notif_types(kw['location']) and not (kw['notif_type'] == 'administrative' and self.checkPermissionPublishObjects())): raise i18n_exception(ValueError, 'Subscribing to ${notif_type} ' 'notifications in "${location}" not allowed', location=kw['location'] or self.getSite().title, notif_type=kw['notif_type']) try: obj = self.getSite().restrictedTraverse(kw['location']) except: raise i18n_exception(ValueError, 'This path is invalid or protected') try: subscription_container = ISubscriptionContainer(obj) except: raise i18n_exception(ValueError, 'Cannot subscribe to this folder') if kw.get('anonymous', False): #Check if subscription exists for this anonymous subscriber if not is_valid_email(kw.get('email', '')): raise i18n_exception(ValueError, 'Your e-mail address does not appear to be valid.') for id, subscription in subscription_container.list_with_keys(): #Normal subscriptions don't have e-mail if isinstance(subscription, AnonymousSubscription): if (subscription.email == kw['email'] and subscription.notif_type == kw['notif_type'] and subscription.lang == kw['lang']): raise i18n_exception(ValueError, 'Subscription already exists')
def test_exception_with_i18n(self): err = i18n_exception(ValueError, "my local message") assert isinstance(err, ValueError) assert err.args == ("my local message",) assert str(err) == "my local message" assert hasattr(err, "_ny_i18n") assert err._ny_i18n == ("my local message", {}) err2 = i18n_exception(IndexError, "bad index for ${name}", name="joe") assert isinstance(err2, IndexError) assert err2.args == ("bad index for joe",) assert str(err2) == "bad index for joe" assert hasattr(err2, "_ny_i18n") assert err2._ny_i18n == ("bad index for ${name}", {'name': 'joe'})
def test_exception_with_i18n(self): err = i18n_exception(ValueError, "my local message") assert isinstance(err, ValueError) assert err.args == ("my local message", ) assert str(err) == "my local message" assert hasattr(err, "_ny_i18n") assert err._ny_i18n == ("my local message", {}) err2 = i18n_exception(IndexError, "bad index for ${name}", name="joe") assert isinstance(err2, IndexError) assert err2.args == ("bad index for joe", ) assert str(err2) == "bad index for joe" assert hasattr(err2, "_ny_i18n") assert err2._ny_i18n == ("bad index for ${name}", {'name': 'joe'})
def request_token(self, email, REQUEST=None): """ User submits an email address. If address found, an email is sent with a password reset token. """ auth_tool = self.getSite().getAuthenticationTool() users = list(auth_tool.lookup_user_by_email(email)) if not users: err = i18n_exception(ValueError, 'E-mail address not found: "${email}"', email=email) if REQUEST is None: raise err else: self.setSessionErrorsTrans(err) return REQUEST.RESPONSE.redirect(self.absolute_url()) for user in users: token = self._new_token(user.getId()) url = '%s/confirm?token=%s' % (self.absolute_url(), token) email_data = email_template.render_email(user=user, portal=self.getSite(), confirmation_url=url) email_tool = self.getSite().getEmailTool() email_tool.sendEmail(email_data['body_text'], [email], email_tool.get_addr_from(), email_data['subject']) if REQUEST is not None: options = {'email': email} return self._request_token_html(REQUEST, **options)
def processRequestInfo(self, username='', password='', confirm='', title='', firstname='', lastname='', email='', address='', phone='', description='', fax='', website='', organisation='', role='', comments='', REQUEST=None, RESPONSE=None): """ process the request for a new account """ if REQUEST.has_key('cancel'): if REQUEST.has_key('return_path'): return RESPONSE.redirect(REQUEST['return_path']) else: return RESPONSE.redirect(self.getSitePath()) err = [] self.setContributorSession(username, role, firstname, lastname, email, '', organisation, comments, address, phone, title, description, fax, website) if not self.checkPermissionSkipCaptcha(): contact_word = REQUEST.get('contact_word') captcha_errors = self.validateCaptcha(contact_word, REQUEST) if captcha_errors: err.extend(captcha_errors) if not err: try: if not self.checkPermissionCreateUser(): raise i18n_exception(ValueError, "Self-registration not allowed") self.getAuthenticationTool().manage_addUser(username, password, confirm, [], [], firstname, lastname, email, strict=1) except Exception, error: err.append(error)
def test_localize_exception(self): message_catalog = { 'bad ${name}': 'TRANSLATED ${name} BLAH', 'hello world': 'howdy world', 'blah blah': 'yada yada', } gettext = message_catalog.get e1 = ValueError("hello world") assert localize_exc(e1, gettext) == "howdy world" e2 = i18n_exception(ValueError, "blah blah") assert localize_exc(e2, gettext) == "yada yada" e3 = i18n_exception(ValueError, "bad ${name}", name="llama") assert localize_exc(e3, gettext) == "TRANSLATED llama BLAH"
def parseFormData(self, data): if self.isEmptyDatamodel(data): return None if isinstance(data, Interval): return data if not isinstance(data, dict): raise i18n_exception(WidgetError, 'Expected multiple values for "${title}"', title=self.title) try: start_date = data.get('start_date', None) if not start_date: start_date = None end_date = data.get('end_date', None) if not end_date: end_date = None start_time = data.get('start_time', None) if not start_time: start_time = None end_time = data.get('end_time', None) if not end_time: end_time = None all_day = data.get('all_day', False) if all_day: all_day = True if None in (start_date, end_date): raise i18n_exception( WidgetError, 'Start time (date) and End time (date) ' + 'must both have values') elif all_day is False and None in (start_time, end_time): raise i18n_exception( WidgetError, 'Start time (hh:mm) and End time (hh:mm)' + ' must both have values when all_day is False') else: start_date = self.normalize_date(start_date, start_time, all_day, "Start Time") end_date = self.normalize_date(end_date, end_time, all_day, "End Time") return Interval(start_date, end_date, all_day) except ValueError, e: raise i18n_exception(WidgetError, str(e))
def parseFormData(self, data): if self.isEmptyDatamodel(data): return None if isinstance(data, Interval): return data if not isinstance(data, dict): raise i18n_exception(WidgetError, 'Expected multiple values for "${title}"', title=self.title) try: start_date = data.get('start_date', None) if not start_date: start_date = None end_date = data.get('end_date', None) if not end_date: end_date = None start_time = data.get('start_time', None) if not start_time: start_time = None end_time = data.get('end_time', None) if not end_time: end_time = None all_day = data.get('all_day', False) if all_day: all_day = True if None in (start_date, end_date): raise i18n_exception(WidgetError, 'Start time (date) and End time (date) ' + 'must both have values') elif all_day is False and None in (start_time, end_time): raise i18n_exception(WidgetError, 'Start time (hh:mm) and End time (hh:mm)' + ' must both have values when all_day is False') else: start_date = self.normalize_date(start_date, start_time, all_day, "Start Time") end_date = self.normalize_date(end_date, end_time, all_day, "End Time") return Interval(start_date, end_date, all_day) except ValueError, e: raise i18n_exception(WidgetError, str(e))
def remove_anonymous_subscription(self, email, location, notif_type, lang): try: obj = self.getSite().restrictedTraverse(location) except: raise i18n_exception(ValueError, 'Invalid location') try: subscription_container = ISubscriptionContainer(obj) except: raise i18n_exception(ValueError, 'Invalid container') anonymous_subscriptions = [(n, s) for n, s in subscription_container.list_with_keys() if hasattr(s, 'email')] subscriptions = filter(lambda s: (s[1].email == email and s[1].location == location and s[1].notif_type == notif_type), anonymous_subscriptions) if len(subscriptions) == 1: subscription_container.remove(subscriptions[0][0]) else: raise i18n_exception(ValueError, 'Subscription not found')
def remove_anonymous_subscription(self, email, location, notif_type, lang): try: obj = self.getSite().restrictedTraverse(location) except: raise i18n_exception(ValueError, 'Invalid location') try: subscription_container = ISubscriptionContainer(obj) except: raise i18n_exception(ValueError, 'Invalid container') anonymous_subscriptions = [ (n, s) for n, s in subscription_container.list_with_keys() if hasattr(s, 'email') ] subscriptions = filter( lambda s: (s[1].email == email and s[1].location == location and s[ 1].notif_type == notif_type), anonymous_subscriptions) if len(subscriptions) == 1: subscription_container.remove(subscriptions[0][0]) else: raise i18n_exception(ValueError, 'Subscription not found')
def _validate_subscription(self, **kw): """ Validate add/edit subscription for authorized and anonymous users """ if kw['notif_type'] not in self.available_notif_types(kw['location']): raise i18n_exception(ValueError, 'Subscribing to notifications in ' '"${location}" not allowed', location=kw['location']) try: obj = self.getSite().restrictedTraverse(kw['location']) except: raise i18n_exception(ValueError, 'This path is invalid or protected') try: subscription_container = ISubscriptionContainer(obj) except: raise i18n_exception(ValueError, 'Cannot subscribe to this folder') if not kw.get('anonymous', False): n = utils.match_account_subscription(subscription_container, kw['user_id'], kw['notif_type'], kw['lang']) if n is not None: raise i18n_exception(ValueError, 'Subscription already exists') else: #Check if subscription exists for this anonymous subscriber if not is_valid_email(kw.get('email', '')): raise i18n_exception(ValueError, 'Your e-mail address does not appear to be valid.') for id, subscription in subscription_container.list_with_keys(): #Normal subscriptions don't have e-mail if isinstance(subscription, AnonymousSubscription): if (subscription.email == kw['email'] and subscription.notif_type == kw['notif_type'] and subscription.lang == kw['lang']): raise i18n_exception(ValueError, 'Subscription already exists')
def normalize_date(self, date, time, all_day, name): """ Used by parseFormData """ if date is None: return date try: ds = map(int, date.split("/")) if all_day is True: return datetime(ds[2], ds[1], ds[0]) else: (h, m) = map(int, time.split(":")) return datetime(ds[2], ds[1], ds[0], h, m) except Exception, e: raise i18n_exception(WidgetError, 'Bad value (${date}, ${time}) for ${who}', date=repr(date), time=repr(time), who=name)