예제 #1
0
파일: forms.py 프로젝트: seanchen/pcp
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')

        self.helper = RostiFormHelper()
        self.helper.form_class = 'dyn_refresh'

        super(FormStatic, self).__init__(*args, **kwargs)

        layout = Layout()
        if 'script' in self.fields:
            layout.fields.append(
                PrependedText('script', '<div class="ajax_refresh" data-el="script" data-target="%s"><span class="status"></span></div>' % reverse('refresh_wsgi')),
            )

        if 'virtualenv' in self.fields:
            layout.fields.append(
                PrependedText('virtualenv', '<div class="ajax_refresh" data-el="virtualenv" data-target="%s"><span class="status"></span></div>' % reverse('refresh_venv')),
            )

        if 'document_root' in self.fields:
            layout.fields.append(
                PrependedText('document_root', '<div class="ajax_refresh" data-el="document_root" data-target="%s"><span class="status"></span></div>' % reverse('refresh_userdirs')),
            )

        self.helper.add_layout(layout)


        if 'document_root' in self.fields:
            user_dirs = user_directories(user=self.user, use_cache=True)
            dirs_choices = [("", _("Not selected"))] + [(x, x) for x in
                                                               user_dirs]
            self.fields['document_root'].widget.choices = dirs_choices
예제 #2
0
파일: views.py 프로젝트: a740122/pcp
def changePasswdBox(request, eid):
    eid = int(eid)
    u = request.session.get('switched_user', request.user)
    superuser = request.user

    try:
        e = Email.objects.get(domain__in=u.email_domain_set.all(), id=eid)
    except Email.DoesNotExist:
        e = None

    if request.method == 'POST':
        form = EmailPasswd(request.POST, instance=e)
        if form.is_valid():
            email = form.save(commit=False)
            email.password = crypt.crypt(form.cleaned_data["password1"], email.login*2)
            email.save()
            messages.add_message(request, messages.SUCCESS, _('Password has been changed'))
            return HttpResponseRedirect(reverse("mailbox_list"))
    else:
        form = EmailPasswd(instance=e)

    helper = RostiFormHelper()
    helper.form_action = reverse("wsgiadmin.emails.views.changePasswdBox", args=[e.id])

    return render_to_response('universal.html',
            {
            "form": form,
            "form_helper": helper,
            "title": _("Change password for e-mail box"),
            "u": u,
            "superuser": superuser,
            "menu_active": "emails",
            },
        context_instance=RequestContext(request)
    )
예제 #3
0
파일: forms.py 프로젝트: yedpodtrzitko/pcp
class FormStatic(ModelForm):
    class Meta:
        model = UserSite
        fields = ('main_domain', 'misc_domains', 'document_root',)
        widgets = {
            'document_root': forms.Select
        }

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')

        self.helper = RostiFormHelper()
        self.helper.form_class = 'dyn_refresh'

        super(FormStatic, self).__init__(*args, **kwargs)

        layout = Layout()
        if 'script' in self.fields:
            layout.fields.append(
                PrependedText('script', '<div class="ajax_refresh" data-el="script" data-target="%s"><span class="status"></span></div>' % reverse('refresh_wsgi')),
            )

        if 'virtualenv' in self.fields:
            layout.fields.append(
                PrependedText('virtualenv', '<div class="ajax_refresh" data-el="virtualenv" data-target="%s"><span class="status"></span></div>' % reverse('refresh_venv')),
            )

        if 'document_root' in self.fields:
            layout.fields.append(
                PrependedText('document_root', '<div class="ajax_refresh" data-el="document_root" data-target="%s"><span class="status"></span></div>' % reverse('refresh_userdirs')),
            )

        self.helper.add_layout(layout)


        if 'document_root' in self.fields:
            user_dirs = user_directories(user=self.user, use_cache=True)
            dirs_choices = [("", _("Not selected"))] + [(x, x) for x in
                                                               user_dirs]
            self.fields['document_root'].widget.choices = dirs_choices


    def clean_document_root(self):
        if ".." in self.cleaned_data["document_root"] or\
           "~" in self.cleaned_data["document_root"]:
            raise forms.ValidationError(
                _("This field hasn't to contain .. and ~"))
        return self.cleaned_data["document_root"]

    def clean(self):
        data = self.cleaned_data
        main_domain = data['main_domain']
        if 'misc_domains' in data and main_domain in data['misc_domains']:
            raise forms.ValidationError(
                _("Main domain cannot be listed also as misc. domain"))
        return data
