コード例 #1
0
 def send_notification(self, mutation, template=None):
     if not template:
         template = 'subscriptions/subscription-notification.mail.html'
     cc = []
     if self.event.owner.canonical_full_email:
         # may be None when <Onbekend>
         cc.append(self.event.owner.canonical_full_email)
     if self.invited:
         cc.append(self.inviter.canonical_full_email)
     # See RFC5322 for a description of the References and In-Reply-To
     # headers:
     # https://tools.ietf.org/html/rfc5322#section-3.6.4
     # They are used here for proper threading in mail applications.
     render_then_email(template,
                       self.user,
                       ctx={
                           'mutation': mutation,
                           'subscription': self,
                           'event': self.event,
                       },
                       cc=cc,
                       reply_to=self.event.owner.canonical_full_email,
                       headers={
                           'In-Reply-To': self.event.messageId,
                           'References': self.event.messageId,
                       })
コード例 #2
0
ファイル: check-email.py プロジェクト: karpenoktem/kninfra
def check_email():
    comm_ids = [_id(x) for x in Es.by_name('comms').get_bearers()]
    list_ids = [_id(x) for x in Es.by_name('lists-opted').get_bearers()]
    for m in args_to_users(sys.argv[1:]):
        rels = m.get_related()
        rels = sorted(rels, key=lambda x: Es.entity_humanName(x['with']))
        comms = []
        lists = []
        others = []
        for rel in rels:
            if Es.relation_is_virtual(rel):
                continue
            if _id(rel['with']) in comm_ids:
                comms.append(rel)
            elif _id(rel['with']) in list_ids:
                lists.append(rel)
            else:
                others.append(rel)
        print(m.name)
        render_then_email('leden/check-email.mail.html',
                          m.email,
                          {'u': m,
                           'comms': comms,
                           'lists': lists,
                           'others': others},
                          from_email='*****@*****.**')
コード例 #3
0
ファイル: check-email.py プロジェクト: yorickvP/kninfra
def check_email():
    comm_ids = [_id(x) for x in Es.by_name('comms').get_bearers()]
    list_ids = [_id(x) for x in Es.by_name('lists-opted').get_bearers()]
    for m in args_to_users(sys.argv[1:]):
        rels = m.get_related()
        rels = sorted(rels, key=lambda x: Es.entity_humanName(x['with']))
        comms = []
        lists = []
        others = []
        for rel in rels:
            if Es.relation_is_virtual(rel):
                continue
            if _id(rel['with']) in comm_ids:
                comms.append(rel)
            elif _id(rel['with']) in list_ids:
                lists.append(rel)
            else:
                others.append(rel)
        print(m.name)
        render_then_email('leden/check-email.mail.html',
                          m.email, {
                              'u': m,
                              'comms': comms,
                              'lists': lists,
                              'others': others
                          },
                          from_email='*****@*****.**')
コード例 #4
0
ファイル: cron.py プロジェクト: yorickvP/kninfra
def send_informacie_digest():
    """ Sends the notifications for the informacie. """
    ntfs = Es.pop_all_informacie_notifications()
    if not ntfs:
        return
    render_then_email('leden/informacie-digest.mail.html',
                      Es.by_name('informacie').canonical_full_email,
                      {'ntfs': ntfs})
コード例 #5
0
ファイル: cron.py プロジェクト: karpenoktem/kninfra
def send_informacie_digest():
    """ Sends the notifications for the informacie. """
    ntfs = Es.pop_all_informacie_notifications()
    if not ntfs:
        return
    render_then_email('leden/informacie-digest.mail.html',
                      Es.by_name('informacie').canonical_full_email, {
                          'ntfs': ntfs})
コード例 #6
0
ファイル: views.py プロジェクト: mrngm/kninfra
def fiscus_debtmail(request):

    if 'fiscus' not in request.user.cached_groups_names:
        raise PermissionDenied

    data = dict([(n, {'debt': Decimal(debt)}) for (n, debt) in
                 giedo.fin_get_debitors()])

    for user in Es.users():
        name = user.full_name
        if name in data:
            data[name]['user'] = user

    ctx = {
        'BASE_URL': settings.BASE_URL,
        'quaestor': fin.quaestor(),
        'account_number': settings.BANK_ACCOUNT_NUMBER,
        'account_holder': settings.BANK_ACCOUNT_HOLDER,
    }

    if request.method == 'POST' and 'debitor' in request.POST:
        users_to_email = request.POST.getlist('debitor')
        for user_name in users_to_email:
            user = Es.by_name(user_name)

            ctx['first_name'] = user.first_name,
            ctx['debt'] = data[user.full_name]['debt']

            try:
                render_then_email("leden/debitor.mail.txt",
                                  to=user, ctx=ctx,
                                  cc=[],  # ADD penningmeester
                                  from_email=ctx['quaestor']['email'],
                                  reply_to=ctx['quaestor']['email'])
                messages.info(
                    request,
                    _("Email gestuurd naar %s.") %
                    user_name)
            except Exception as e:
                messages.error(request,
                               _("Email naar %(user)s faalde: %(e)s.") %
                               {'user': user_name, 'e': repr(e)})

    # get a sample of the email that will be sent for the quaestor's review.
    email = ""
    email_template = get_template('leden/debitor.mail.txt')

    ctx['first_name'] = '< Naam >'
    ctx['debt'] = '< Debet >'
    context = Context(ctx)
    for node in email_template:
        if isinstance(node, BlockNode) and node.name == "plain":
            email = node.render(context)
            break

    return render_to_response('leden/fiscus_debtmail.html',
                              {'data': data, 'email': email},
                              context_instance=RequestContext(request))
