Example #1
0
    def remove_action(self, index, post_data):
        emails = self.user.get_mail_aliases()
        if len(emails) == 1:
            message = _('Error: You only have one email address and it  '
                        'can not be removed')
            return {
                'result': 'error',
                'message': get_localizer(self.request).translate(message),
            }
        remove_email = emails[index]['email']
        emails.remove(emails[index])

        self.user.set_mail_aliases(emails)
        primary_email = self.user.get_mail()

        if not primary_email or primary_email == remove_email:
            self.user.set_mail(emails[0]['email'])

        try:
            self.user.save(self.request)
        except UserOutOfSync:
            return self.sync_user()

        self.request.stats.count('dashboard/email_removed', 1)
        message = _('Email address was successfully removed')
        return {
            'result': 'success',
            'message': get_localizer(self.request).translate(message),
        }
Example #2
0
 def render(self):
     model = self.model
     title = model.metadata.get('title', model.name)
     if not model.properties.action_delete:
         ts = _('object_not_deletable',
                default='Object "${title}" not deletable',
                mapping={'title': title})
         localizer = get_localizer(self.request)
         message = localizer.translate(ts)
         ajax_message(self.request, message, 'error')
         return u''
     content_tile = model.properties.action_delete_tile
     if not content_tile:
         content_tile = 'content'
     parent = model.parent
     del parent[model.name]
     if hasattr(parent, '__call__'):
         parent()
     query = make_query(contenttile=content_tile)
     url = make_url(self.request, node=parent, query=query)
     ajax_continue(self.request, self.continuation(url))
     if self.show_confirm_deleted:
         ts = _('deleted_object',
                default='Deleted: ${title}',
                mapping={'title': title})
         localizer = get_localizer(self.request)
         message = localizer.translate(ts)
         ajax_message(self.request, message, 'info')
     return u''
Example #3
0
    def setprimary_action(self, index, post_data):
        self.user = get_session_user(self.request)
        mobiles = self.user.phone_numbers.to_list()

        try:
            mobile = mobiles[index]
        except IndexError:
            return self.sync_user()

        if not mobile.is_verified:
            message = _('You need to confirm your mobile number '
                        'before it can become primary')
            return {
                'result': 'bad',
                'message': get_localizer(self.request).translate(message),
            }

        self.user.phone_numbers.primary = mobile.number
        try:
            self.context.save_dashboard_user(self.user)
        except UserOutOfSync:
            return self.sync_user()

        self.request.stats.count('mobile_number_set_primary')
        message = _('Mobile phone number was successfully made primary')
        return {
            'result': 'success',
            'message': get_localizer(self.request).translate(message),
        }
Example #4
0
    def add_success(self, emailform):
        newemail = self.schema.serialize(emailform)

        new_email = MailAddress(email=newemail['mail'],
                application='dashboard',
                verified=False, primary=False)

        self.user = get_session_user(self.request)
        self.user.mail_addresses.add(new_email)
        try:
            self.context.save_dashboard_user(self.user)
        except UserOutOfSync:
            self.sync_user()

        else:
            message = _('Changes saved')
            self.request.session.flash(get_localizer(self.request).translate(message), queue='forms')

            send_verification_mail(self.request, newemail['mail'])

            second_msg = _('A confirmation email has been sent to your email '
                    'address. Please enter your confirmation code '
                    '<a href="#" class="verifycode" '
                    'data-identifier="${id}">here</a>.', mapping={'id': self.user.mail_addresses.count})
            self.request.session.flash(get_localizer(self.request).translate(second_msg), queue='forms')
Example #5
0
    def setprimary_action(self, index, post_data):

        self.user = get_session_user(self.request)
        try:
            mail = self.user.mail_addresses.to_list()[index]
        except IndexError:
            return self.sync_user()

        if not mail.is_verified:
            message = _('You need to confirm your email address '
                        'before it can become primary')
            return {
                'result': 'bad',
                'message': get_localizer(self.request).translate(message),
            }

        self.user.mail_addresses.primary = mail.email
        try:
            self.context.save_dashboard_user(self.user)
        except UserOutOfSync:
            return self.sync_user()

        self.request.stats.count('dashboard/email_set_primary', 1)
        message = _('Your primary email address was '
                    'successfully changed')
        return {'result': 'success',
                'message': get_localizer(self.request).translate(message)}
Example #6
0
    def remove_action(self, index, post_data):
        self.user = get_session_user(self.request)
        emails = self.user.mail_addresses.to_list()
        if len(emails) == 1:
            message = _('Error: You only have one email address and it  '
                        'can not be removed')
            return {
                'result': 'error',
                'message': get_localizer(self.request).translate(message),
            }

        try:
            remove_email = emails[index].email
        except IndexError:
            return self.sync_user()

        try:
            self.user.mail_addresses.remove(remove_email)
        except PrimaryElementViolation:
            new_index = 0 if index != 0 else 1
            self.user.mail_addresses.primary = emails[new_index].email
            self.user.mail_addresses.remove(remove_email)

        try:
            self.context.save_dashboard_user(self.user)
        except UserOutOfSync:
            return self.sync_user()

        self.request.stats.count('dashboard/email_removed', 1)
        message = _('Email address was successfully removed')
        return {
            'result': 'success',
            'message': get_localizer(self.request).translate(message),
        }
Example #7
0
    def __call__(self, node, value):
        """
        Validator which makes sure that:
        1. the NiN has not already been added by the user
        2. the user does not already have a confirmed NiN.
        """

        from eduiddashboard.models import normalize_nin
        value = normalize_nin(copy(value))

        request = node.bindings.get('request')
        user = get_session_user(request)
        user_nins = user.nins

        unverified_user_nins = request.db.verifications.find({
            'obj_id': value,
            'model_name': 'norEduPersonNIN',
            'user_oid': user.user_id,
            'verified': False
        })

        # Search the request.POST for any post that starts with "add".
        for post_value in request.POST:
            if post_value.startswith('add') and (user_nins.find(value) or
                                      unverified_user_nins.count() > 0):
                err = _('National identity number already added')
                raise colander.Invalid(node, get_localizer(request).translate(err))

            elif post_value.startswith('add') and user_nins.count > 0:
                err = _('You already have a confirmed national identity number')
                raise colander.Invalid(node, get_localizer(request).translate(err))
