Various changes:

* Updated *Settings* section
* Users can now change their first/last name (see #268)
* *admin* and *userprefs* templates moved to their respective application folders (see #245)
This commit is contained in:
Antoine Nguyen
2012-06-19 16:57:08 +02:00
parent 956f726373
commit 06268041c1
37 changed files with 176 additions and 167 deletions
+1 -1
View File
@@ -27,7 +27,7 @@ def domains(request):
if request.user.has_perm("admin.view_mailboxes"):
return HttpResponseRedirect(reverse(identities))
return HttpResponseRedirect(reverse(userprefs.views.preferences))
return HttpResponseRedirect(reverse(userprefs.views.index))
domains = request.user.get_domains()
squery = request.GET.get("searchquery", None)
+1 -1
View File
@@ -81,7 +81,7 @@ class SQLconnector(MBconnector):
return emails
class SQLlisting(EmailListing):
tpl = "amavis_quarantine/index2.html"
tpl = "amavis_quarantine/index.html"
tbltype = Qtable
deflocation = "listing/"
defcallback = "updatelisting"
+2 -22
View File
@@ -8,7 +8,7 @@ functionality into Postfix.
"""
from django.conf.urls.defaults import include
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _, ugettext_lazy, get_language
from django.utils.translation import ugettext as _, ugettext_lazy
from modoboa.lib import events, parameters
from modoboa.extensions import ModoExtension, exts_pool
from models import *
@@ -65,9 +65,7 @@ def menu(target, user):
return [
{"name" : "autoreply",
"url" : reverse(views.autoreply),
"label" : ugettext_lazy("Auto-reply message"),
"modal": True,
"modalcb" : "arform_cb"}
"label" : ugettext_lazy("Auto-reply message")}
]
@events.observe("CreateDomain")
@@ -113,21 +111,3 @@ def onModifyMailbox(mailbox, oldmailbox):
alias.autoreply_address = \
"%s@autoreply.%s" % (mailbox.full_address, mailbox.domain.name)
alias.save()
@events.observe("GetStaticContent")
def get_static_content(user):
if not user.has_mailbox:
return []
return """<script type="text/javascript">
function arform_cb() {
$('#id_untildate').datepicker({format: 'yyyy-mm-dd', language: '%s'});
$(".submit").one('click', function(e) {
simple_ajax_form_post(e, {
error_cb: arform_cb,
formid: "arform"
});
});
}
</script>
""" % get_language()
+2 -2
View File
@@ -13,9 +13,9 @@ class Alias(models.Model):
class ARmessage(models.Model):
mbox = models.ForeignKey(Mailbox)
subject = models.CharField(_('subject'), max_length=255,
help_text=_("The subject that will appear in sended emails"))
help_text=_("The subject that will appear in sent emails"))
content = models.TextField(_('content'),
help_text=_("The content that will appear in sended emails"))
help_text=_("The content that will appear in sent emails"))
enabled = models.BooleanField(_('enabled'),
help_text=_("Activate/Deactivate your auto reply"))
untildate = models.DateField()
@@ -0,0 +1,20 @@
{% extends "userprefs/section.html" %}
{% block html_head %}
<script type="text/javascript">
$(document).ready(function() {
$('#id_untildate').datepicker({format: 'yyyy-mm-dd', language: '{{ LANGUAGE_CODE }}'});
$(document).on("click", "#update", function(evt) {
evt.preventDefault();
var $form = $("#form");
$.post($form.attr("action"), $form.serialize(), function(data) {
if (data.status == "ok") {
$("body").notify("success", data.respmsg, 2000);
} else {
$("#form").html(data.content);
$('#id_untildate').datepicker({format: 'yyyy-mm-dd', language: '{{ LANGUAGE_CODE }}'});
}
});
});
});
</script>
{% endblock %}
+14 -15
View File
@@ -7,21 +7,14 @@ from django.contrib.auth.decorators \
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from modoboa.lib.webutils import _render, ajax_response
from modoboa.lib.webutils import _render, ajax_simple_response, ajax_response
from modoboa.lib.decorators import needs_mailbox
from forms import *
from models import *
@login_required
@needs_mailbox()
def autoreply(request, tplname="common/generic_modal_form.html"):
ctx = dict(
title=_("Auto-reply message"),
action=reverse(autoreply),
formid="arform",
action_label=_("Update"),
action_classes="submit"
)
def autoreply(request, tplname="userprefs/section.html"):
mb = Mailbox.objects.get(user=request.user.id)
try:
arm = ARmessage.objects.get(mbox=mb.id)
@@ -32,7 +25,6 @@ def autoreply(request, tplname="common/generic_modal_form.html"):
form = ARmessageForm(request.POST, instance=arm)
else:
form = ARmessageForm(request.POST)
error = None
if form.is_valid():
from modoboa import userprefs
@@ -40,15 +32,22 @@ def autoreply(request, tplname="common/generic_modal_form.html"):
arm.untildate = form.cleaned_data["untildate"]
arm.mbox = mb
arm.save()
messages.info(request, _("Auto reply message updated successfully."))
return ajax_response(request, url=reverse(userprefs.views.index))
ctx.update(form=form, error=error)
return ajax_response(request, status="ko", template=tplname, **ctx)
return ajax_simple_response(dict(
status="ok", respmsg=_("Auto reply message updated successfully.")
))
return ajax_response(request, status="ko", template="userprefs/form.html", form=form)
ctx = dict(
title=_("Auto-reply message"),
subtitle=_("Define an automatic message to send when you are unavailable"),
action=reverse(autoreply),
left_selection="autoreply",
)
form = ARmessageForm(instance=arm)
if arm is not None:
form.fields['untildate'].initial = arm.untildate
else:
form.fields['untildate'].initial = date.today()
ctx.update(form=form)
return _render(request, tplname, ctx)
return _render(request, "postfix_autoreply/autoreply.html", ctx)
+2 -2
View File
@@ -94,9 +94,9 @@ def render_form(form, tpl=None):
return ret
@register.simple_tag
def render_field(field):
def render_field(field, help_display_mode="tooltip"):
return render_to_string("common/generic_field.html", dict(
field=field
field=field, help_display_mode=help_display_mode
))
@register.simple_tag
+2 -1
View File
@@ -62,7 +62,8 @@ body {
}
.spaced select,
.spaced input[type="text"] {
.spaced input[type="text"],
.spaced input[type="password"] {
margin-bottom: 8px;
}
+1
View File
@@ -226,4 +226,5 @@ $(document).ready(function() {
$(document).ajaxSuccess(function(e, xhr, settings) { ajax_login_redirect(xhr); });
$(document).on('click', 'a[data-toggle="ajaxmodal"]', modalbox);
$(document).on('click', 'a[data-toggle="ajaxmodal-autowidth"]', modalbox_autowidth);
$(".help").popover();
});
+1 -2
View File
@@ -1,7 +1,6 @@
{% load i18n %}
<div class="control-group {% if field.errors %}error{% endif %}"{% if hidden %}style="display: none"{% endif %}>
{% if field.label %}<label class="control-label" for="id_{{ field.html_name }}">{{ field.label }}</label>{% endif %}
{% if field.help_text %}<a href="#" class="help pull-left" data-original-title="{% trans 'Help:' %} {{ field.label }}" data-content="{{ field.help_text }}" rel="popover">?</a>{% endif %}
{% if field.label %}<label class="control-label" for="id_{{ field.html_name }}">{{ field.label }}</label>{% endif %}{% if field.help_text %}<a href="#" class="help pull-left" data-original-title="{% trans 'Help:' %} {{ field.label }}" data-content="{{ field.help_text }}" rel="popover">?</a>{% endif %}
<div class="controls spaced">
{{ field }}{% if field.errors %}<p class="help-block">{% for error in field.errors %}{{ error|safe }}{% endfor %}</p>{% endif %}
</div>
-5
View File
@@ -27,8 +27,3 @@ if settings.DEBUG:
from django.conf.urls.static import static
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# urlpatterns += patterns(
# url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
# {'document_root': settings.MEDIA_ROOT, 'show_indexes' : True}),
# url(r'', include('django.contrib.staticfiles.urls')),
# )
-13
View File
@@ -9,16 +9,3 @@ parameters.register_user("LANG", type="list", deflt="en",
("es", "español"), ("fr", "français")],
help=ugettext_lazy("Prefered language to display pages"),
app="general")
@events.observe("GetStaticContent")
def get_static_content(user):
return """<script type="text/javascript">
function chpasswordform_cb() {
$(".submit").one('click', function(e) {
simple_ajax_form_post(e, {
formid: "chpasswordform",
error_cb: chpasswordform_cb
});
});
}
</script>"""
+28 -9
View File
@@ -1,5 +1,5 @@
from django import forms
from modoboa.admin.models import Domain, Mailbox
from modoboa.admin.models import User, Domain, Mailbox
from django.utils.translation import ugettext as _, ugettext_lazy
from modoboa.lib.emailutils import split_mailbox
from modoboa.lib import parameters
@@ -7,23 +7,33 @@ from modoboa.lib import parameters
class BadDestination(Exception):
pass
class ChangePasswordForm(forms.Form):
oldpassword = forms.CharField(label=ugettext_lazy("Old password"),
class ProfileForm(forms.ModelForm):
oldpassword = forms.CharField(label=ugettext_lazy("Old password"), required=False,
widget=forms.PasswordInput)
newpassword = forms.CharField(label=ugettext_lazy("New password"),
newpassword = forms.CharField(label=ugettext_lazy("New password"), required=False,
widget=forms.PasswordInput)
confirmation = forms.CharField(label=ugettext_lazy("Confirmation"),
confirmation = forms.CharField(label=ugettext_lazy("Confirmation"), required=False,
widget=forms.PasswordInput)
def __init__(self, target, *args, **kwargs):
super(ChangePasswordForm, self).__init__(*args, **kwargs)
self.target = target
class Meta:
model = User
fields = ("first_name", "last_name")
def __init__(self, update_password, *args, **kwargs):
super(ProfileForm, self).__init__(*args, **kwargs)
if not update_password:
del self.fields["oldpassword"]
del self.fields["newpassword"]
del self.fields["confirmation"]
def clean_oldpassword(self):
if self.cleaned_data["oldpassword"] == "":
return self.cleaned_data["oldpassword"]
if parameters.get_admin("AUTHENTICATION_TYPE", app="admin") != "local":
return self.cleaned_data["oldpassword"]
if not self.target.check_password(self.cleaned_data["oldpassword"]):
if not self.instance.check_password(self.cleaned_data["oldpassword"]):
raise forms.ValidationError(_("Old password mismatchs"))
return self.cleaned_data["oldpassword"]
@@ -32,6 +42,15 @@ class ChangePasswordForm(forms.Form):
raise forms.ValidationError(_("Passwords mismatch"))
return self.cleaned_data["confirmation"]
def save(self, commit=True):
user = super(ProfileForm, self).save(commit=False)
if commit:
if self.cleaned_data.has_key("confirmation") and \
self.cleaned_data["confirmation"] != "":
user.set_password(self.cleaned_data["confirmation"], self.cleaned_data["oldpassword"])
user.save()
return user
class ForwardForm(forms.Form):
dest = forms.CharField(label=ugettext_lazy("Destination(s)"), widget=forms.Textarea)
keepcopies = forms.BooleanField(label=ugettext_lazy("Keep local copies"), required=False)
+5
View File
@@ -0,0 +1,5 @@
{% load i18n libextras %}
{% render_form form %}
<div class="form-actions">
<button type="submit" class="btn btn-primary" id="update" name="update">{% trans 'Update' %}</button>
</div>
@@ -2,16 +2,6 @@
{% block pagetitle %}{% trans "Settings" %}{% endblock %}
{% block html_head %}
<script type="text/javascript">
function forwardform_cb() {
$(".submit").one('click', function(e) {
simple_ajax_form_post(e, {
formid: "forwardform",
error_cb: forwardform_cb,
reload_on_success: false
});
});
}
$(document).ready(function() {
$("#update").click(function(evt) {
evt.preventDefault();
@@ -28,11 +18,13 @@ $(document).ready(function() {
{% endblock %}
{% block leftcol %}<div class="well sidebar-nav">{% uprefs_menu left_selection user %}</div>{% endblock %}
{% block apparea %}
<h2>{% trans "Preferences" %} <small>{% trans "Customize Modoboa" %}</small></h2>
<hr>
<form class="form-horizontal" method="POST"
action="{% url modoboa.userprefs.views.savepreferences %}"
action="{% url modoboa.userprefs.views.preferences %}"
id="uparams_form">
{% include "common/parameters.html" %}
<hr>
<button type="submit" class="btn btn-primary" id="update" name="update">{% trans 'Save' %}</button>
</form>
<hr>
<a href="#" class="btn btn-primary" id="update" name="update">{% trans 'Save' %}</a>
{% endblock %}
@@ -0,0 +1,27 @@
{% extends "twocols.html" %}{% load i18n uprefs_extras libextras %}
{% block pagetitle %}{{ title }}{% endblock %}
{% block html_head %}
<script type="text/javascript">
$(document).ready(function() {
$(document).on("click", "#update", function(evt) {
evt.preventDefault();
var $form = $("#form");
$.post($form.attr("action"), $form.serialize(), function(data) {
if (data.status == "ok") {
$("body").notify("success", data.respmsg, 2000);
} else {
$("#form").html(data.content);
}
});
});
});
</script>
{% endblock %}
{% block leftcol %}<div class="well sidebar-nav">{% uprefs_menu left_selection user %}</div>{% endblock %}
{% block apparea %}
<h2>{{ title }} <small>{{ subtitle }}</small></h2>
<hr>
<form class="form-horizontal" method="POST" action="{{ action }}" id="form">
{% include "userprefs/form.html" %}
</form>
{% endblock %}
+11 -17
View File
@@ -1,6 +1,5 @@
from django import template
from django.template.loader import render_to_string
from django.template import Template, Context
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from modoboa import userprefs
@@ -12,21 +11,21 @@ register = template.Library()
@register.simple_tag
def uprefs_menu(selection, user):
entries = [
{"name" : "profile",
"url" : reverse("modoboa.userprefs.views.profile"),
"label" : _("Profile")},
{"name" : "preferences",
"url" : "",
"url" : reverse("modoboa.userprefs.views.preferences"),
"label" : _("Preferences")},
]
if user.group == 'SimpleUsers':
entries += [
{"name" : "setforwards",
"url" : reverse("modoboa.userprefs.views.setforward"),
"modal" : True,
"modalcb" : "forwardform_cb",
"label" : _("Forward")}
]
entries.insert(0, {"name" : "forward",
"url" : reverse("modoboa.userprefs.views.forward"),
"modalcb" : "forwardform_cb",
"label" : _("Forward")})
entries += events.raiseQueryEvent("UserMenuDisplay", "uprefs_menu", user)
entries = sorted(entries, key=lambda e: e["label"])
return render_to_string('common/menu.html', {
"entries" : entries,
"css" : "nav nav-list",
@@ -42,18 +41,13 @@ def user_menu(user, selection):
"img" : "icon-user icon-white",
"label" : user.fullname,
"menu" : [
{"name" : "changepwd",
"url" : reverse("modoboa.userprefs.views.changepassword"),
"img" : "icon-edit",
"label" : _("Change password"),
"modal" : True,
"modalcb" : "chpasswordform_cb"},
{"name" : "settings",
"img" : "icon-list",
"label" : _("Settings"),
"url" : reverse("modoboa.userprefs.views.preferences")}
"url" : reverse("modoboa.userprefs.views.index")}
]}
]
entries[0]["menu"] += \
events.raiseQueryEvent("UserMenuDisplay", "options_menu", user) \
+ [{"name" : "logout",
+2 -3
View File
@@ -3,7 +3,6 @@ from django.conf.urls.defaults import *
urlpatterns = patterns('modoboa.userprefs.views',
url(r'^$', 'index'),
(r'^preferences/$', 'preferences'),
(r'^preferences/save/$', 'savepreferences'),
(r'^changepassword/$', 'changepassword'),
(r'^setforward/$', 'setforward'),
(r'^profile/$', 'profile'),
(r'^forward/$', 'forward'),
)
+52 -61
View File
@@ -1,5 +1,7 @@
# coding: utf-8
import copy
from django.shortcuts import render
from django.template.loader import render_to_string
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators \
@@ -7,8 +9,7 @@ from django.contrib.auth.decorators \
from django.conf import settings
from django.utils.translation import ugettext as _
from modoboa.lib import parameters, events
from modoboa.lib.webutils import _render, _render_error, ajax_response, \
ajax_simple_response
from modoboa.lib.webutils import ajax_response, ajax_simple_response
from forms import *
from modoboa.admin.models import Mailbox, Alias
from modoboa.admin.lib import AdminError
@@ -16,55 +17,17 @@ from modoboa.auth.lib import encrypt
@login_required
def index(request):
return HttpResponseRedirect(reverse(preferences))
@login_required
def changepassword(request, tplname="common/generic_modal_form.html"):
res = events.raiseQueryEvent("PasswordChange", request.user)
if True in res:
from modoboa.lib.exceptions import ModoboaException
raise ModoboaException(_("Password change is disabled for this user"))
# ctx = dict(error=_("Password change is disabled for this user"))
# return _render_error(request, user_context=ctx)
ctx = dict(
title=_("Change password"),
formid="chpasswordform",
action=reverse(changepassword),
action_label=_("Update"),
action_classes="submit",
)
error = None
if request.method == "POST":
form = ChangePasswordForm(request.user, request.POST)
if form.is_valid():
try:
request.user.set_password(form.cleaned_data["confirmation"],
form.cleaned_data["oldpassword"])
except AdminError, e:
error = str(e)
else:
request.session["password"] = encrypt(request.POST["confirmation"])
request.user.save()
if error is None:
return ajax_response(request, respmsg=_("Password changed"))
ctx.update(form=form, error=error)
return ajax_response(request, status="ko", template=tplname, **ctx)
ctx.update(form=ChangePasswordForm(request.user))
return _render(request, tplname, ctx)
return HttpResponseRedirect(reverse(profile))
@login_required
@user_passes_test(lambda u: u.belongs_to_group('SimpleUsers'))
def setforward(request, tplname="common/generic_modal_form.html"):
def forward(request):
mb = request.user.mailbox_set.all()[0]
ctx = dict(
title=_("Define a forward"),
formid="forwardform",
action=reverse(setforward),
action_label=_("Update"),
action_classes="submit",
title=_("Forward"),
subtitle=_("Automatically forward emails to another address"),
action=reverse(forward),
left_selection="forward",
)
try:
al = Alias.objects.get(address=mb.address,
@@ -90,7 +53,7 @@ def setforward(request, tplname="common/generic_modal_form.html"):
except BadDestination, e:
error = str(e)
ctx.update(form=form, error=error)
return ajax_response(request, status="ko", template=tplname, **ctx)
return ajax_response(request, status="ko", template="userprefs/form.html", **ctx)
form = ForwardForm()
if al is not None:
@@ -102,10 +65,50 @@ def setforward(request, tplname="common/generic_modal_form.html"):
else:
form.fields["keepcopies"].initial = True
ctx.update(form=form)
return _render(request, tplname, ctx)
return render(request, "userprefs/section.html", ctx)
@login_required
def profile(request):
update_password = True
if True in events.raiseQueryEvent("PasswordChange", request.user):
update_password = False
if request.method == "POST":
form = ProfileForm(update_password, request.POST, instance=request.user)
if form.is_valid():
form.save()
if update_password:
request.session["password"] = encrypt(form.cleaned_data["confirmation"])
return ajax_simple_response(dict(
status="ok", respmsg=_("Profile updated")
))
return ajax_simple_response(dict(
status="ko",
content=render_to_string("userprefs/form.html", dict(form=form))
))
form = ProfileForm(update_password, instance=request.user)
return render(request, 'userprefs/section.html', {
"title" : _("Profile"),
"subtitle" : _("Update your personal information"),
"action" : reverse(profile),
"left_selection" : "profile",
"form" : form
})
@login_required
def preferences(request):
if request.method == "POST":
for pname, v in request.POST.iteritems():
if pname == "update":
continue
app, name = pname.split('.')
parameters.save_user(request.user, name, v, app=app)
return ajax_simple_response(dict(
status="ok", message=_("Preferences saved")
))
apps = sorted(parameters._params.keys())
gparams = []
for app in apps:
@@ -124,20 +127,8 @@ def preferences(request):
tmp["params"] += [newdef]
gparams += [tmp]
return _render(request, 'userprefs/preferences.html', {
return render(request, 'userprefs/preferences.html', {
"selection" : "user",
"left_selection" : "preferences",
"gparams" : gparams
})
@login_required
def savepreferences(request):
for pname, v in request.POST.iteritems():
if pname == "update":
continue
app, name = pname.split('.')
parameters.save_user(request.user, name, v, app=app)
return ajax_simple_response(dict(
status="ok", message=_("Preferences saved")
))