コード例 #7
0
ファイル: views.py プロジェクト: Blackeel/kninfra
def fiscus_debtmail(request):

    if 'fiscus' not in request.user.cached_groups_names:
        raise PermissionDenied

    data = dict([(n, {
        'debt': Decimal(debt)
    }) for (n, debt) in giedo.fin_get_debitors()])

    for user in Es.users():
        name = user.full_name
        if name in data:
            data[name]['user'] = user

    ctx = {
        'BASE_URL': settings.BASE_URL,
        'quaestor': fin.quaestor(),
        'account_number': settings.BANK_ACCOUNT_NUMBER,
        'account_holder': settings.BANK_ACCOUNT_HOLDER,
    }

    if request.method == 'POST' and 'debitor' in request.POST:
        users_to_email = request.POST.getlist('debitor')
        for user_name in users_to_email:
            user = Es.by_name(user_name)

            ctx['first_name'] = user.first_name
            ctx['debt'] = data[user.full_name]['debt']

            try:
                render_then_email(
                    'leden/debitor.mail.html',
                    to=user,
                    ctx=ctx,
                    cc=[],  # ADD penningmeester
                    from_email=ctx['quaestor']['email'],
                    reply_to=ctx['quaestor']['email'])
                messages.info(request,
                              _("Email gestuurd naar %s.") % user_name)
            except Exception as e:
                messages.error(
                    request,
                    _("Email naar %(user)s faalde: %(e)s.") % {
                        'user': user_name,
                        'e': repr(e)
                    })

    # get a sample of the email that will be sent for the quaestor's review.
    ctx['first_name'] = '< Naam >'
    ctx['debt'] = '< Debet >'
    email = render_message('leden/debitor.mail.html', ctx)['html']

    return render(request, 'leden/fiscus_debtmail.html', {
        'data': data,
        'email': email
    })
コード例 #8
0
ファイル: views.py プロジェクト: karpenoktem/kninfra
def user_reset_password(request, _id):
    if not "secretariaat" in request.user.cached_groups_names:
        raise PermissionDenied
    u = Es.by_id(_id).as_user()
    if not u.is_active:
        raise ValueError, _("Gebruiker is niet geactiveerd")
    pwd = pseudo_randstr()
    u.set_password(pwd)
    giedo.change_password(str(u.name), pwd, pwd)
    render_then_email("leden/reset-password.mail.txt", u, {"user": u, "password": pwd})
    messages.info(request, _("Wachtwoord gereset!"))
    return redirect_to_referer(request)
コード例 #9
0
ファイル: views.py プロジェクト: Soyweiser/kninfra
def user_reset_password(request, _id):
    if not 'secretariaat' in request.user.cached_groups_names:
        raise PermissionDenied
    u = Es.by_id(_id).as_user()
    pwd = pseudo_randstr()
    u.set_password(pwd)
    giedo.change_password(str(u.name), pwd, pwd)
    render_then_email("leden/reset-password.mail.txt",
                        u.canonical_full_email, {
                            'user': u,
                            'password': pwd})
    request.user.push_message("Wachtwoord gereset!")
    return redirect_to_referer(request)
コード例 #10
0
ファイル: views.py プロジェクト: Jille/kninfra
def user_reset_password(request, _id):
    if not 'secretariaat' in request.user.cached_groups_names:
        raise PermissionDenied
    u = Es.by_id(_id).as_user()
    pwd = pseudo_randstr()
    u.set_password(pwd)
    giedo.change_password(str(u.name), pwd, pwd)
    render_then_email("leden/reset-password.mail.txt",
                        u.canonical_full_email, {
                            'user': u,
                            'password': pwd})
    request.user.push_message("Wachtwoord gereset!")
    return redirect_to_referer(request)
コード例 #11
0
ファイル: views.py プロジェクト: karpenoktem/kninfra
def _deactivate_mm(name, user, record, moderators):
    giedo.maillist_deactivate_moderation(name)
    if record:
        record.delete()
    if user:
        render_then_email('moderation/disabled-by.mail.txt',
                          moderators.canonical_full_email, {
                              'name': name,
                              'user': user})
    else:
        render_then_email('moderation/timed-out.mail.txt',
                          moderators.canonical_full_email, {
                              'name': name})
コード例 #12
0
def _deactivate_mm(name, user, record, moderators):
    giedo.maillist_deactivate_moderation(name)
    if record:
        record.delete()
    if user:
        render_then_email('moderation/disabled-by.mail.txt',
                          moderators.canonical_full_email, {
                              'name': name,
                              'user': user
                          })
    else:
        render_then_email('moderation/timed-out.mail.txt',
                          moderators.canonical_full_email, {'name': name})