Example #8
0
    def add_success(self, emailform):
        newemail = self.schema.serialize(emailform)

        # We need to add the new email to the emails list

        emails = self.user.get_mail_aliases()

        mailsubdoc = {
            'email': newemail['mail'],
            'verified': False,
            'added_timestamp': datetime.utcnow()
        }

        emails.append(mailsubdoc)

        self.user.set_mail_aliases(emails)
        try:
            self.user.save(self.request)
        except UserOutOfSync:
            self.sync_user()

        else:
            message = _('Changes saved')
            self.request.session.flash(get_localizer(self.request).translate(message), queue='forms')

            send_verification_mail(self.request, newemail['mail'])

            second_msg = _('A confirmation email has been sent to your email '
                    'address. Please enter your confirmation code '
                    '<a href="#" class="verifycode" '
                    'data-identifier="${id}">here</a>.', mapping={'id': len(emails)})
            self.request.session.flash(get_localizer(self.request).translate(second_msg), queue='forms')
Example #9
0
def account(request):
    change_password_form = forms.ChangePasswordForm(
        csrf_context=request
    )
    if request.method == 'POST':
        change_password_form.process(request.POST)
        if change_password_form.validate():
            try:
                user = DBSession.query(User).filter(
                    User.id == authenticated_userid(request)
                ).one()
            except database_exceptions.NoResultFound:
                raise httpexceptions.HTTPNotFound()
            user.set_password(change_password_form.password.data)
            DBSession.add(user)
            request.session.flash(
                get_localizer(request).translate(_(
                    "Your password has been successfuly changed."
                )),
                queue='success'
            )
            return httpexceptions.HTTPFound(
                request.route_url('alpaca.users.account')
            )
        else:
            request.session.flash(
                get_localizer(request).translate(_(
                    "There were some problems with your request."
                    " Please check the form for error messages."
                )),
                queue='error'
            )
    return {
        'change_password_form': change_password_form,
    }
Example #10
0
 def __init__(self, context, request):
     self.request = request
     self.context = context
     self.user = context.user
     self.verify_messages = {}
     for msgid, msg in self.default_verify_messages.items():
         if msgid not in self.special_verify_messages:
             self.verify_messages[msgid] = get_localizer(
                     request).translate(msg)
         else:
             self.verify_messages[msgid] = get_localizer(
                     request).translate(self.special_verify_messages[msgid])
Example #11
0
def user_add_to_group_action(model, request):
    """Add user to group.
    """
    group_id = request.params.get('id')
    if not group_id:
        group_ids = request.params.getall('id[]')
    else:
        group_ids = [group_id]
    try:
        user = model.model
        validate_add_users_to_groups(model, [user.id], group_ids)
        groups = user.root.groups
        for group_id in group_ids:
            groups[group_id].add(user.name)
        groups()
        model.parent.invalidate(user.name)
        localizer = get_localizer(request)
        message = localizer.translate(_(
            'added_user_to_group',
            default="Added user '${uid}' to group '${gid}'.",
            mapping={
                'uid': user.id,
                'gid': ', '.join(group_ids)
            }
        ))
        return {
            'success': True,
            'message': message
        }
    except ManageMembershipError as e:
        if e.reason is not LM_TARGET_GID_NOT_ALLOWED:
            raise Exception(u"Unknown ManageMembershipError reason.")
        localizer = get_localizer(request)
        message = localizer.translate(_(
            'lm_add_target_gid_not_allowed',
            default=(
                "Failed adding user '${uid}' to group '${gid}'. "
                "Manage membership denied for target group."
            ),
            mapping={
                'uid': user.id,
                'gid': e.data
            }
        ))
        return {
            'success': False,
            'message': message
        }
    except Exception as e:
        return {
            'success': False,
            'message': str(e)
        }
Example #12
0
def user_remove_from_group_action(model, request):
    """Remove user from group.
    """
    group_id = request.params.get("id")
    if not group_id:
        group_ids = request.params.getall("id[]")
    else:
        group_ids = [group_id]
    try:
        user = model.model
        validate_remove_users_from_groups(model, [user.id], group_ids)
        groups = user.root.groups
        for group_id in group_ids:
            del groups[group_id][user.name]
        groups()
        model.parent.invalidate(user.name)
        localizer = get_localizer(request)
        message = localizer.translate(
            _(
                "removed_user_from_group",
                default="Removed user '${uid}' from group '${gid}'.",
                mapping={"uid": user.id, "gid": ", ".join(group_ids)},
            )
        )
        return {"success": True, "message": message}
    except ManageMembershipError, e:
        localizer = get_localizer(request)
        if e.reason is LM_TARGET_GID_NOT_ALLOWED:
            message = localizer.translate(
                _(
                    "lm_remove_target_gid_not_allowed",
                    default="Failed removing user '${uid}' from group '${gid}'. "
                    "Manage membership denied for target group.",
                    mapping={"uid": user.id, "gid": e.data},
                )
            )
        elif e.reason is LM_TARGET_GID_IS_DEFAULT:
            message = localizer.translate(
                _(
                    "lm_remove_target_gid_is_default",
                    default="Failed removing user '${uid}' from group '${gid}'. "
                    "Target group is default group of user.",
                    mapping={"uid": user.id, "gid": e.data},
                )
            )
        else:
            raise Exception(u"Unknown ManageMembershipError reason.")
        return {"success": False, "message": message}
Example #13
0
def auto_translate(request, string):
    localizer = get_localizer(request)
    untranslated = _(string)
    if string and isinstance(string, basestring):
        if hasattr(string, 'domain'):
            untranslated = string
    return localizer.translate(untranslated)
Example #14
0
 def __call__(self, node, value):
     request = node.bindings.get('request')
     try:
         request.userdb.get_user_by_email(value)
     except UserDoesNotExist:
         err = _("Email address does not exist")
         raise colander.Invalid(node, get_localizer(request).translate(err))