예제 #4
0
파일: views.py 프로젝트: ghostmod/pcp
def add(request, dbtype):
    """
    DB create
    """
    u = request.session.get('switched_user', request.user)
    superuser = request.user

    form_class = MysqlForm if dbtype == 'mysql' else PgsqlForm

    if request.method == 'POST':
        form = form_class(request.POST)
        orig_dbname = form.data['dbname']
        old = form.data
        form.data._mutable = True
        form.data['dbname'] = "%s_%s" % (u.parms.prefix(), form.data['dbname'])
        form.data._mutable = old

        if form.is_valid():
            db_obj = form.save(commit=False)
            db_obj.owner = u
            db_obj.save()

            if dbtype == 'mysql':
                mr = MySQLRequest(u, u.parms.mysql_machine)
            elif dbtype == 'pgsql':
                mr = PostgreSQLRequest(u, u.parms.pgsql_machine)
            else:
                return HttpResponseBadRequest(_('Unknown database type'))
            mr.add_db(db_obj.dbname, form.cleaned_data["password1"])

            return HttpResponseRedirect(reverse("db_list", kwargs=dict(dbtype=dbtype)))
        else:
            form.data['dbname'] = orig_dbname
    else:
        form = form_class()
        form.owner = u


    helper = RostiFormHelper()

    helper.form_action = reverse("db_add", kwargs=dict(dbtype=dbtype))

    return render_to_response('universal.html',
            {
            "form": form,
            "form_helper": RostiFormHelper(),
            "title": _("Create %s database" % dbtype),
            "u": u,
            "superuser": superuser,
            "menu_active": "dbs",
            },
        context_instance=RequestContext(request)
    )
예제 #5
0
파일: views.py 프로젝트: seanchen/pcp
def add(request, dbtype):
    """
    DB create
    """
    u = request.session.get('switched_user', request.user)
    superuser = request.user

    form_class = MysqlForm if dbtype == 'mysql' else PgsqlForm

    if request.method == 'POST':
        form = form_class(request.POST)
        orig_dbname = form.data['dbname']
        old = form.data
        form.data._mutable = True
        form.data['dbname'] = "%s_%s" % (u.parms.prefix(), form.data['dbname'])
        form.data._mutable = old

        if form.is_valid():
            db_obj = form.save(commit=False)
            db_obj.owner = u
            db_obj.save()

            if dbtype == 'mysql':
                mr = MySQLRequest(u, u.parms.mysql_machine)
            elif dbtype == 'pgsql':
                mr = PostgreSQLRequest(u, u.parms.pgsql_machine)
            else:
                return HttpResponseBadRequest(_('Unknown database type'))
            mr.add_db(db_obj.dbname, form.cleaned_data["password1"])

            return HttpResponseRedirect(
                reverse("db_list", kwargs=dict(dbtype=dbtype)))
        else:
            form.data['dbname'] = orig_dbname
    else:
        form = form_class()
        form.owner = u

    helper = RostiFormHelper()

    helper.form_action = reverse("db_add", kwargs=dict(dbtype=dbtype))

    return render_to_response('universal.html', {
        "form": form,
        "form_helper": RostiFormHelper(),
        "title": _("Create %s database" % dbtype),
        "u": u,
        "superuser": superuser,
        "menu_active": "dbs",
    },
                              context_instance=RequestContext(request))
예제 #6
0
def ftp_upsert(request, ftp_id=0):
    u = request.session.get('switched_user', request.user)
    superuser = request.user

    try:
        ftp = Ftp.objects.get(pk=ftp_id)
    except Ftp.DoesNotExist:
        ftp = None

    if request.method == 'POST':
        if ftp:
            form = FTPUpdateForm(request.POST, user=u, instance=ftp)
        else:
            form = FTPForm(request.POST, user=u)

        if form.is_valid():
            iftp = form.save(commit=False)
            iftp.uid = u.parms.uid
            iftp.gid = u.parms.gid
            iftp.owner = u
            if "password1" in form.cleaned_data:
                iftp.password = crypt.crypt(form.cleaned_data["password1"],
                                            iftp.owner.username)
            iftp.save()

            messages.add_message(
                request, messages.SUCCESS,
                _('FTP account has been %s') %
                _("changed") if ftp else _("added"))
            return HttpResponseRedirect(reverse("ftp_list"))
    else:
        if ftp:
            form = FTPUpdateForm(user=u, instance=ftp)
        else:
            form = FTPForm(user=u)

    helper = RostiFormHelper()
    helper.form_action = reverse("ftp_upsert", kwargs={'ftp_id': ftp_id})

    return render_to_response(
        'universal.html', {
            "form": form,
            "form_helper": RostiFormHelper(),
            "title": _("FTP account"),
            "note": [_("* Username will be prefixed with `%s_`" % u.username)],
            "u": u,
            "superuser": superuser,
            "menu_active": "ftps",
        },
        context_instance=RequestContext(request))