コード例 #13
0
ファイル: views.py プロジェクト: karpenoktem/kninfra
def _renew_mm(name, user, record, moderators):
    now = datetime.datetime.now()
    until = now + settings.MOD_RENEW_INTERVAL
    if record is None:
        record = mod_Es.ModerationRecord({'list': name})
    record.by = user
    record.at = now
    record.save()
    render_then_email('moderation/extended.mail.txt',
                      moderators.canonical_full_email, {
                          'name': name,
                          'user': user,
                          'until': until})
    return record
コード例 #14
0
ファイル: views.py プロジェクト: Blackeel/kninfra
def user_reset_password(request, _id):
    if 'secretariaat' not in request.user.cached_groups_names:
        raise PermissionDenied
    u = Es.by_id(_id).as_user()
    if not u.is_active:
        raise ValueError(_("Gebruiker is niet geactiveerd"))
    pwd = pseudo_randstr()
    u.set_password(pwd)
    giedo.change_password(str(u.name), pwd, pwd)
    render_then_email("leden/reset-password.mail.html", u, {
        'user': u,
        'password': pwd
    })
    messages.info(request, _("Wachtwoord gereset!"))
    return redirect_to_referer(request)
コード例 #15
0
ファイル: views.py プロジェクト: Soyweiser/kninfra
def note_add(request):
    if not 'secretariaat' in request.user.cached_groups_names:
        raise PermissionDenied
    if 'on' not in request.POST or 'note' not in request.POST:
        raise ValueError, "missing `on' or `note'"
    on = Es.by_id(_id(request.POST['on']))
    if on is None:
        raise Http404
    on.add_note(request.POST['note'], request.user)
    render_then_email("leden/new-note.mail.txt",
                        Es.by_name('secretariaat').canonical_full_email, {
                            'user': request.user,
                            'note': request.POST['note'],
                            'on': on})
    return redirect_to_referer(request)
コード例 #16
0
ファイル: views.py プロジェクト: Jille/kninfra
def note_add(request):
    if not 'secretariaat' in request.user.cached_groups_names:
        raise PermissionDenied
    if 'on' not in request.POST or 'note' not in request.POST:
        raise ValueError, "missing `on' or `note'"
    on = Es.by_id(_id(request.POST['on']))
    if on is None:
        raise Http404
    on.add_note(request.POST['note'], request.user)
    render_then_email("leden/new-note.mail.txt",
                        Es.by_name('secretariaat').canonical_full_email, {
                            'user': request.user,
                            'note': request.POST['note'],
                            'on': on})
    return redirect_to_referer(request)
コード例 #17
0
ファイル: views.py プロジェクト: karpenoktem/kninfra
def note_add(request):
    if not "secretariaat" in request.user.cached_groups_names:
        raise PermissionDenied
    if "on" not in request.POST or "note" not in request.POST:
        raise ValueError, _("missende `on' of `note'")
    on = Es.by_id(_id(request.POST["on"]))
    if on is None:
        raise Http404
    on.add_note(request.POST["note"], request.user)
    render_then_email(
        "leden/new-note.mail.txt",
        Es.by_name("secretariaat").canonical_full_email,
        {"user": request.user, "note": request.POST["note"], "on": on},
    )
    return redirect_to_referer(request)
コード例 #18
0
def _renew_mm(name, user, record, moderators):
    now = datetime.datetime.now()
    until = now + settings.MOD_RENEW_INTERVAL
    if record is None:
        record = mod_Es.ModerationRecord({'list': name})
    record.by = user
    record.at = now
    record.save()
    render_then_email('moderation/extended.mail.txt',
                      moderators.canonical_full_email, {
                          'name': name,
                          'user': user,
                          'until': until
                      })
    return record
コード例 #19
0
ファイル: views.py プロジェクト: mrngm/kninfra
def note_add(request):
    if 'secretariaat' not in request.user.cached_groups_names:
        raise PermissionDenied
    if 'on' not in request.POST or 'note' not in request.POST:
        raise ValueError(_("missende `on' of `note'"))
    on = Es.by_id(_id(request.POST['on']))
    if on is None:
        raise Http404
    note = on.add_note(request.POST['note'], request.user)
    render_then_email("leden/new-note.mail.html",
                      Es.by_name('secretariaat').canonical_full_email, {
                          'user': request.user,
                          'note': request.POST['note'],
                          'on': on},
                      headers={
                          'In-Reply-To': note.messageId,
                          'References': note.messageId})
    return redirect_to_referer(request)
コード例 #20
0
ファイル: views.py プロジェクト: Jille/kninfra
def _activate_mm(ml, name, user, record, moderators):
    if ml.emergency:
        return
    ml.emergency = True
    ml.Save()
    now = datetime.datetime.now()
    until = now + settings.MOD_RENEW_INTERVAL
    if record is None:
        record = mod_Es.ModerationRecord({'list':name})
    record.by = user
    record.at = now
    record.save()
    render_then_email('moderation/enabled.mail.txt',
            moderators.canonical_full_email, {
                'name': name,
                'user': user,
                'until': until})
    return record