Example #15
0
File: util.py Project: igudym/Kotti
def translate(*args, **kwargs):
    request = get_current_request()
    if request is None:
        localizer = get_localizer_for_locale_name('en')
    else:
        localizer = get_localizer(request)
    return localizer.translate(*args, **kwargs)
Example #16
0
    def __call__(self, node, value):

        request = node.bindings.get('request')
        user = get_session_user(request)
        mobile = normalize_to_e_164(request, value)

        # The debug logs below were added to help figure out how a user
        # managed to get by past this function with a duplicated phone number,
        # which was caught by userdb while saving the user.

        log.debug("User {!r} tried to add a phone number {!r}: "
                  "entering 1st code-section that will verify that it's unique."
                  .format(user.eppn, mobile))

        if sanitize_post_key(request, 'add') is not None:
            log.debug("User {!r} tried to add a phone number {!r}: "
                      "1st code-section evaluated, POST request OK."
                      .format(user.eppn, mobile))

            if user.phone_numbers.find(mobile):
                log.debug("User {!r} tried to add a phone number {!r}: "
                          "2nd code-section evaluated, the user had already "
                          "added the phone number."
                          .format(user.eppn, mobile))

                err = _("This mobile phone was already registered")
                raise colander.Invalid(node, get_localizer(request).translate(err))

            else:
                log.debug("User {!r} tried to add a phone number {!r}: "
                          "2nd code-section evaluated, the phone number "
                          "has not previously been added by the user."
                          .format(user.eppn, mobile))
Example #17
0
 def __call__(self, node, value):
     request = node.bindings.get('request')
     is_email = '@' in value
     localizer = get_localizer(request)
     if not is_email:
         try:
             request.userdb.get_user_by_username(value)
         except UserDB.UserDoesNotExist:
             err = _("Username does not exist")
             raise colander.Invalid(node, localizer.translate(err))
         except UserDB.MultipleUsersReturned:
             err = _("There is more than one user for that username")
             raise colander.Invalid(node, localizer.translate(err))
     else:
         try:
             request.userdb.get_user_by_email(value)
         except UserDoesNotExist as e:
             if e.args:
                 msg = e.args[0]
             else:
                 msg = _("email address ${val} does not exist "
                         "or is unverified")
                 msg = localizer.translate(msg, mapping={'val': value})
             raise colander.Invalid(node, msg)
         except MultipleUsersReturned:
             msg = _("There is more than one user for that email")
             raise colander.Invalid(node, localizer.translate(msg))
Example #18
0
    def __call__(self, node, value):
        request = node.bindings.get('request')
        localizer = get_localizer(request)
        settings = request.registry.settings
        value = value.replace(" ", "")
        password_min_entropy = int(settings.get('password_entropy', 60))

        # We accept a 10% of variance in password_min_entropy because
        # we have calculated the entropy by javascript too and the results
        # may vary.
        password_min_entropy = (0.90 * password_min_entropy)

        generated_password = request.session.get('last_generated_password', '')
        if len(generated_password) > 0 and generated_password == value:
            # Don't validate the password if it is the generated password
            # That is, the user has filled out the form with the suggested
            # password
            return

        # Get a users e-mail addresses to make sure a user does not use one of those as password
        user = get_session_user(request, raise_on_not_logged_in = False)
        if not user:
            # User is resetting a forgotten password
            hash_code = request.matchdict['code']
            password_reset = request.db.reset_passwords.find_one({'hash_code': hash_code})
            user = request.userdb_new.get_user_by_mail(password_reset['email'])
        mail_addresses = [item.email for item in user.mail_addresses.to_list()]

        veredict = zxcvbn.password_strength(value, user_inputs=mail_addresses)

        if veredict.get('entropy', 0) < password_min_entropy:
            err = _('The password complexity is too weak.')
            raise colander.Invalid(node, localizer.translate(err))
Example #19
0
 def validate_python(self, value, state):
     super(CSRFTokenValidator, self).validate_python(value, state)
     request = state.request
     token = request.session.get_csrf_token()
     if token != value:
         localizer = get_localizer(request)
         raise formencode.Invalid(localizer.translate(_('Invalid CSRF token.')), value, state)
def get_tab(request):
    label = _('Postal address')
    return {
        'status': get_status,
        'label': get_localizer(request).translate(label),
        'id': 'postaladdress',
    }
Example #21
0
def client_promise(ctx, request):
	loc = get_localizer(request)
	csrf = request.POST.get('csrf', '')
	diff = request.POST.get('diff', '')

	if 'submit' in request.POST:
		sess = DBSession()
		if csrf != request.get_csrf():
			request.session.flash({
				'text' : loc.translate(_('Error submitting form')),
				'class' : 'danger'
			})
			return HTTPSeeOther(location=request.route_url('stashes.cl.accounts', traverse=()))
		fp = FuturePayment()
		fp.stash = ctx
		fp.entity = request.user.parent
		fp.origin = FuturePaymentOrigin.user
		fp.difference = diff
		sess.add(fp)
		request.session.flash({
			'text' : loc.translate(_('Successfully added new promised payment'))
		})
		return HTTPSeeOther(location=request.route_url('stashes.cl.accounts', traverse=()))

	request.session.flash({
		'text' : loc.translate(_('Error submitting form')),
		'class' : 'danger'
	})

	return HTTPSeeOther(location=request.route_url('stashes.cl.accounts', traverse=()))
Example #22
0
def add_localizer(event):
    request = event.request
    localizer = get_localizer(request)
    def auto_translate(string):
        return localizer.translate(tsf2(localizer.translate(tsf1(string))))
    request.localizer = localizer
    request.translate = auto_translate
    def __call__(self, node, value):
        """
            Check if the NIN was not already registered and verified by any user
            Check if the NIN was not already registered by the present user in the
                verifications process.
        """

        from eduiddashboard.models import normalize_nin
        value = normalize_nin(copy(value))

        request = node.bindings.get('request')
        user = request.context.user
        user_nins = user.get_nins()

        unverified_user_nins = request.db.verifications.find({
            'obj_id': value,
            'model_name': 'norEduPersonNIN',
            'user_oid': user.get_id(),
            'verified': False
        })

        # Search the request.POST for any post that starts with "add"
        for post_value in request.POST:
            if post_value.startswith('add'):
                if unverified_user_nins.count() > 0 or value in user_nins:
                    err = _("This national identity number is already in use")
                    raise colander.Invalid(node,
                            get_localizer(request).translate(err))