예제 #7
0
파일: views.py 프로젝트: seanchen/pcp
def passwd_ftp(request, ftp_id):
    iftp = get_object_or_404(Ftp, id=ftp_id)
    u = request.session.get('switched_user', request.user)
    superuser = request.user

    if request.method == 'POST':
        form = PassCheckForm(request.POST)
        
        if form.is_valid():
            if iftp.owner != u:
                return HttpResponseForbidden(ugettext("Unable to edit chosen account"))

            iftp.password = crypt.crypt(form.cleaned_data["password1"], iftp.owner.username)
            iftp.save()
            #iftp.password = crypt.crypt(form.cleaned_data["password1"], iftp.owner.username)
            messages.add_message(request, messages.SUCCESS, _('Password has been changed'))
            return HttpResponseRedirect(reverse("ftp_list"))
    else:
        form = PassCheckForm()

    return render_to_response('universal.html',
            {
            "form": form,
            "form_helper": RostiFormHelper(),
            "title": _("Edit FTP account"),
            "submit": _("Save changes"),
            "action": reverse("ftp_passwd", kwargs={'ftp_id': ftp_id}),
            "u": u,
            "superuser": superuser,
            "menu_active": "ftps",
            },
        context_instance=RequestContext(request)
    )
예제 #8
0
class AppParametersForm(forms.Form):
    helper = RostiFormHelper()
    this_app = None

    domains = forms.CharField(
        max_length=1024,
        required=False,
        label=_("Domains"),
        help_text=
        _("There is no relation to DNS or Domains menu. Write your domains separated by spaces."
          ))
    password = forms.CharField(max_length=128,
                               required=False,
                               label=_("Password"),
                               widget=forms.PasswordInput,
                               help_text=_("For SSH/SFTP/FTP"))

    def clean_domains(self):
        domains = self.cleaned_data["domains"].split()
        used_domains = []
        for x in [
                app.domains_list for app in App.objects.all()
                if not self.this_app or self.this_app.id != app.id
        ]:
            used_domains += x
        for domain in domains:
            if not re.match("^[0-9a-z_\.\-\*]*$", domain):
                raise forms.ValidationError(
                    _("Each domain has to be in this format: ^[0-9a-z_\.\-]*$")
                )
            if domain in used_domains:
                raise forms.ValidationError(
                    _("One of your domain is already used. (%s)" % domain))

        return self.cleaned_data["domains"]
예제 #9
0
class FtpAccessForm(ModelForm):
    helper = RostiFormHelper()

    password = forms.CharField(label=_("Password"))
    directory = forms.ChoiceField(label=_("Directory"))

    def __init__(self, *args, **kwargs):
        self.ftpaccess = None
        super(FtpAccessForm, self).__init__(*args, **kwargs)

    class Meta:
        model = FtpAccess
        fields = ["username", "directory"]
        widgets = {
            'hash': forms.PasswordInput,
        }

    def clean_username(self):
        if not re.match("^[0-9a-zA-Z_]*$", self.cleaned_data["username"]):
            raise forms.ValidationError(
                _("Username has to be in this format: ^[0-9a-zA-Z_]*$"))
        if self.app.ftpaccess_set.filter(
                username=self.cleaned_data["username"]).count() and (
                    not self.ftpaccess or
                    self.ftpaccess.username != self.cleaned_data["username"]):
            raise forms.ValidationError(_("This username is already used"))
        return self.cleaned_data["username"]
예제 #10
0
파일: forms.py 프로젝트: simhaonline/pcp
    def __init__(self, *args, **kwargs):
        if 'dbname' in kwargs:
            self.dbname = kwargs.pop('dbname')

        super(MysqlForm, self).__init__(*args, **kwargs)

        self.helper = RostiFormHelper()
예제 #11
0
class AppForm(ModelForm):
    helper = RostiFormHelper()

    class Meta:
        model = App
        fields = ("name", "domains", "core_server")

    def __init__(self, *args, **kwargs):
        super(AppForm, self).__init__(*args, **kwargs)
        self.fields["domains"].help_text = _(
            "On these domains your app will listen. There is no relation to DNS. Write your domains separated by spaces. For example: mydomain.cz www.mydomain.cz"
        )

    def clean_domains(self):
        domains = self.cleaned_data["domains"].split()
        used_domains = []
        for x in [app.domains_list for app in App.objects.all()]:
            used_domains += x
        for domain in domains:
            if not re.match("^[0-9a-z_\.\-]*$", domain):
                raise forms.ValidationError(
                    _("Each domain has to be in this format: ^[0-9a-z_\.\-]*$")
                )
            if domain in used_domains:
                raise forms.ValidationError(
                    _("One of your domain is already used. (%s)" % domain))
        return self.cleaned_data["domains"]

    def clean_name(self):
        if not re.match("^[0-9a-zA-Z_\ \.\-]*$", self.cleaned_data["name"]):
            raise forms.ValidationError(
                _("App name has to be in this format: ^[0-9a-zA-Z_\ \.\-]*$"))
        if self.user.app_set.filter(name=self.cleaned_data["name"]):
            raise forms.ValidationError(_("This name is already used"))
        return self.cleaned_data["name"]