コード例 #21
0
ファイル: views.py プロジェクト: Jille/kninfra
def _deactivate_mm(ml, name, user, record, moderators):
    if not ml.emergency:
        return
    ml.emergency = False
    if not record is None:
        record.delete()
    for id in ml.GetHeldMessageIds():
        ml.HandleRequest(id, mm_cfg.APPROVE)
    ml.Save()
    if user is None:
        render_then_email('moderation/timed-out.mail.txt',
                moderators.canonical_full_email, {
                    'name': name})
    else:
        render_then_email('moderation/disabled-by.mail.txt',
                moderators.canonical_full_email, {
                    'name': name,
                    'user': user})
コード例 #22
0
def close_note(data, request):
    """ Wraps Note.close()

          >> {action:"close_note", id: "5038b134d4080073f410fafd"}
          << {ok: true}
        ( << {ok: false, error: "Note already closed"} ) """
    if not 'secretariaat' in request.user.cached_groups_names:
        return {'ok': False, 'error': 'Permission denied'}
    note = Es.note_by_id(_id(data.get('id')))
    if note is None:
        return {'ok': False, 'error': 'Note not found'}
    if not note.open:
        return {'ok': False, 'error': 'Note already closed'}
    note.close(_id(request.user))
    render_then_email('leden/note-closed.mail.txt',
                      Es.by_name('secretariaat').canonical_full_email,
                      {'note': note})
    return {'ok': True}
コード例 #23
0
def _deactivate_mm(ml, name, user, record, moderators):
    if not ml.emergency:
        return
    ml.emergency = False
    if not record is None:
        record.delete()
    for id in ml.GetHeldMessageIds():
        ml.HandleRequest(id, mm_cfg.APPROVE)
    ml.Save()
    if user is None:
        render_then_email('moderation/timed-out.mail.txt',
                          moderators.canonical_full_email, {'name': name})
    else:
        render_then_email('moderation/disabled-by.mail.txt',
                          moderators.canonical_full_email, {
                              'name': name,
                              'user': user
                          })
コード例 #24
0
ファイル: api.py プロジェクト: Jille/kninfra
def close_note(data, request):
    """ Wraps Note.close()

          >> {action:"close_note", id: "5038b134d4080073f410fafd"}
          << {ok: true}
        ( << {ok: false, error: "Note already closed"} ) """
    if not 'secretariaat' in request.user.cached_groups_names:
        return {'ok': False, 'error': 'Permission denied'}
    note = Es.note_by_id(_id(data.get('id'))) 
    if note is None:
        return {'ok': False, 'error': 'Note not found'}
    if not note.open:
        return {'ok': False, 'error': 'Note already closed'}
    note.close(_id(request.user))
    render_then_email('leden/note-closed.mail.txt',
                        Es.by_name('secretariaat').canonical_full_email, {
                            'note': note})
    return {'ok': True}
コード例 #25
0
def _activate_mm(ml, name, user, record, moderators):
    if ml.emergency:
        return
    ml.emergency = True
    ml.Save()
    now = datetime.datetime.now()
    until = now + settings.MOD_RENEW_INTERVAL
    if record is None:
        record = mod_Es.ModerationRecord({'list': name})
    record.by = user
    record.at = now
    record.save()
    render_then_email('moderation/enabled.mail.txt',
                      moderators.canonical_full_email, {
                          'name': name,
                          'user': user,
                          'until': until
                      })
    return record
コード例 #26
0
ファイル: views.py プロジェクト: Blackeel/kninfra
def note_add(request):
    if 'secretariaat' not in request.user.cached_groups_names:
        raise PermissionDenied
    if 'on' not in request.POST or 'note' not in request.POST:
        raise ValueError(_("missende `on' of `note'"))
    on = Es.by_id(_id(request.POST['on']))
    if on is None:
        raise Http404
    note = on.add_note(request.POST['note'], request.user)
    render_then_email("leden/new-note.mail.html",
                      Es.by_name('secretariaat').canonical_full_email, {
                          'user': request.user,
                          'note': request.POST['note'],
                          'on': on
                      },
                      headers={
                          'In-Reply-To': note.messageId,
                          'References': note.messageId
                      })
    return redirect_to_referer(request)
コード例 #27
0
ファイル: api.py プロジェクト: Blackeel/kninfra
def delete_note(data, request):
    """ Wraps Note.delete()

          >> {action:"delete_note", id: "5038b134d4080073f410fafd"}
          << {ok: true}
        ( << {ok: false, error: "Note not found"} ) """
    if 'secretariaat' not in request.user.cached_groups_names:
        return {'ok': False, 'error': 'Permission denied'}
    note = Es.note_by_id(_id(data.get('id')))
    if note is None:
        return {'ok': False, 'error': 'Note not found'}
    note.delete()
    render_then_email('leden/note-deleted.mail.html',
                      Es.by_name('secretariaat').canonical_full_email,
                      {'note': note, 'closed_by': request.user},
                      headers={
                              'In-Reply-To': note.messageId,
                              'References': note.messageId,
                      })
    return {'ok': True}