Example #24
0
	def get_cfg(self, model, req, **kwargs):
		loc = get_localizer(req)
		store = []
		maxlen = 0
		for sym in self.enum:
			store.append({
				'id'    : sym.value,
				'value' : loc.translate(sym.description)
			})
		return {
			'xtype'          : 'combobox',
			'allowBlank'     : self.kw.get('nullable', False),
			'name'           : self.name,
			'fieldLabel'     : loc.translate(self.kw.get('label', self.name)),
			'format'         : 'string',
			'displayField'   : 'value',
			'valueField'     : 'id',
			'queryMode'      : 'local',
			'editable'       : False,
			'forceSelection' : True,
			'store'          : {
				'xtype'  : 'simplestore',
				'fields' : ('id', 'value'),
				'data'   : store
			}
		}
    def __call__(self, node, value):

        request = node.bindings.get('request')

        if not request.registry.settings.get('use_vccs', True):
            return

        old_password = value
        old_password = old_password.replace(" ", "")

        if 'edit-user' in request.session:
            userid = request.session['edit-user'].get_id()
        else:
            userid = request.session['user'].get_id()
        # Load user from database to ensure we are working on an up-to-date set of credentials.
        user = request.userdb.get_user_by_oid(userid)
        # XXX if we saved user['passwords'] to node.bindings.request['user']['passwords'] here,
        # we could possibly avoid doing the same refresh again when changing passwords
        # (in PasswordsView.save_success()).

        vccs_url = request.registry.settings.get('vccs_url')
        password = check_password(vccs_url, old_password, user)
        if not password:
            err = _('Current password is incorrect')
            localizer = get_localizer(request)
            raise colander.Invalid(node, localizer.translate(err))
Example #26
0
def login(request):
    login_url = request.route_url('login')
    activated = False
    if 'activated' in request.params:
        activated = request.params['activated'].lower() == 'true'
    referrer = request.url
    if referrer == login_url:
        # never use the login form itself as came_from
        # use main view instead
        referrer = 'map'
    came_from = request.params.get('came_from', referrer)
    message = ''
    login = ''
    if 'form.submitted' in request.params:
        login = request.params['login']
        if user_service.check_login_request(request):
            headers = remember(request, login)
            return HTTPFound(location=came_from,
                             headers=headers)

        localizer = get_localizer(request)
        message_ts = _('failed_login', domain='Ondestan')
        message = localizer.translate(message_ts)

    return dict(
        message=message,
        came_from=came_from,
        login=login,
        activated=activated
        )
Example #27
0
def send_confirmation_email(request, email):
    mailer = get_mailer(request)
    localizer = get_localizer(request)
    confirm_what = _('email')
    if isinstance(email.profile, User) and not email.profile.verified:
        confirm_what = _('account')
    data = {
        'name': email.profile.name,
        'email': email.email,
        'confirm_what': localizer.translate(confirm_what),
        'confirm_url': request.route_url('user_confirm_email',
                                         ticket=email_token(email))
    }
    message = Message(
        subject=localizer.translate(_('confirm_title', default="Please confirm your ${confirm_what} with Assembl", mapping=data)),
        sender=config.get('assembl.admin_email'),
        recipients=["%s <%s>" % (email.profile.name, email.email)],
        body=localizer.translate(_('confirm_email', default=u"""Hello, ${name}!
Please confirm your ${confirm_what} <${email}> with Assembl by clicking on the link below.
<${confirm_url}>
""", mapping=data)),
        html=localizer.translate(_('confirm_email_html', default=u"""<p>Hello, ${name}!</p>
<p>Please <a href="${confirm_url}">confirm your ${confirm_what}</a> &lt;${email}&gt; with Assembl.</p>
""", mapping=data)))
    #if deferred:
    #    mailer.send_to_queue(message)
    #else:
    mailer.send(message)
Example #28
0
def get_tab(request):
    label = _('Permissions')
    return {
        'status': get_dummy_status,
        'label': get_localizer(request).translate(label),
        'id': 'permissions',
    }
    def save_success(self, addressform):
        address = self.schema.serialize(addressform)
        address['verified'] = False
        address['type'] = 'alternative'

        addresses = self.user.get_addresses()
        if len(addresses) > 0 and addresses[0].get('type') == 'official':
            if len(addresses) == 1:
                addresses.append(address)
            else:
                addresses[1] = address
        else:
            addresses = [address]

        # update the session data
        self.user.set_addresses(addresses)
        try:
            self.user.save(self.request)
        except UserOutOfSync:
            self.sync_user()
        else:
            message = _('Changes saved.')
            self.request.session.flash(
                    get_localizer(self.request).translate(message),
                    queue='forms')
            self.request.stats.count('dashboard/postal_address_saved', 1)
Example #30
0
def get_device_config_fancy_description(config, request=None, locale=None):

    if request != None:
        localizer = get_localizer(request)
    else:
        localizer = get_custom_localizer(locale)

    datatime = get_device_config_fancy_description_unit_value(config.datatime)
    sampletime = get_device_config_fancy_description_unit_value(config.sampletime)
    readtime = get_device_config_fancy_description_unit_value(config.readtime)
    parameters = {
        'datatime_val': datatime[0],
        'datatime_unit': localizer.translate(_(datatime[1],
            domain='Ondestan')),
        'sampletime_val': sampletime[0],
        'sampletime_unit': localizer.translate(_(sampletime[1],
            domain='Ondestan')),
        'readtime_val': readtime[0],
        'readtime_unit': localizer.translate(_(readtime[1],
            domain='Ondestan'))
    }

    return localizer.translate(_("fancy_config_description",
         domain='Ondestan',
         mapping=parameters))