예제 #12
0
파일: views.py 프로젝트: ghostmod/pcp
def change_passwd(request):
    u = request.session.get('switched_user', request.user)
    superuser = request.user

    if request.method == 'POST':
        form = PassCheckForm(request.POST)
        if form.is_valid():
            u.set_password(form.cleaned_data["password1"])
            u.save()

            messages.add_message(request, messages.SUCCESS,
                                 _('Password has been changed'))
            return HttpResponseRedirect(
                reverse("wsgiadmin.useradmin.views.change_passwd"))
    else:
        form = PassCheckForm()

    return render_to_response(
        'universal.html', {
            "form": form,
            "form_helper": RostiFormHelper(),
            "title": _("Change password for this administration"),
            "u": u,
            "superuser": superuser,
            "menu_active": "settings",
        },
        context_instance=RequestContext(request))
예제 #13
0
파일: forms.py 프로젝트: yedpodtrzitko/pcp
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')

        self.helper = RostiFormHelper()
        self.helper.form_class = 'dyn_refresh'

        super(FormStatic, self).__init__(*args, **kwargs)

        layout = Layout()
        if 'script' in self.fields:
            layout.fields.append(
                PrependedText('script', '<div class="ajax_refresh" data-el="script" data-target="%s"><span class="status"></span></div>' % reverse('refresh_wsgi')),
            )

        if 'virtualenv' in self.fields:
            layout.fields.append(
                PrependedText('virtualenv', '<div class="ajax_refresh" data-el="virtualenv" data-target="%s"><span class="status"></span></div>' % reverse('refresh_venv')),
            )

        if 'document_root' in self.fields:
            layout.fields.append(
                PrependedText('document_root', '<div class="ajax_refresh" data-el="document_root" data-target="%s"><span class="status"></span></div>' % reverse('refresh_userdirs')),
            )

        self.helper.add_layout(layout)


        if 'document_root' in self.fields:
            user_dirs = user_directories(user=self.user, use_cache=True)
            dirs_choices = [("", _("Not selected"))] + [(x, x) for x in
                                                               user_dirs]
            self.fields['document_root'].widget.choices = dirs_choices
예제 #14
0
파일: views.py 프로젝트: masterdubs/pcp
def ftp_upsert(request, ftp_id=0):
    u = request.session.get('switched_user', request.user)
    superuser = request.user

    try:
        ftp = Ftp.objects.get(pk=ftp_id)
    except Ftp.DoesNotExist:
        ftp = None

    if request.method == 'POST':
        if ftp:
            form = FTPUpdateForm(request.POST, user=u, instance=ftp)
        else:
            form = FTPForm(request.POST, user=u)

        if form.is_valid():
            iftp = form.save(commit=False)
            iftp.uid = u.parms.uid
            iftp.gid = u.parms.gid
            iftp.owner = u
            if "password1" in form.cleaned_data: iftp.password = crypt.crypt(form.cleaned_data["password1"], iftp.owner.username)
            iftp.save()

            messages.add_message(request, messages.SUCCESS, _('FTP account has been %s') % _("changed") if ftp else _("added"))
            return HttpResponseRedirect(reverse("ftp_list"))
    else:
        if ftp:
            form = FTPUpdateForm(user=u, instance=ftp)
        else:
            form = FTPForm(user=u)

    helper = RostiFormHelper()
    helper.form_action = reverse("ftp_upsert", kwargs={'ftp_id': ftp_id})

    return render_to_response('universal.html',
            {
            "form": form,
            "form_helper": RostiFormHelper(),
            "title": _("FTP account"),
            "note": [_("* Username will be prefixed with `%s_`" % u.username)],
            "u": u,
            "superuser": superuser,
            "menu_active": "ftps",
            },
        context_instance=RequestContext(request)
    )
예제 #15
0
class DbFormPasswd(ModelForm):
    helper = RostiFormHelper()

    class Meta:
        model = Db
        fields = ["password", "comment"]
        widgets = {
            'password': forms.PasswordInput,
        }
예제 #16
0
class DomainForm(ModelForm):
    helper = RostiFormHelper()

    class Meta:
        model = Domain
        fields = ["name", "rname", "ttl"]

    def clean_user(self):
        return None
예제 #17
0
파일: forms.py 프로젝트: simhaonline/pcp
class VirtForm(forms.ModelForm):
    helper = RostiFormHelper()

    def __init__(self, *args, **kwargs):
        super(VirtForm, self).__init__(*args, **kwargs)
        self.fields["server"].queryset = get_virt_servers(self.app_type)

    class Meta:
        fields = ("name", )
        model = VirtMachine
예제 #18
0
class AppParmetersForm(forms.Form):
    helper = RostiFormHelper()

    domains = forms.CharField(
        max_length=512,
        required=False,
        label=_("Domains"),
        help_text=
        _("Domain is not necessary anymore (in native apps). There is no relation to DNS or Domains menu."
          ))