コード例 #28
0
ファイル: entities.py プロジェクト: aykevl/kninfra
 def send_notification(self, mutation, template=None):
     if not template:
         template = 'subscriptions/subscription-notification.mail.html'
     cc = [self.event.owner.canonical_full_email]
     if self.invited:
         cc.append(self.inviter.canonical_full_email)
     # See RFC5322 for a description of the References and In-Reply-To
     # headers:
     # https://tools.ietf.org/html/rfc5322#section-3.6.4
     # They are used here for proper threading in mail applications.
     render_then_email(template, self.user,
                       ctx={
                           'mutation': mutation,
                           'subscription': self,
                           'event': self.event,
                       },
                       cc=cc,
                       reply_to=self.event.owner.canonical_full_email,
                       headers={
                           'In-Reply-To': self.event.messageId,
                           'References': self.event.messageId,
                       })
コード例 #29
0
ファイル: views.py プロジェクト: karpenoktem/kninfra
def event_new_or_edit(request, edit=None):
    superuser = subscr_Es.is_superuser(request.user)
    if edit is not None:
        e = subscr_Es.event_by_name(edit)
        if e is None:
            raise Http404
        if not superuser and not request.user.is_related_with(e.owner) and \
                not _id(e.owner) == request.user._id:
            raise PermissionDenied
    AddEventForm = get_add_event_form(request.user, superuser, bool(edit))
    if request.method == 'POST':
        form = AddEventForm(request.POST)
        if form.is_valid():
            fd = form.cleaned_data
            # The superuser may do everything, and when you yourself are the
            # owner that's always okay too.
            if not superuser and fd['owner'] != request.user.id:
                # Check some more constraints.
                owner = Es.by_id(fd['owner'])
                if not request.user.is_related_with(owner):
                    raise PermissionDenied(
                        _('Gebruiker niet verwant met eigenaar')
                    )
                if not subscr_Es.may_set_owner(request.user, owner):
                    raise PermissionDenied(_('Mag deze eigenaar niet kiezen'))
            d = {
                'date': date_to_dt(fd['date']),
                'owner': _id(fd['owner']),
                'description': fd['description'],
                'description_html': kn.utils.markdown.parser.convert(
                    fd['description']),
                'has_public_subscriptions': fd['has_public_subscriptions'],
                'may_unsubscribe': fd['may_unsubscribe'],
                'humanName': fd['humanName'],
                'createdBy': request.user._id,
                'cost': str(fd['cost']),
                'max_subscriptions': fd['max_subscriptions'],
                'is_official': superuser}
            if edit is None:
                name = fd['name']
                # If not secretariaat, then prefix name with the username
                if fd['owner'] == request.user.id:
                    prefix = str(request.user.name) + '-'
                else:
                    prefix = str(Es.by_id(fd['owner']).name) + '-'
                if (not superuser and not name.startswith(prefix) and (
                        edit is None or e.name != name)):
                    name = prefix + name
                d['name'] = name
                d['is_open'] = True  # default for new events
                e = subscr_Es.Event(d)
            else:
                e.update(d, request.user, save=False)
            e.save()
            render_then_email(
                'subscriptions/' +
                ('event-edited' if edit else 'new-event') + '.mail.html',
                Es.by_name('secretariaat').canonical_full_email, {
                    'event': e,
                    'user': request.user
                },
                headers={
                    'In-Reply-To': e.messageId,
                    'References': e.messageId,
                },
            )
            return HttpResponseRedirect(
                reverse('event-detail', args=(e.name,)))
    elif edit is None:
        form = AddEventForm()
    else:
        d = e._data
        form = AddEventForm(d)
    ctx = {'form': form,
           'edit': edit}
    return render(request, 'subscriptions/event_new_or_edit.html', ctx)