Example #31
0
def add_localizer(event):
    request = event.request
    localizer = get_localizer(request)

    def auto_translate(string):
        if request.path_info.startswith("/admin/"):
            tsf_list = [tsf_admin, tsf_c2cgeoform]
        elif request.path_info.startswith("/getitfixed"):
            tsf_list = [tsf_getitfixed, tsf_c2cgeoform]
        else:
            tsf_list = [tsf_server, tsf_geoportal]
        for tsf in tsf_list:
            result = localizer.translate(tsf(string))
            if result != string:
                break
        return result

    request.localizer = localizer
    request.translate = auto_translate
Example #32
0
def add_localizer(event):
    request = event.request
    localizer = get_localizer(request)

    def auto_translate(*args, **kwargs):
        # set the default domain if not provided by the context
        kwargs.setdefault('domain', DEFAULT_TRANSLATION_DOMAIN)

        return localizer.translate(*args, **kwargs)

    def auto_plural_translate(*args, **kwargs):
        # set the default domain if not provided by the context
        kwargs.setdefault('domain', DEFAULT_TRANSLATION_DOMAIN)

        return localizer.pluralize(*args, **kwargs)

    request.localizer = localizer
    request.translate = auto_translate
    request.plural_translate = auto_plural_translate
Example #33
0
def send_email(subject,
               recipients,
               html,
               sender=None,
               plaintext=None,
               request=None,
               send_immediately=False,
               **kw):
    """ Send an email to users. This also checks the required settings and translates
        the subject.
        
        returns the message object sent, or None
    """ #FIXME: Docs
    if request is None:
        request = get_current_request()
    localizer = get_localizer(request)
    if isinstance(subject, TranslationString):
        subject = localizer.translate(subject)
    if isinstance(recipients, basestring):
        recipients = (recipients, )
    if plaintext is None:
        html2text = HTML2Text()
        html2text.ignore_links = True
        html2text.ignore_images = True
        html2text.body_width = 0
        plaintext = html2text.handle(html).strip()
    if not plaintext:
        plaintext = None  #In case it was an empty string
    #It seems okay to leave sender blank since it's part of the default configuration
    msg = Message(subject=subject,
                  recipients=recipients,
                  sender=sender,
                  body=plaintext,
                  html=html,
                  **kw)
    mailer = get_mailer(request)
    #Note that messages are sent during the transaction process. See pyramid_mailer docs
    if send_immediately:
        mailer.send_immediately(msg)
    else:
        mailer.send(msg)
    return msg
Example #34
0
 def template_globals(event):
     '''Adds stuff we use all the time to template context.
     There is no need to add *request* since it is already there.
     '''
     request = event['request']
     settings = request.registry.settings
     # A nicer "route_url": no need to pass it the request object.
     event['url'] = lambda name, *a, **kw: \
         route_url(name, request, *a, **kw)
     event['base_path'] = settings.get('base_path', '/')
     event['static_url'] = lambda s: static_url(s, request)
     event['appname'] = settings.get('app.name', 'Application')
     localizer = get_localizer(request)
     translate = localizer.translate
     pluralize = localizer.pluralize
     event['_'] = lambda text, mapping=None: \
         translate(text, domain=package_name, mapping=mapping)
     event['plur'] = lambda singular, plural, n, mapping=None: \
         pluralize(singular, plural, n,
                   domain=package_name, mapping=mapping)
Example #35
0
 def __init__(self, req, propdef, *args, **kwargs):
     super(DAVPrincipalSearchPropertySetResponse,
           self).__init__(*args, request=req, **kwargs)
     loc = get_localizer(req)
     ns_map = dprops.NS_MAP.copy()
     self.xml_root = etree.Element(dprops.PRINC_SEARCH_PROP_SET,
                                   nsmap=ns_map)
     for prop, descr in propdef.items():
         srcprop = etree.SubElement(self.xml_root, dprops.PRINC_SEARCH_PROP)
         el = etree.SubElement(srcprop, dprops.PROP)
         etree.SubElement(el, prop)
         if descr:
             el = etree.SubElement(srcprop, dprops.DESCRIPTION)
             if isinstance(descr, TranslationString):
                 el.set('{http://www.w3.org/XML/1998/namespace}lang',
                        req.locale_name)
                 el.text = loc.translate(descr)
             else:
                 el.set('{http://www.w3.org/XML/1998/namespace}lang', 'en')
                 el.text = descr
Example #36
0
 def _handle(self, request, key, file):
     if not self.scanning:
         localizer = get_localizer(request)
         request.session.flash(
             localizer.translate(
                 _('clamav-not-configured-message',
                   default=('File upload found but clamav is not '
                            'configured.'))), 'error')
         clamlog.error('File upload found but clamav is not configured.')
         return
     try:
         result = self._check_file(request, key, file)
     except (OSError, BrokenPipeError, clamd.ConnectionError) as e:
         clamlog.error('Connection to ClamD was lost: {}'.format(str(e)))
         file.seek(0)
     else:
         if result and result.get('stream')[0] == 'FOUND':
             sig = result.get('stream')[1]
             return handle_virus(request, sig, key)
         else:
             file.seek(0)
Example #37
0
    def add_by_mobile_success(self, ninform):
        """ This method is bounded to the "add_by_mobile"-button by it's name """
        newnin = self.schema.serialize(ninform)
        newnin = newnin['norEduPersonNIN']
        newnin = normalize_nin(newnin)

        self.user = get_session_user(self.request)
        message = set_nin_verified(self.request, self.user, newnin)

        try:
            self.request.context.save_dashboard_user(self.user)
        except UserOutOfSync:
            log.info("Failed to save user {!r} after mobile phone vetting. User out of sync.".format(self.user))
            raise

        log.info("Saved user {!r} after NIN vetting using mobile phone".format(self.user))
        self.request.session.flash(
            get_localizer(self.request).translate(message),
            queue='forms')

        self.request.stats.count('nin_add_mobile')