예제 #19
0
class AppForm(ModelForm):
    helper = RostiFormHelper()

    class Meta:
        model = App
        fields = ("name", "domains")

    def clean_name(self):
        if not re.match("^[0-9a-zA-Z_]*$", self.cleaned_data["name"]):
            raise forms.ValidationError(
                _("App name has to be in this format: ^[0-9a-zA-Z_]*$"))
        return self.cleaned_data["name"]
예제 #20
0
def changeRedirect(request, rid):
    u = request.session.get('switched_user', request.user)
    superuser = request.user
    rid = int(rid)

    r = get_object_or_404(EmailRedirect, id=rid)
    if r.domain.user != u:
        return HttpResponseForbidden(ugettext("Forbidden operation"))

    domains = [(x.name, x.name) for x in u.email_domain_set.filter()]
    if request.method == 'POST':
        form = FormRedirect(request.POST, instance=r)
        form.fields["_domain"].choices = domains
        if form.is_valid():
            fredirect = form.save(commit=False)
            fredirect.domain = get_object_or_404(
                u.email_domain_set, name=form.cleaned_data["_domain"])
            fredirect.save()
            messages.add_message(request, messages.SUCCESS,
                                 _('Redirect has been changed'))
            return HttpResponseRedirect(reverse("redirect_list"))
    else:
        form = FormRedirect(instance=r)
        form.fields["_domain"].choices = domains

    helper = RostiFormHelper()
    helper.form_action = reverse("wsgiadmin.emails.views.changeRedirect",
                                 args=[rid])

    return render_to_response('universal.html', {
        "form": form,
        "form_helper": helper,
        "title": _("Modify email alias"),
        "submit": _("Save changes"),
        "u": u,
        "superuser": superuser,
        "menu_active": "emails",
    },
                              context_instance=RequestContext(request))
예제 #21
0
파일: forms.py 프로젝트: simhaonline/pcp
class FormDomain(forms.models.ModelForm):
    helper = RostiFormHelper()

    class Meta:
        model = Domain
        fields = ["name", "mail", "dns", "ipv4", "ipv6", "enable"]

    def clean_domain(self):
        if not re.search("[a-z0-9\-\.]*\.[a-z]{2,5}",
                         self.cleaned_data["domain"]):
            raise forms.ValidationError(_("Domain is not in valid format"))

        return self.cleaned_data["domain"]
예제 #22
0
파일: views.py 프로젝트: a740122/pcp
def changeRedirect(request, rid):
    u = request.session.get('switched_user', request.user)
    superuser = request.user
    rid = int(rid)

    r = get_object_or_404(EmailRedirect, id=rid)
    if r.domain.user != u:
        return HttpResponseForbidden(ugettext("Forbidden operation"))

    domains = [(x.name, x.name) for x in u.email_domain_set.filter()]
    if request.method == 'POST':
        form = FormRedirect(request.POST, instance=r)
        form.fields["_domain"].choices = domains
        if form.is_valid():
            fredirect = form.save(commit=False)
            fredirect.domain = get_object_or_404(u.email_domain_set, name=form.cleaned_data["_domain"])
            fredirect.save()
            messages.add_message(request, messages.SUCCESS, _('Redirect has been changed'))
            return HttpResponseRedirect(reverse("redirect_list"))
    else:
        form = FormRedirect(instance=r)
        form.fields["_domain"].choices = domains

    helper = RostiFormHelper()
    helper.form_action = reverse("wsgiadmin.emails.views.changeRedirect", args=[rid])

    return render_to_response('universal.html',
            {
            "form": form,
            "form_helper": helper,
            "title": _("Modify email alias"),
            "submit": _("Save changes"),
            "u": u,
            "superuser": superuser,
            "menu_active": "emails",
            },
        context_instance=RequestContext(request)
    )
예제 #23
0
class RecordForm(ModelForm):
    helper = RostiFormHelper()

    class Meta:
        model = Record
        fields = ["name", "record_type", "value", "ttl", "prio"]

    def clean_user(self):
        return None

    def clean_prio(self):
        if self.data["record_type"] == "MX" and not self.cleaned_data["prio"]:
            raise forms.ValidationError(_("MX needs prio"))
        return self.cleaned_data["prio"]