コード例 #30
0
ファイル: views.py プロジェクト: Jille/kninfra
def event_new_or_edit(request, edit=None):
    superuser = '******' in request.user.cached_groups_names
    if edit is not None:
        e = subscr_Es.event_by_name(edit)
        if e is None:
            raise Http404
        if not superuser and not request.user.is_related_with(e.owner) and \
                not _id(e.owner) == request.user._id:
            raise PermissionDenied
    AddEventForm = get_add_event_form(request.user, superuser)
    if request.method == 'POST':
        form = AddEventForm(request.POST)
        if form.is_valid():
            fd = form.cleaned_data
            if not superuser and not request.user.is_related_with(
                    fd['owner']) and not fd['owner'] == request.user.id:
                raise PermissionDenied
            name = fd['name']
            # If not secretariaat, then prefix name with the username
            if fd['owner'] == request.user.id:
                prefix = str(request.user.name) + '-'
            else:
                prefix = str(Es.by_id(fd['owner']).name) + '-'
            if (not superuser and not name.startswith(prefix) and (
                    edit is None or e.name != name)):
                name = prefix + name
            d = {
                'date': date_to_dt(fd['date']),
                'owner': _id(fd['owner']),
                'description': fd['description'],
                'description_html': kn.utils.markdown.parser.convert(
                                                fd['description']),
                'mailBody': fd['mailBody'],
                'subscribedByOtherMailBody': fd['subscribedByOtherMailBody'],
                'confirmationMailBody': fd['confirmationMailBody'],
                'everyone_can_subscribe_others':
                        fd['everyone_can_subscribe_others'],
                'has_public_subscriptions': fd['has_public_subscriptions'],
                'humanName': fd['humanName'],
                'createdBy': request.user._id,
                'name': name,
                'cost': str(fd['cost']),
                'is_open': True,
                'is_official': superuser}
            if edit is None:
                e = subscr_Es.Event(d)
            else:
                e._data.update(d)
            e.save()
            render_then_email('subscriptions/' +
                    ('event-edited' if edit else 'new-event') + '.mail.txt',
                    Es.by_name('secretariaat').canonical_full_email, {
                        'event': e,
                        'user': request.user})
            return HttpResponseRedirect(reverse('event-detail', args=(e.name,)))
    elif edit is None:
        form = AddEventForm()
    else:
        d = e._data
        form = AddEventForm(d)
    ctx = {'form': form,
           'edit': edit}
    return render_to_response('subscriptions/event_new_or_edit.html', ctx,
            context_instance=RequestContext(request))
コード例 #31
0
ファイル: views.py プロジェクト: Jille/kninfra
def event_new_or_edit(request, edit=None):
    superuser = '******' in request.user.cached_groups_names
    if edit is not None:
        e = subscr_Es.event_by_name(edit)
        if e is None:
            raise Http404
        if not superuser and not request.user.is_related_with(e.owner) and \
                not _id(e.owner) == request.user._id:
            raise PermissionDenied
    AddEventForm = get_add_event_form(request.user, superuser)
    if request.method == 'POST':
        form = AddEventForm(request.POST)
        if form.is_valid():
            fd = form.cleaned_data
            if not superuser and not request.user.is_related_with(
                    fd['owner']) and not fd['owner'] == request.user.id:
                raise PermissionDenied
            name = fd['name']
            # If not secretariaat, then prefix name with the username
            if fd['owner'] == request.user.id:
                prefix = str(request.user.name) + '-'
            else:
                prefix = str(Es.by_id(fd['owner']).name) + '-'
            if (not superuser and not name.startswith(prefix)
                    and (edit is None or e.name != name)):
                name = prefix + name
            d = {
                'date':
                date_to_dt(fd['date']),
                'owner':
                _id(fd['owner']),
                'description':
                fd['description'],
                'description_html':
                kn.utils.markdown.parser.convert(fd['description']),
                'mailBody':
                fd['mailBody'],
                'subscribedByOtherMailBody':
                fd['subscribedByOtherMailBody'],
                'confirmationMailBody':
                fd['confirmationMailBody'],
                'everyone_can_subscribe_others':
                fd['everyone_can_subscribe_others'],
                'has_public_subscriptions':
                fd['has_public_subscriptions'],
                'humanName':
                fd['humanName'],
                'createdBy':
                request.user._id,
                'name':
                name,
                'cost':
                str(fd['cost']),
                'is_open':
                True,
                'is_official':
                superuser
            }
            if edit is None:
                e = subscr_Es.Event(d)
            else:
                e._data.update(d)
            e.save()
            render_then_email(
                'subscriptions/' + ('event-edited' if edit else 'new-event') +
                '.mail.txt',
                Es.by_name('secretariaat').canonical_full_email, {
                    'event': e,
                    'user': request.user
                })
            return HttpResponseRedirect(
                reverse('event-detail', args=(e.name, )))
    elif edit is None:
        form = AddEventForm()
    else:
        d = e._data
        form = AddEventForm(d)
    ctx = {'form': form, 'edit': edit}
    return render_to_response('subscriptions/event_new_or_edit.html',
                              ctx,
                              context_instance=RequestContext(request))