Example #38
0
def get_status(request, user):
    """
    Check if there is exist norEduPersonNIN active
    Else:
        Check is user has pending nin in verifications collection

    return msg and icon
    """

    completed_fields = 0
    pending_actions = None
    pending_action_type = ''
    verification_needed = -1

    all_nins = user.nins
    if all_nins.count:
        completed_fields = 1

    unverified_nins = get_not_verified_nins_list(request, user)

    if not all_nins.count and not unverified_nins:
        pending_actions = _('Add national identity number')
    if unverified_nins and request.registry.settings.get('enable_mm_verification'):
        pending_actions = _('Validation required for national identity number')
        pending_action_type = 'verify'
        verification_needed = len(unverified_nins) - 1

    status = {
        'completed': (completed_fields, 1)
    }
    if pending_actions:
        pending_actions = get_localizer(request).translate(pending_actions)
        status.update({
            'icon': get_icon_string('warning-sign'),
            'pending_actions': pending_actions,
            'pending_action_type': pending_action_type,
            'verification_needed': verification_needed,
        })

    return status
Example #39
0
def get_device_preconfig_names(request=None, locale=None):
    nr = 1
    try:
        while True:
            Config.get_int_value('gps.preconfig_' + str(nr) + '_readtime')
            Config.get_int_value('gps.preconfig_' + str(nr) + '_sampletime')
            Config.get_int_value('gps.preconfig_' + str(nr) + '_datatime')
            nr = nr + 1
    except:
        pass

    if request != None:
        localizer = get_localizer(request)
    else:
        localizer = get_custom_localizer(locale)

    device_preconfig_names = []
    for i in range(1, nr):
        device_preconfig_names.append(
            localizer.translate(
                _('gps_preconfig_' + str(i) + '_name', domain='Ondestan')))
    return device_preconfig_names
Example #40
0
def animal_charging_history_viewer(request):
    animal_id = request.matchdict['animal_id']
    email = get_user_email(request)
    is_admin = check_permission('admin', request)
    animal = None
    if animal_id != None:
        try:
            animal = animal_service.get_animal_by_id(int(animal_id))
        except ValueError:
            pass
    if (animal == None) or (not is_admin and animal.user.email != email):
        return HTTPFound(request.route_url("map"))
    parameters = {'max_positions': max_positions}
    too_many_positions_msg = _("too_many_positions_in_selected_time_interval",
                               domain='Ondestan',
                               mapping=parameters)
    return dict(
        view=animal.get_bounding_box_as_json(),
        animal_id=animal_id,
        too_many_positions_msg=get_localizer(request).\
            translate(too_many_positions_msg)
    )
Example #41
0
def login(request):
    FORM_TITLE = _('Login')
    localizer = get_localizer(request)
    main = get_renderer(BASE_TEMPLATE).implementation()
    login_form = LoginForm.get_form(localizer)

    login_url = route_url('users.login', request)
    referrer = request.url
    if referrer == login_url:
        referrer = route_url('staff.panel', request)

    b64_caller = request.params.get('caller', None)
    caller = base64.b64decode(b64_caller) if b64_caller is not None else referrer

    if request.method == 'POST':

        controls = request.POST.items()
        try:
            appstruct = login_form.validate(controls)
        except deform.ValidationFailure, e:

            return {'content':e.render(),
                    'main':main,
                    'general_stuff':{'form_title':FORM_TITLE},
                    'user':get_logged_user(request),
                    }
        try:
            user = request.rel_db_session.query(users.User).filter_by(username=appstruct['username']).one()
        except NoResultFound:
            request.session.flash(_("Username doesn't exist."))
        else:
            if SHA256.new(appstruct['password']).hexdigest() == user.password:
                if not user.is_active:
                    request.session.flash(_("The username is not active. Check your email account for the activation instructions."))
                else:
                    headers = remember(request, user.id)
                    return HTTPFound(location=caller, headers=headers)
            else:
                request.session.flash(_("Username/password doesn't match"))
Example #42
0
    def _Run(self, **values):

        try:
            localizer = get_localizer(get_current_request())
        except:
            localizer = FakeLocalizer()

        app = self.app
        datapool = app.db
        conn = datapool.connection
        c = conn.cursor()

        self.stream.write(u"<table>\n")

        sql = "select count(*) from pool_meta"
        c.execute(sql)
        rec = c.fetchall()
        self.stream.write(localizer.translate(_(u"<tr><th>Elements in total</th><td>${value}</td></tr>\n", mapping={u"value": rec[0][0]})))

        sql = "select count(*) from pool_files"
        c.execute(sql)
        rec = c.fetchall()
        self.stream.write(localizer.translate(_(u"<tr><th>Physical files</th><td>${value}</td></tr>\n", mapping={u"value": rec[0][0]})))

        sql = "select sum(size) from pool_files"
        c.execute(sql)
        rec = c.fetchall()
        self.stream.write(localizer.translate(_(u"<tr><th>Physical files size</th><td>${value}</td></tr>\n", mapping={u"value": FormatBytesForDisplay(rec[0][0])})))

        for t in app.GetAllObjectConfs():
            sql = "select count(*) from pool_meta where pool_type='%s'" % t.id
            c.execute(sql)
            rec = c.fetchall()
            self.stream.write(localizer.translate(_(u"<tr><th>${name}</th><td>${value}</td></tr>\n", mapping={u"name": t.name, u"value": rec[0][0]})))
        
        self.stream.write(u"</table>\n")

        c.close()
        return 1
Example #43
0
def sign_in(request):
    destination = request.GET.get(
        'destination', request.route_url('alpaca.problems.dashboard'))
    sign_in_form = forms.AuthenticationForm(csrf_context=request)
    if request.method == 'POST':
        sign_in_form.process(request.POST)
        if sign_in_form.validate():
            try:
                user = DBSession.query(User).filter(
                    User.email == sign_in_form.email.data).one()
            except database_exceptions.NoResultFound:
                pass
            else:
                if user.valid_password(sign_in_form.password.data):
                    return httpexceptions.HTTPFound(destination,
                                                    headers=security.remember(
                                                        request, user.id))
        request.session.flash(get_localizer(request).translate(
            _("Invalid credentials.")),
                              queue='error')
    return {
        'sign_in_form': sign_in_form,
    }