예제 #24
0
파일: views.py 프로젝트: simhaonline/pcp
def add(request):
    """
    Add domain of customer
    """
    u = request.session.get('switched_user', request.user)
    superuser = request.user

    if request.method == 'POST':
        form = FormDomain(request.POST)
        if form.is_valid():
            name = form.cleaned_data["name"]

            object = form.save(commit=False)
            object.owner = u
            object.save()

            if config.handle_dns and object.dns:
                pri_br = BindRequest(u, "master")
                pri_br.mod_zone(object)
                pri_br.mod_config()
                pri_br.reload()
                if config.handle_dns_secondary:
                    sec_br = BindRequest(u, "slave")
                    sec_br.mod_config()
                    sec_br.reload()

            logging.info(_("Added domain %s ") % name)
            message = _("Domain %s has been successfuly added") % name
            send_mail(_('Added new domain: %s') % name,
                      message,
                      settings.EMAIL_FROM,
                      [mail for (name, mail) in settings.ADMINS if mail],
                      fail_silently=True)

            messages.add_message(request, messages.SUCCESS,
                                 _('Domain has been added'))
            return HttpResponseRedirect(
                reverse("subdomains", args=(object.id, )))
    else:
        form = FormDomain()

    return render_to_response('universal.html', {
        "form": form,
        'form_helper': RostiFormHelper(),
        "title": _("Add domain"),
        "u": u,
        "superuser": superuser,
        "menu_active": "domains",
    },
                              context_instance=RequestContext(request))
예제 #25
0
class FormRedirect(ModelForm):
    helper = RostiFormHelper()
    _domain = forms.ChoiceField(label=_("Domain"), choices=[(11, 22)])

    class Meta:
        model = EmailRedirect
        exclude = ("pub_date", "owner", "domain")
        fields = ('alias', '_domain', 'email')

    def clean_login(self):
        if Email.objects.filter(domain__name=self.data['domain'],
                                login=self.cleaned_data["alias"]).count():
            raise forms.ValidationError(_("Given alias already exists"))

        return self.cleaned_data["alias"]
예제 #26
0
class DbForm(ModelForm):
    helper = RostiFormHelper()

    def __init__(self, *args, **kwargs):
        super(DbForm, self).__init__(*args, **kwargs)
        self.fields["db_type"].help_text = _(
            "PostgreSQL database has public scheme as default. Make sure, you create your own. Otherwise everybody can see your tables/views/.. (not data, just structure)."
        )

    class Meta:
        model = Db
        fields = ["db_type", "password", "comment", "pg_postgis"]
        widgets = {
            'password': forms.PasswordInput,
        }
예제 #27
0
파일: views.py 프로젝트: a740122/pcp
def addRedirect(request):
    u = request.session.get('switched_user', request.user)
    superuser = request.user

    domains = [(x.name, x.name) for x in u.email_domain_set.filter()]
    if request.method == 'POST':
        form = FormRedirect(request.POST)
        form.fields["_domain"].choices = domains
        if form.is_valid():
            redirect = form.save(commit=False)
            redirect.alias = form.cleaned_data["alias"]
            redirect.domain = get_object_or_404(u.email_domain_set, name=form.cleaned_data["_domain"])
            redirect.pub_date = date.today()
            redirect.save()

            messages.add_message(request, messages.SUCCESS, _('Redirect has been added'))
            return HttpResponseRedirect(reverse("redirect_list"))
    else:
        form = FormRedirect()
        form.fields["_domain"].choices = domains

    helper = RostiFormHelper()
    helper.form_action = reverse("add_redirect")

    return render_to_response('universal.html',
            {
            "form": form,
            "form_helper": helper,
            "title": _("Add email redirect"),
            "submit": _("Add redirect"),
            "u": u,
            "superuser": superuser,
            "menu_active": "emails",
            },
        context_instance=RequestContext(request)
    )
예제 #28
0
def addRedirect(request):
    u = request.session.get('switched_user', request.user)
    superuser = request.user

    domains = [(x.name, x.name) for x in u.email_domain_set.filter()]
    if request.method == 'POST':
        form = FormRedirect(request.POST)
        form.fields["_domain"].choices = domains
        if form.is_valid():
            redirect = form.save(commit=False)
            redirect.alias = form.cleaned_data["alias"]
            redirect.domain = get_object_or_404(
                u.email_domain_set, name=form.cleaned_data["_domain"])
            redirect.pub_date = date.today()
            redirect.save()

            messages.add_message(request, messages.SUCCESS,
                                 _('Redirect has been added'))
            return HttpResponseRedirect(reverse("redirect_list"))
    else:
        form = FormRedirect()
        form.fields["_domain"].choices = domains

    helper = RostiFormHelper()
    helper.form_action = reverse("add_redirect")

    return render_to_response('universal.html', {
        "form": form,
        "form_helper": helper,
        "title": _("Add email redirect"),
        "submit": _("Add redirect"),
        "u": u,
        "superuser": superuser,
        "menu_active": "emails",
    },
                              context_instance=RequestContext(request))