コード例 #32
0
ファイル: views.py プロジェクト: Blackeel/kninfra
def secr_add_user(request):
    if 'secretariaat' not in request.user.cached_groups_names:
        raise PermissionDenied
    if request.method == 'POST':
        form = AddUserForm(request.POST)
        if form.is_valid():
            fd = form.cleaned_data
            # First, create the entity.
            u = Es.User({
                'types': ['user'],
                'names': [fd['username']],
                'humanNames': [{
                    'human':
                    fd['first_name'] + ' ' + fd['last_name']
                }],
                'person': {
                    'titles': [],
                    'nick': fd['first_name'],
                    'given': None,
                    'family': fd['last_name'],
                    'dateOfBirth': date_to_dt(fd['dateOfBirth'])
                },
                'email':
                fd['email'],
                'address': {
                    'street': fd['addr_street'],
                    'number': fd['addr_number'],
                    'zip': fd['addr_zip'],
                    'city': fd['addr_city']
                },
                'telephone':
                fd['telephone'],
                'studies': [{
                    'institute': _id(fd['study_inst']),
                    'study': _id(fd['study']),
                    'from': DT_MIN,
                    'until': DT_MAX,
                    'number': fd['study_number']
                }],
                'is_active':
                True,
                'password':
                None
            })
            logging.info("Added user %s" % fd['username'])
            u.save()
            # Then, add the relations.
            groups = ['leden']
            if fd['incasso']:
                groups.append('incasso')
            else:
                groups.append('geen-incasso')
            for group in groups:
                Es.add_relation(u,
                                Es.id_by_name(group, use_cache=True),
                                _from=date_to_dt(fd['dateJoined']))
            for l in fd['addToList']:
                Es.add_relation(u,
                                Es.id_by_name(l, use_cache=True),
                                _from=now())
            # Let giedo synch. to create the e-mail adresses, unix user, etc.
            # TODO use giedo.async() and let giedo send the welcome e-mail
            giedo.sync()
            # Create a new password and send it via e-mail
            pwd = pseudo_randstr()
            u.set_password(pwd)
            giedo.change_password(str(u.name), pwd, pwd)
            render_then_email("leden/set-password.mail.html", u, {
                'user': u,
                'password': pwd
            })
            # Send the welcome e-mail
            render_then_email("leden/welcome.mail.html", u, {'u': u})
            Es.notify_informacie('adduser', request.user, entity=u._id)
            return HttpResponseRedirect(
                reverse('user-by-name', args=(fd['username'], )))
    else:
        form = AddUserForm()
    return render(request, 'leden/secr_add_user.html', {'form': form})
コード例 #33
0
def event_new_or_edit(request, edit=None):
    superuser = subscr_Es.is_superuser(request.user)
    if edit is not None:
        e = subscr_Es.event_by_name(edit)
        if e is None:
            raise Http404
        if not superuser and not request.user.is_related_with(e.owner) and \
                not _id(e.owner) == request.user._id:
            raise PermissionDenied
    AddEventForm = get_add_event_form(request.user, superuser, bool(edit))
    if request.method == 'POST':
        form = AddEventForm(request.POST)
        if form.is_valid():
            fd = form.cleaned_data
            # The superuser may do everything, and when you yourself are the
            # owner that's always okay too.
            if not superuser and fd['owner'] != request.user.id:
                # Check some more constraints.
                owner = Es.by_id(fd['owner'])
                if not request.user.is_related_with(owner):
                    raise PermissionDenied(
                        _('Gebruiker niet verwant met eigenaar'))
                if not subscr_Es.may_set_owner(request.user, owner):
                    raise PermissionDenied(_('Mag deze eigenaar niet kiezen'))
            d = {
                'date':
                date_to_dt(fd['date']),
                'owner':
                _id(fd['owner']),
                'description':
                fd['description'],
                'description_html':
                kn.utils.markdown.parser.convert(fd['description']),
                'has_public_subscriptions':
                fd['has_public_subscriptions'],
                'may_unsubscribe':
                fd['may_unsubscribe'],
                'humanName':
                fd['humanName'],
                'createdBy':
                request.user._id,
                'cost':
                str(fd['cost']),
                'max_subscriptions':
                fd['max_subscriptions'],
                'is_official':
                superuser
            }
            if edit is None:
                name = fd['name']
                # If not secretariaat, then prefix name with the username
                if fd['owner'] == request.user.id:
                    prefix = str(request.user.name) + '-'
                else:
                    prefix = str(Es.by_id(fd['owner']).name) + '-'
                if (not superuser and not name.startswith(prefix)
                        and (edit is None or e.name != name)):
                    name = prefix + name
                d['name'] = name
                d['is_open'] = True  # default for new events
                e = subscr_Es.Event(d)
            else:
                e.update(d, request.user, save=False)
            e.save()
            render_then_email(
                'subscriptions/' + ('event-edited' if edit else 'new-event') +
                '.mail.html',
                Es.by_name('secretariaat').canonical_full_email,
                {
                    'event': e,
                    'user': request.user
                },
                headers={
                    'In-Reply-To': e.messageId,
                    'References': e.messageId,
                },
            )
            return HttpResponseRedirect(
                reverse('event-detail', args=(e.name, )))
    elif edit is None:
        form = AddEventForm()
    else:
        d = e._data
        form = AddEventForm(d)
    ctx = {'form': form, 'edit': edit}
    return render(request, 'subscriptions/event_new_or_edit.html', ctx)