Example #44
0
def set_lang(request, lang=None):
    if lang:
        request._LOCALE_ = lang
        request.localizer = None
        request.locale_name = None
    localizer = get_localizer(request)

    def auto_translate(string):
        return localizer.translate(tsf(string))

    def auto_pluralize(singular, plural, n, mapping={}):
        mapping.update({'num': n})
        try:
            return localizer.pluralize(singular,
                                       plural,
                                       n,
                                       domain='larryslist',
                                       mapping=mapping)
        except AttributeError, e:
            if n != 1:
                return Template(plural).substitute(mapping)
            else:
                return Template(singular).substitute(mapping)
Example #45
0
    def _Run(self, **values):

        try:
            localizer = get_localizer(get_current_request())
        except:
            localizer = FakeLocalizer()

        app = self.app
        root = app.root()
        datapool = app.db
        conn = datapool.connection
        c = conn.cursor()

        # delete
        sql = u"delete from pool_fulltext"
        c.execute(sql)
        c.close()
        conn.commit()
        self.stream.write(localizer.translate(_(u"Deleted previous fulltext index.<br>")))
        
        pages = root.Select(parameter={"pool_stag":10,"pool_state":1})
        cnt = len(pages)
        err = 0
        for page in pages:
            page = page[0]
            obj = root.LookupObj(page)
            if not obj:
                err += 1
                self.stream.write(localizer.translate(_(u"Error: Unable to open page (${id}).<br>", mapping={"id":page})))
            else:
                try:
                    obj.UpdateFulltext()
                except Exception, e:
                    err += 1
                    self.stream.write(localizer.translate(_(u"Error: Unable to update page (${id}).<br>", mapping={"id":page})))
                    self.stream.write(unicode(e))
                    self.stream.write(u"<br><br>")
Example #46
0
    def _Run(self, **values):

        result = 1
        importWf = 1
        importSecurity = 0
        showSystem = values.get("showSystem")
        modify = values.get("modify")
        request = values["original"]
        
        try:
            localizer = get_localizer(get_current_request())
        except:
            localizer = FakeLocalizer()
        #localizer.translate(term) 

        text = _(u""" <div class="well">
This tool compares the physically existing database structure (tables, columns) with the current configuration settings.
The database structure is shown on the left, configuration settings on the right. <br/><br/>
Existing database columns will only be altered if manually selected in the 'Modify' column. Modifying a table may destroy the data
stored (e.g if converted from string to integer), so don't forget to create backups of the database before modifying anything.<br/>
By default this tool will only create new tables and columns and never delete any column.
 </div>       """)
        self.stream.write(localizer.translate(_(text)))

        self.stream.write(u"""<form action="" method="post">
                     <input type="hidden" name="tag" value="dbStructureUpdater">
                     <input type="hidden" name="modify" value="1">""")
        app = self.app
        try:
            conf = app.dbConfiguration
            connection = app.NewConnection()
            if not connection:
                self.stream.write(localizer.translate(_(u"""<div class="alert alert-error">No database connection configured</div>""")))
                return 0
        except OperationalError, e:
            self.stream.write(localizer.translate(_(u"""<div class="alert alert-error">No database connection configured</div>""")))
            return 0
Example #47
0
    def remove_action(self, index, post_data):
        self.user = get_session_user(self.request)
        mobiles = self.user.phone_numbers.to_list()

        try:
            mobile_to_remove = mobiles[index]
        except IndexError:
            return self.sync_user()

        try:
            self.user.phone_numbers.remove(mobile_to_remove.number)
        except PrimaryElementViolation:
            # The exception was raised because it would result in zero
            # primary mobiles while there still exits verified ones.
            # Therefore we first we have to set one of the other
            # verified mobiles as primary before we can try to
            # remove the previous one again.
            verified_mobiles = self.user.phone_numbers.verified.to_list()

            for mobile in verified_mobiles:
                if mobile.number != mobile_to_remove.number:
                    self.user.phone_numbers.primary = mobile.number
                    break

            self.user.phone_numbers.remove(mobile_to_remove.number)

        try:
            self.context.save_dashboard_user(self.user)
        except UserOutOfSync:
            return self.sync_user()

        self.request.stats.count('mobile_number_removed')
        message = _('Mobile phone number was successfully removed')
        return {
            'result': 'success',
            'message': get_localizer(self.request).translate(message),
        }
Example #48
0
def letter_status(request, user, nin):
    settings = request.registry.settings
    letter_url = settings.get('letter_service_url')
    state_url = urlappend(letter_url, 'get-state')
    data = {'eppn': user.eppn}
    response = requests.post(state_url, data=data)

    sent, result = False, 'error'
    msg = _('There was a problem with the letter service. '
            'Please try again later.')
    if response.status_code == 200:
        state = response.json()

        if 'letter_sent' in state:
            sent = True
            result = 'success'
            expires = datetime.utcfromtimestamp(int(state['letter_expires']))
            expires = expires.strftime('%Y-%m-%d')
            msg = _('A letter has already been sent to your official postal address. '
                    'The code enclosed will expire on ${expires}. '
                    'After that date you can restart the process if the letter was lost.',
                    mapping={'expires': expires})
        else:
            sent = False
            result = 'success'
            msg = _('When you click on the "Send" button a letter with a '
                    'verification code will be sent to your official postal address.')
            logger.info("Asking user {!r} if they want to send a letter.".format(user))
    else:
        logger.error('Error getting status from the letter service. Status code {!r}, msg "{}"'.format(
            response.status_code, response.text))
    return {
        'result': result,
        'message': get_localizer(request).translate(msg),
        'sent': sent
    }
Example #49
0
    def resend_code_action(self, index, post_data):
        self.user = get_session_user(self.request)
        data = self.user.to_dict().get(self.data_attribute, [])

        # Catch the unlikely event when the user have e.g. removed all entries
        # in a separate tab, or one in the middle and then tries to resend the
        # code for a non-existing entry.
        # This is an incomplete fix since it is better if we can get the list
        # from the UI and then check that the entry which the client want to
        # resend the code for corresponds to the same entry we get from
        # data[index].
        try:
            data_to_resend = data[index]
        except IndexError:
            log.warning('Index error in resend_code_action, user {!s}'.format(
                self.user))
            message = self.verify_messages['out_of_sync']
            return {
                'result': 'out_of_sync',
                'message': get_localizer(self.request).translate(message),
            }

        data_id = self.get_verification_data_id(data_to_resend)
        reference, code = new_verification_code(
            self.request,
            self.data_attribute,
            data_id,
            self.user,
            hasher=get_short_hash,
        )
        self.send_verification_code(data_id, reference, code)
        msg = self.verify_messages['new_code_sent']
        return {
            'result': 'success',
            'message': msg,
        }
