#/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2010-2011 Étienne Loks # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . # See the file COPYING for details. """ Administrative forms definitions: manage accounts and persons """ import datetime from django import forms from django.template import Context, RequestContext, loader from django.shortcuts import render_to_response from django.core import validators from django.core.mail import send_mail from django.core.exceptions import ObjectDoesNotExist from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from django.contrib.sites.models import Site from ishtar import settings import models import widgets from forms import Wizard, FinalForm, reverse_lazy, name_validator class PersonWizard(Wizard): model = models.Person class PersonFormSelection(forms.Form): form_label = _("Person") associated_models = {'pk':models.Person} currents = {'pk':models.Person} pk = forms.IntegerField(label=_("Person"), widget=widgets.JQueryAutoComplete(reverse_lazy('autocomplete-person'), associated_model=models.Person), validators=[models.valid_id(models.Person)]) class PersonForm(forms.Form): form_label = _("Identity") associated_models = {'attached_to':models.Organization, 'person_type':models.PersonType} title = forms.ChoiceField(label=_("Title"), choices=models.Person.TYPE) surname = forms.CharField(label=_(u"Surname"), max_length=20, validators=[name_validator]) name = forms.CharField(label=_(u"Name"), max_length=30, validators=[name_validator]) email = forms.CharField(label=_(u"Email"), max_length=40, required=False, validators=[validators.validate_email]) person_type = forms.ChoiceField(label=_("Person type"), choices=models.PersonType.get_types()) attached_to = forms.IntegerField(label=_("Current organization"), widget=widgets.JQueryAutoComplete(reverse_lazy('autocomplete-organization'), associated_model=models.Organization), validators=[models.valid_id(models.Organization)], required=False) is_author = forms.BooleanField(label=_(u"Is an author?"), required=False) in_charge_storage = forms.BooleanField(required=False, label=_(u"In charge of a storage?")) def __init__(self, *args, **kwargs): super(PersonForm, self).__init__(*args, **kwargs) self.fields['person_type'].choices = models.PersonType.get_types() person_creation_wizard = PersonWizard([ ('identity-person_creation', PersonForm), ('final-person_creation', FinalForm)], url_name='person_creation',) person_modification_wizard = PersonWizard([ ('selec-person_modification', PersonFormSelection), ('identity-person_modification', PersonForm), ('final-person_modification', FinalForm)], url_name='person_modification',) class AccountWizard(Wizard): model = models.Person def get_formated_datas(self, forms): datas = super(AccountWizard, self).get_formated_datas(forms) for form in forms: if not hasattr(form, "cleaned_data"): continue for key in form.cleaned_data: if key == 'hidden_password' and form.cleaned_data[key]: datas[-1][1].append((_("New password"), "*"*8)) return datas def done(self, request, storage, form_list, **kwargs): ''' Save the account ''' dct = {} for form in form_list: if not form.is_valid(): return self.render(request, storage, form) associated_models = hasattr(form, 'associated_models') and \ form.associated_models or {} if type(form.cleaned_data) == dict: for key in form.cleaned_data: if key == 'pk': continue value = form.cleaned_data[key] if key in associated_models and value: value = associated_models[key].objects.get(pk=value) dct[key] = value person = self.get_current_object(request, storage) if not person: return self.render(request, storage, form) for key in dct.keys(): if key.startswith('hidden_password'): dct['password'] = dct.pop(key) try: account = models.IshtarUser.objects.get(person=person) account.username = dct['username'] account.email = dct['email'] except ObjectDoesNotExist: now = datetime.datetime.now() account = models.IshtarUser(person=person, username=dct['username'], email=dct['email'], first_name=person.surname, last_name=person.name, is_staff=False, is_active=True, is_superuser=False, last_login=now, date_joined=now) if dct['password']: account.set_password(dct['password']) account.save() if 'send_password' in dct and dct['send_password'] and \ settings.ADMINS: site = Site.objects.get_current() app_name = site and ("Ishtar - " + site.name) \ or "Ishtar" context = Context({'login':dct['username'], 'password':dct['password'], 'app_name':app_name, 'site': site and site.domain or "" }) t = loader.get_template('account_activation_email.txt') msg = t.render(context) subject = _(u"[%(app_name)s] Account creation/modification") % { "app_name":app_name} send_mail(subject, msg, settings.ADMINS[0][1], [dct['email']], fail_silently=True) res = render_to_response('wizard_done.html', {}, context_instance=RequestContext(request)) return res def get_form(self, request, storage, step=None, data=None, files=None): """ Display the "Send email" field if necessary """ form = super(AccountWizard, self).get_form(request, storage, step, data, files) if not hasattr(form, 'is_hidden'): return form if self.session_get_value(request, storage, 'account-account_management', 'hidden_password'): form.is_hidden = False return form class AccountForm(forms.Form): form_label = _("Account") associated_models = {'pk':models.Person} currents = {'pk':models.Person} pk = forms.IntegerField(widget=forms.HiddenInput, required=False) username = forms.CharField(label=_(u"Account"), max_length=30) email = forms.CharField(label=_(u"Email"), max_length=75, validators=[validators.validate_email]) hidden_password = forms.CharField(label=_(u"New password"), max_length=128, widget=forms.PasswordInput, required=False, validators=[validators.MinLengthValidator(4)]) hidden_password_confirm = forms.CharField( label=_(u"New password (confirmation)"), max_length=128, widget=forms.PasswordInput, required=False) def __init__(self, *args, **kwargs): if 'initial' in kwargs and 'pk' in kwargs['initial']: try: person = models.Person.objects.get(pk=kwargs['initial']['pk']) account = models.IshtarUser.objects.get(person=person) kwargs['initial'].update({'username':account.username, 'email':account.email}) except ObjectDoesNotExist: pass return super(AccountForm, self).__init__(*args, **kwargs) def clean(self): cleaned_data = self.cleaned_data password = cleaned_data.get("hidden_password") if password and password != cleaned_data.get("hidden_password_confirm"): raise forms.ValidationError(_(u"Your password and confirmation " u"password do not match.")) if not cleaned_data.get("pk"): models.is_unique(User, 'username')(cleaned_data.get("username")) if not password: raise forms.ValidationError(_(u"You must provide a correct \ password.")) return cleaned_data class FinalAccountForm(forms.Form): final = True form_label = _("Confirm") send_password = forms.BooleanField(label=_(u"Send the new password by " u"email?"), required=False) def __init__(self, *args, **kwargs): self.is_hidden = True return super(FinalAccountForm, self).__init__(*args, **kwargs) account_management_wizard = AccountWizard([ ('selec-account_management', PersonFormSelection), ('account-account_management', AccountForm), ('final-account_management', FinalAccountForm)], url_name='account_management',)