コード例 #34
0
ファイル: views.py プロジェクト: karpenoktem/kninfra
def secr_add_user(request):
    if "secretariaat" not in request.user.cached_groups_names:
        raise PermissionDenied
    if request.method == "POST":
        form = AddUserForm(request.POST)
        if form.is_valid():
            fd = form.cleaned_data
            # First, create the entity.
            u = Es.User(
                {
                    "types": ["user"],
                    "names": [fd["username"]],
                    "humanNames": [{"human": fd["first_name"] + " " + fd["last_name"]}],
                    "person": {
                        "titles": [],
                        "nick": fd["first_name"],
                        "given": None,
                        "family": fd["last_name"],
                        "gender": fd["gender"],
                        "dateOfBirth": date_to_dt(fd["dateOfBirth"]),
                    },
                    "emailAddresses": [{"email": fd["email"], "from": DT_MIN, "until": DT_MAX}],
                    "addresses": [
                        {
                            "street": fd["addr_street"],
                            "number": fd["addr_number"],
                            "zip": fd["addr_zip"],
                            "city": fd["addr_city"],
                            "from": DT_MIN,
                            "until": DT_MAX,
                        }
                    ],
                    "telephones": [{"number": fd["telephone"], "from": DT_MIN, "until": DT_MAX}],
                    "studies": [
                        {
                            "institute": _id(fd["study_inst"]),
                            "study": _id(fd["study"]),
                            "from": DT_MIN,
                            "until": DT_MAX,
                            "number": fd["study_number"],
                        }
                    ],
                    "is_active": True,
                    "password": None,
                }
            )
            logging.info("Added user %s" % fd["username"])
            u.save()
            # Then, add the relations.
            groups = ["leden"]
            groups.append({"m": "mannen", "v": "vrouwen"}.get(fd["gender"]))
            if fd["incasso"]:
                groups.append("incasso")
            else:
                groups.append("geen-incasso")
            for group in groups:
                Es.add_relation(u, Es.id_by_name(group, use_cache=True), _from=date_to_dt(fd["dateJoined"]))
            for l in fd["addToList"]:
                Es.add_relation(u, Es.id_by_name(l, use_cache=True), _from=now())
            # Let giedo synch. to create the e-mail adresses, unix user, etc.
            # TODO use giedo.async() and let giedo send the welcome e-mail
            giedo.sync()
            # Create a new password and send it via e-mail
            pwd = pseudo_randstr()
            u.set_password(pwd)
            giedo.change_password(str(u.name), pwd, pwd)
            render_then_email("leden/set-password.mail.txt", u, {"user": u, "password": pwd})
            # Send the welcome e-mail
            render_then_email("leden/welcome.mail.txt", u, {"u": u})
            Es.notify_informacie("adduser", request.user, entity=u._id)
            return HttpResponseRedirect(reverse("user-by-name", args=(fd["username"],)))
    else:
        form = AddUserForm()
    return render_to_response("leden/secr_add_user.html", {"form": form}, context_instance=RequestContext(request))
コード例 #35
0
ファイル: views.py プロジェクト: mrngm/kninfra
def secr_add_user(request):
    if 'secretariaat' not in request.user.cached_groups_names:
        raise PermissionDenied
    if request.method == 'POST':
        form = AddUserForm(request.POST)
        if form.is_valid():
            fd = form.cleaned_data
            # First, create the entity.
            u = Es.User({
                'types': ['user'],
                'names': [fd['username']],
                'humanNames': [{'human': fd['first_name'] + ' ' +
                                fd['last_name']}],
                'person': {
                    'titles': [],
                    'nick': fd['first_name'],
                    'given': None,
                    'family': fd['last_name'],
                    'dateOfBirth': date_to_dt(
                        fd['dateOfBirth'])
                },
                'emailAddresses': [
                    {'email': fd['email'],
                     'from': DT_MIN,
                     'until': DT_MAX}],
                'addresses': [
                    {'street': fd['addr_street'],
                     'number': fd['addr_number'],
                     'zip': fd['addr_zip'],
                     'city': fd['addr_city'],
                     'from': DT_MIN,
                     'until': DT_MAX}],
                'telephones': [
                    {'number': fd['telephone'],
                     'from': DT_MIN,
                     'until': DT_MAX}],
                'studies': [
                    {'institute': _id(fd['study_inst']),
                     'study': _id(fd['study']),
                     'from': DT_MIN,
                     'until': DT_MAX,
                     'number': fd['study_number']}],
                'is_active': True,
                'password': None
            })
            logging.info("Added user %s" % fd['username'])
            u.save()
            # Then, add the relations.
            groups = ['leden']
            if fd['incasso']:
                groups.append('incasso')
            else:
                groups.append('geen-incasso')
            for group in groups:
                Es.add_relation(u, Es.id_by_name(group,
                                                 use_cache=True),
                                _from=date_to_dt(fd['dateJoined']))
            for l in fd['addToList']:
                Es.add_relation(u, Es.id_by_name(l, use_cache=True),
                                _from=now())
            # Let giedo synch. to create the e-mail adresses, unix user, etc.
            # TODO use giedo.async() and let giedo send the welcome e-mail
            giedo.sync()
            # Create a new password and send it via e-mail
            pwd = pseudo_randstr()
            u.set_password(pwd)
            giedo.change_password(str(u.name), pwd, pwd)
            render_then_email("leden/set-password.mail.txt", u, {
                'user': u,
                'password': pwd})
            # Send the welcome e-mail
            render_then_email("leden/welcome.mail.txt", u, {
                'u': u})
            Es.notify_informacie('adduser', request.user, entity=u._id)
            return HttpResponseRedirect(reverse('user-by-name',
                                                args=(fd['username'],)))
    else:
        form = AddUserForm()
    return render_to_response('leden/secr_add_user.html',
                              {'form': form},
                              context_instance=RequestContext(request))