Example #50
0
    def test_relative_time_format(self):
        request = testing.DummyRequest()
        locale = get_localizer(request)
        trans = locale.translate
        
        obj = self._make_obj()
        now = obj.utcnow()
        fut = obj.relative_time_format
        
        #Just now
        self.assertEqual(fut(now), u"Just now")

        #30 seconds ago - is this really a smart test? :)
        now = obj.utcnow()
        out = fut(now - timedelta(seconds=30))
        self.assertEqual(trans(out), u"30 seconds ago")

        #90 seconds ago - I.e. after 1 minute
        out = fut(now - timedelta(seconds=90))
        self.assertEqual(trans(out), u"1 minute ago")

        #5 minutes ago
        out = fut(now - timedelta(minutes=5))
        self.assertEqual(trans(out), u"5 minutes ago")

        #1 hour ago
        out = fut(now - timedelta(hours=1, seconds=1))
        self.assertEqual(trans(out), u"1 hour ago")

        #5 hours ago
        out = fut(now - timedelta(hours=6, seconds=1))
        self.assertEqual(trans(out), u"6 hours ago")
        
        #After about 1 day, return regular date time format
        date = obj.localize( datetime.strptime('1999-08-14 18:12', "%Y-%m-%d %H:%M") )
        self.assertEqual(fut(date), u'8/14/99, 6:12 PM')
Example #51
0
    def add_success_other(self, ninform):
        newnin = self.schema.serialize(ninform)
        newnin = newnin['norEduPersonNIN']

        newnin = normalize_nin(newnin)

        old_user = self.request.db.profiles.find_one({
            'norEduPersonNIN': newnin
            })

        if old_user:
            old_user = DashboardUser(data=old_user)
            retrieve_modified_ts(old_user, self.request.dashboard_userdb)
            old_user.nins.remove(newnin)
            self.context.save_dashboard_user(old_user)

        primary = False
        if self.user.nins.count == 0:
            primary = True
        newnin_obj = Nin(number=newnin, application='dashboard',
                verified=True, primary=primary)
        self.user.nins.add(newnin_obj)

        try:
            self.context.save_dashboard_user(self.user)
        except UserOutOfSync:
            message = _('Your user profile is out of sync. Please '
                        'reload the page and try again.')
        else:
            message = _('Your national identity number has been confirmed')
        # Save the state in the verifications collection
        save_as_verified(self.request, 'norEduPersonNIN', self.user, newnin)
        self.request.session.flash(
                get_localizer(self.request).translate(message),
                queue='forms')
        self.request.stats.count('nin_add_other')
Example #52
0
 def render(self):
     model = self.model
     request = self.request
     try:
         principal_id = request.params['id']
         role = request.params['role']
         roles = model.principal_roles
         if not principal_id in roles:
             model.principal_roles[principal_id] = [role]
             return u''
         existing = set(model.principal_roles[principal_id])
         existing.add(role)
         model.principal_roles[principal_id] = list(existing)
     except Exception, e:
         logger.error(e)
         localizer = get_localizer(self.request)
         message = localizer.translate(_(
             'cannot_add_role_for_principal',
             default="Can not add role '${role}' for principal '${pid}'"),
                                       mapping={
                                           'role': role,
                                           'pid': principal_id
                                       })
         ajax_message(self.request, message, 'error')
Example #53
0
def bytes_fmt(ctx, obj):
    req = ctx.get('req', None)
    i18n = ctx.get('i18n', None)
    loc = None
    if req:
        loc = get_localizer(req)
    suffix = _('B')

    if obj > 1073741824:
        obj = obj / 1073741824
        suffix = _('GiB')
    elif obj > 1048576:
        obj = obj / 1048576
        suffix = _('MiB')
    elif obj > 1024:
        obj = obj / 1024
        suffix = _('KiB')
    if loc:
        suffix = loc.translate(suffix)
    if i18n:
        obj = format_decimal(obj, '#,##0.###;-#', i18n)
    else:
        obj = format_decimal(obj, '#,##0.###;-#')
    return '%s %s' % (obj, suffix)
Example #54
0
def get_device_config_fancy_description(config, request=None, locale=None):

    if request != None:
        localizer = get_localizer(request)
    else:
        localizer = get_custom_localizer(locale)

    datatime = get_device_config_fancy_description_unit_value(config.datatime)
    sampletime = get_device_config_fancy_description_unit_value(
        config.sampletime)
    readtime = get_device_config_fancy_description_unit_value(config.readtime)
    parameters = {
        'datatime_val': datatime[0],
        'datatime_unit': localizer.translate(_(datatime[1],
                                               domain='Ondestan')),
        'sampletime_val': sampletime[0],
        'sampletime_unit':
        localizer.translate(_(sampletime[1], domain='Ondestan')),
        'readtime_val': readtime[0],
        'readtime_unit': localizer.translate(_(readtime[1], domain='Ondestan'))
    }

    return localizer.translate(
        _("fancy_config_description", domain='Ondestan', mapping=parameters))
Example #55
0
 def localizer(self):
     return i18n.get_localizer(get_current_request())
Example #56
0
def translate(ctx, text, *elements, **kw):
    request = ctx.get('request') or get_current_request()
    tsf = TranslationStringFactory('thinkhazard')
    localizer = get_localizer(request)
    return localizer.translate(tsf(text))
Example #57
0
def translator(msg):
    request = get_current_request()
    localizer = get_localizer(request)
    return localizer.translate(msg)
Example #58
0
 def _callFUT(self, request):
     from pyramid.i18n import get_localizer
     return get_localizer(request)
Example #59
0
 def __init__(self, context, request):
     self.context = context
     self.request = request
     self.localizer = get_localizer(request)
Example #60
0
 def __init__(self, request):
     self.request = request
     self.config = self.request.registry.settings
     self.localizer = get_localizer(self.request)