예제 #29
0
def changePasswdBox(request, eid):
    eid = int(eid)
    u = request.session.get('switched_user', request.user)
    superuser = request.user

    try:
        e = Email.objects.get(domain__in=u.email_domain_set.all(), id=eid)
    except Email.DoesNotExist:
        e = None

    if request.method == 'POST':
        form = PassCheckModelForm(request.POST, instance=e)
        if form.is_valid():
            email = form.save(commit=False)
            email.password = crypt.crypt(form.cleaned_data["password1"],
                                         email.login)
            email.save()
            messages.add_message(request, messages.SUCCESS,
                                 _('Password has been changed'))
            return HttpResponseRedirect(reverse("mailbox_list"))
    else:
        form = PassCheckModelForm(instance=e)

    helper = RostiFormHelper()
    helper.form_action = reverse("wsgiadmin.emails.views.changePasswdBox",
                                 args=[e.id])

    return render_to_response('universal.html', {
        "form": form,
        "form_helper": helper,
        "title": _("Change password for e-mail box"),
        "u": u,
        "superuser": superuser,
        "menu_active": "emails",
    },
                              context_instance=RequestContext(request))
예제 #30
0
class DomainForm(forms.ModelForm):
    helper = RostiFormHelper()

    class Meta:
        model = Domain
        fields = ("name", )

    def clean_name(self):
        if not re.match("^[0-9a-zA-Z\.\-]*$", self.cleaned_data["name"]):
            raise forms.ValidationError(
                _("Domain name has to be in this format: ^[0-9a-zA-Z\.]*$"))
        return self.cleaned_data["name"]

    def clean_user(self):
        return None
예제 #31
0
def addBox(request):
    u = request.session.get('switched_user', request.user)
    superuser = request.user

    domains = [(x.name, x.name) for x in u.domain_set.filter(mail=True)]

    if request.method == 'POST':
        form = FormEmail(request.POST)
        form.fields["xdomain"].choices = domains

        if form.is_valid():
            form.cleaned_data["xdomain"] = get_object_or_404(
                u.domain_set, name=form.cleaned_data["xdomain"])
            email = form.save(commit=False)
            email.login = form.cleaned_data["login"]
            email.domain = form.cleaned_data["xdomain"]
            email.pub_date = date.today()
            email.password = crypt.crypt(form.cleaned_data["password1"],
                                         form.cleaned_data["login"])
            email.uid = config.email_uid
            email.gid = config.email_gid
            email.save()

            er = EMailRequest(u, u.parms.mail_machine)
            er.create_mailbox(email)

            messages.add_message(request, messages.INFO,
                                 _('Box will be created in few minutes'))
            return HttpResponseRedirect(reverse("mailbox_list"))
    else:
        form = FormEmail()
        form.fields["xdomain"].choices = domains

    helper = RostiFormHelper()

    return render_to_response('universal.html', {
        "form": form,
        "form_helper": helper,
        "title": _("New e-mail"),
        "submit": _("Create box"),
        "u": u,
        "superuser": superuser,
        "menu_active": "emails",
    },
                              context_instance=RequestContext(request))
예제 #32
0
파일: views.py 프로젝트: seanchen/pcp
def passwd(request, dbtype, dbname):
    u = request.session.get('switched_user', request.user)
    superuser = request.user

    if request.method == 'POST':
        form = PassCheckForm(request.POST)
        if form.is_valid():
            if dbtype == 'mysql':
                #TODO - raise better exception
                try:
                    u.mysqldb_set.get(dbname=dbname)
                except MySQLDB.DoesNotExist:
                    return HttpResponseForbidden(
                        ugettext("Unable to modify chosen database"))
                else:
                    mr = MySQLRequest(u, u.parms.mysql_machine)
            elif dbtype == 'pgsql':
                try:
                    u.pgsql_set.get(dbname=dbname)
                except PGSQL.DoesNotExist:
                    return HttpResponseForbidden(
                        ugettext("Unable to modify chosen database"))
                else:
                    mr = PostgreSQLRequest(u, u.parms.pgsql_machine)
            else:
                return HttpResponseBadRequest(_('Unknown database type'))

            mr.passwd_db(dbname, form.cleaned_data["password1"])
            messages.add_message(request, messages.SUCCESS,
                                 _('Password has been changed'))
            return HttpResponseRedirect(
                reverse('db_list', kwargs=dict(dbtype=dbtype)))
    else:
        form = PassCheckForm()

    return render_to_response('simplepasswd.html', {
        "form": form,
        "form_helper": RostiFormHelper(),
        "title": _("Change password for database"),
        "u": u,
        "superuser": superuser,
        "menu_active": "dbs",
    },
                              context_instance=RequestContext(request))
예제 #33
0
class FormEmail(PassCheckModelForm):
    helper = RostiFormHelper()
    login = forms.CharField(label=_("Name"),
                            help_text=_("Mailbox in name@domain format"))
    xdomain = forms.ChoiceField(label=_("Domain"), choices=[(11, 22)])

    class Meta:
        model = Email
        fields = ("login", "xdomain", "password1", "password2")

    def clean_login(self):
        if Email.objects.filter(domain__name=self.data['xdomain'],
                                login=self.cleaned_data["login"]).count():
            raise forms.ValidationError(_("Given username already exists"))
        if not re.match("^[0-9a-zA-Z_\.]*$", self.cleaned_data["login"]):
            raise forms.ValidationError(
                _("Login has to be in this format: ^[0-9a-zA-Z_\.]*$"))

        return self.cleaned_data["login"]
예제 #34
0
파일: forms.py 프로젝트: simhaonline/pcp
class FTPForm(PassCheckModelForm, FTPUpdateForm):
    helper = RostiFormHelper()

    class Meta:
        model = Ftp
        fields = ('username', 'dir', 'password1', 'password2')
        widgets = {
            'dir': forms.Select,
        }

    def clean(self):
        super(FTPForm, self).clean()
        super(FTPForm, self).clean_password1()
        self.cleaned_data['password1'] = self.cleaned_data['password1']
        return self.cleaned_data

    def clean_username(self):
        out_value = "%s_%s" % (self.user.username,
                               self.cleaned_data["username"])
        if Ftp.objects.filter(username=out_value).count():
            raise forms.ValidationError(_("Chosen username already exists"))

        return out_value
예제 #35
0
파일: forms.py 프로젝트: simhaonline/pcp
class FTPUpdateForm(ModelForm):
    helper = RostiFormHelper()

    class Meta:
        model = Ftp
        fields = ('username', 'dir')
        widgets = {
            'dir': forms.Select,
        }

    def __init__(self, *args, **kwargs):
        if 'user' in kwargs:
            self.user = kwargs.pop('user')
        super(FTPUpdateForm, self).__init__(*args, **kwargs)

        user_dirs = user_directories(user=self.user, use_cache=True)
        dirs_choices = [("", _("Not selected"))] + [(x, x) for x in user_dirs]
        self.fields['dir'].widget.choices = dirs_choices
        if 'username' in self.initial:
            self.initial['username'] = self.initial['username'][len(self.user.
                                                                    username) +
                                                                1:]

    def clean_username(self):
        out_value = "%s_%s" % (self.user.username,
                               self.cleaned_data["username"])
        if Ftp.objects.filter(username=out_value).exclude(
                pk=self.instance.pk).count():
            raise forms.ValidationError(_("Chosen username already exists"))

        return out_value

    def clean_dir(self):
        if ".." in self.cleaned_data["dir"] or "~" in self.cleaned_data["dir"]:
            raise forms.ValidationError(
                _("This field hasn't to contain .. and ~"))
        return self.cleaned_data["dir"]
예제 #36
0
파일: forms.py 프로젝트: seanchen/pcp
class FormStatic(ModelForm):
    class Meta:
        model = UserSite
        fields = ('main_domain', 'misc_domains', 'document_root',)
        widgets = {
            'document_root': forms.Select
        }

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')

        self.helper = RostiFormHelper()
        self.helper.form_class = 'dyn_refresh'

        super(FormStatic, self).__init__(*args, **kwargs)

        layout = Layout()
        if 'script' in self.fields:
            layout.fields.append(
                PrependedText('script', '<div class="ajax_refresh" data-el="script" data-target="%s"><span class="status"></span></div>' % reverse('refresh_wsgi')),
            )

        if 'virtualenv' in self.fields:
            layout.fields.append(
                PrependedText('virtualenv', '<div class="ajax_refresh" data-el="virtualenv" data-target="%s"><span class="status"></span></div>' % reverse('refresh_venv')),
            )

        if 'document_root' in self.fields:
            layout.fields.append(
                PrependedText('document_root', '<div class="ajax_refresh" data-el="document_root" data-target="%s"><span class="status"></span></div>' % reverse('refresh_userdirs')),
            )

        self.helper.add_layout(layout)


        if 'document_root' in self.fields:
            user_dirs = user_directories(user=self.user, use_cache=True)
            dirs_choices = [("", _("Not selected"))] + [(x, x) for x in
                                                               user_dirs]
            self.fields['document_root'].widget.choices = dirs_choices


    def clean_document_root(self):
        if ".." in self.cleaned_data["document_root"] or\
           "~" in self.cleaned_data["document_root"]:
            raise forms.ValidationError(
                _("This field hasn't to contain .. and ~"))
        return self.cleaned_data["document_root"]

    def clean(self):
        data = self.cleaned_data
        try:
            main_domain = data['main_domain']
        except KeyError:
            raise forms.ValidationError(
                _("Main domain has to be filled"))
            
        if 'misc_domains' in data and main_domain in data['misc_domains']:
            raise forms.ValidationError(
                _("Main domain cannot be listed also as misc. domain"))
        return data
예제 #37
0
파일: views.py 프로젝트: ghostmod/pcp
 def get_context_data(self, **kwargs):
     data = super(PasswordView, self).get_context_data(**kwargs)
     data['form_helper'] = RostiFormHelper()
     data['menu_active'] = "reset_passwd"
     return data