Esempio n. 1
0
            def __init__(self, *args, **kwargs):
                super(ApiForm, self).__init__(*args, **kwargs)
                self.query_params_fields = []
                self.input_params_fields = []
                self.fields['api'] = forms.CharField(
                    widget=forms.widgets.HiddenInput(), required=False)
                if '{}' in endpoint['url']:
                    self.fields['pk'] = forms.CharField(label='ID',
                                                        required=True)
                for param in endpoint['query_params']:
                    self.fields[param['name']] = forms.CharField(
                        label=param['verbose_name'],
                        required=param['required'],
                        help_text=param['help_text'])
                    self.query_params_fields.append(param['name'])
                for param in endpoint['input_params']:
                    self.fields[param['name']] = forms.CharField(
                        label=param['verbose_name'],
                        required=param['required'],
                        help_text=param['help_text'])
                    self.input_params_fields.append(param['name'])

                self.fieldsets = []
                if 'pk' in self.fields:
                    self.fieldsets.append((u'Identifier', {
                        'fields': ('pk', )
                    }))
                if self.query_params_fields:
                    self.fieldsets.append((u'Query Params', {
                        'fields': self.query_params_fields
                    }))
                if self.input_params_fields:
                    self.fieldsets.append((u'Input Params', {
                        'fields': self.input_params_fields
                    }))
Esempio n. 2
0
class GroupForm(forms.ModelForm):
    name = forms.CharField(label='Name')

    class Meta:
        title = '{} {}'.format(_('Register'), _('Group'))
        submit_label = _('Save')
        icon = 'fa-users'
        model = Group
        fields = ('name', )
Esempio n. 3
0
class GroupForm(forms.ModelForm):
    name = forms.CharField(label=u'Name')

    class Meta:
        title = 'Cadastro de Grupo'
        submit_label = 'Cadastrar'
        icon = 'fa-users'
        model = Group
        fields = ('name',)
Esempio n. 4
0
class RegisterForm(forms.Form):
    name = forms.CharField(label=_('Name'), required=True)
    email = forms.EmailField(label=_('E-mail'), required=True)
    new_password = forms.PasswordField(label=_('Password'), required=True)
    confirm_password = forms.PasswordField(label=_('Password'),
                                           required=True,
                                           help_text=_('Repeat Password'))

    class Meta:
        title = 'Novo Usuário'
        icon = 'fa-user'
        submit_label = 'Cadastrar'
        captcha = True

    fieldsets = (
        (_('User Data'), {
            'fields': ('name', 'email')
        }),
        (_('Access Password'), {
            'fields': (('new_password', 'confirm_password'), )
        }),
    )

    def clean(self):
        if not self.data['new_password'] == self.data['confirm_password']:
            raise forms.ValidationError(_('The passwords must be the same.'))
        return self.cleaned_data

    def save(self, *args, **kwargs):
        create = True
        user = User()
        password = self.cleaned_data['new_password']
        user.name = self.cleaned_data['name']
        user.email = self.cleaned_data['email']
        user.username = self.cleaned_data['email']
        user.active = True
        user.is_superuser = False
        user.last_login = None
        user.date_joined = datetime.datetime.now()
        user.username = user.email
        user.set_password(password)
        if create:
            user.save()
            return user
        else:
            token = signing.dumps('{};{};{}'.format(user.name, user.email,
                                                    password))
            url = '{}/admin/create_user/{}/'.format(settings.SERVER_ADDRESS,
                                                    token)
            msg = '{}: {}'.format(
                _('Click on the link to activate your account'),
                url), settings.SYSTEM_EMAIL_ADDRESS
            user.email_user(_('Account Activation'), msg)
            return None
Esempio n. 5
0
class RegisterForm(forms.Form):
    name = forms.CharField(label='Nome', required=True)
    email = forms.EmailField(label='E-mail', required=True)
    new_password = forms.PasswordField(label=u'Senha', required=True)
    confirm_password = forms.PasswordField(label=u'Senha', required=True,
                                           help_text=u'Repita a senha digitada anteriormente')

    class Meta:
        title = u'Novo Usuário'
        icon = u'fa-user'
        submit_label = 'Cadastrar'

    fieldsets = (
        (u'Dados Gerais', {'fields': ('name', 'email')}),
        (u'Senha de Acesso', {'fields': (('new_password', 'confirm_password'))}),
    )

    def clean(self):
        if not self.data['new_password'] == self.data['confirm_password']:
            raise forms.ValidationError(u'As senhas devem ser iguais.')
        return self.cleaned_data

    def save(self, *args, **kwargs):
        user = User()
        password = self.cleaned_data['new_password']
        user.name = self.cleaned_data['name']
        user.email = self.cleaned_data['email']
        user.username = self.cleaned_data['email']
        user.active = True
        user.is_superuser = False
        user.last_login = datetime.datetime.now()
        user.date_joined = datetime.datetime.now()
        user.username = user.email
        user.set_password(password)
        if True:
            user.save()
            return user
        else:
            token = encrypt('%s;%s;%s;%s' % (user.first_name, user.last_name, user.email, password))
            url = u'%s/admin/create_user/%s/' % (settings.SERVER_ADDRESS, token)
            user.email_user(u'Criação de Conta', u'Clique para confirmar a criação de sua conta: %s' % url,
                            settings.SYSTEM_EMAIL_ADDRESS)
            return None
Esempio n. 6
0
class ScheduleTableForm(forms.Form):
    values = forms.CharField(label='Values',
                             widget=forms.widgets.HiddenInput())

    def __init__(self, *args, **kwargs):
        schedule = kwargs.get('initial', {}).pop('schedule', [])
        kwargs['initial']['values'] = ''
        super().__init__(*args, **kwargs)
        form_prefix = self.prefix and '{}-'.format(self.prefix) or None
        self.component = MultiScheduleTable(schedule,
                                            self.request,
                                            title='Horários',
                                            form_prefix=form_prefix)

    def clean_values(self):
        values = self.cleaned_data['values']
        cleaned_values = []
        if values:
            for value in values.split('|'):
                i, interval = value.split('::')
                cleaned_values.append(
                    (ScheduleTable.WEEK_DAYS[int(i) - 1], interval))
        return cleaned_values
Esempio n. 7
0
class ResetPasswordForm(forms.Form):
    mail = forms.CharField(label=u'E-mail')

    class Meta:
        title = u'Alteração de Senha'
        icon = u'mdi-content-mail'
        submit_label = u'Enviar E-mail'
        note = u'Ao preencher e submeter o formulário abaixo, um e-mail será enviado para vocêcontendo ' \
               u'um link através do qual você poderá alterar sua senha.'

    def clean_mail(self):
        self.qs = User.objects.filter(email=self.cleaned_data['mail'])
        if self.qs.exists():
            return self.cleaned_data['mail']
        else:
            raise forms.ValidationError(u'E-mail não cadastrado.')

    def submit(self):
        user = self.qs[0]
        token = encrypt('%s' % user.pk)
        url = '%s/admin/password/%s/' % (settings.SERVER_ADDRESS, token)
        user.email_user(u'Recuperação de Senha', u'Clique no link a seguir para alterar sua senha: %s' % url,
                        settings.SYSTEM_EMAIL_ADDRESS)
Esempio n. 8
0
class LoginForm(forms.Form):

    ORGANIZATION = 'organization'
    UNIT = 'unit'

    username = forms.CharField(label=_('User'))
    password = forms.PasswordField(label=_('Password'))

    def __init__(self,
                 request,
                 scope=None,
                 organization=None,
                 unit=None,
                 *args,
                 **kwargs):
        super(LoginForm, self).__init__(request, *args, **kwargs)
        self.scope = None
        self.fields['username'].widget.attrs[
            'class'] = 'input-sm bounceIn animation-delay2'
        if scope:
            if scope == LoginForm.ORGANIZATION or scope == (
                    CACHE['ORGANIZATION_MODEL']
                    and CACHE['ORGANIZATION_MODEL'].__name__.lower()):
                if organization:
                    self.scope_display = organization
                else:
                    organizations = Organization.objects.all()
                    self.fields['login_scope'] = forms.ModelChoiceField(
                        organizations)
                self.scope = LoginForm.ORGANIZATION
            elif scope == LoginForm.UNIT or scope == (
                    CACHE['UNIT_MODEL']
                    and CACHE['UNIT_MODEL'].__name__.lower()):
                if unit:
                    self.scope_display = unit
                else:
                    if organization:
                        self.scope_display = organization
                        units = organization.get_units()
                    else:
                        units = Unit.objects.all()
                    self.fields['login_scope'] = forms.ModelChoiceField(units)
                self.scope = LoginForm.UNIT
        self.organization = organization
        self.unit = unit

    def clean(self):
        cleaned_data = super(LoginForm, self).clean()
        username = cleaned_data.get('username')
        password = cleaned_data.get('password')
        if not User.objects.filter(username=username).exists():
            raise forms.ValidationError(_('User not registered.'))
        user = auth.authenticate(username=username, password=password)
        if user is not None:
            if user.active:
                user.permission_mapping = ''
                user.organization = None
                user.unit = None
                if self.scope == LoginForm.ORGANIZATION:
                    user.organization = cleaned_data.get(
                        'login_scope', self.organization)
                    is_organization_user = user.role_set.filter(
                        scope__in=(user.organization, 0)).exists()
                    if not is_organization_user:
                        raise forms.ValidationError('{} {} {}'.format(
                            username, _('is not user of'), user.organization))
                elif self.scope == LoginForm.UNIT:
                    user.unit = cleaned_data.get('login_scope', self.unit)
                    is_unit_user = user.role_set.filter(
                        scope__in=(user.unit, 0)).exists()
                    is_organization_user = CACHE[
                        'ORGANIZATION_MODEL'] and user.role_set.filter(
                            scope__in=(user.unit.get_organization(),
                                       0)).exists()
                    if not is_unit_user and not is_organization_user:
                        raise forms.ValidationError('{} {} {}'.format(
                            username, _('is not user of'), user.unit))
                else:
                    roles = user.role_set.all()
                    if roles.count() == 1:
                        role = roles.first()
                        if role.scope:
                            user.scope = role.scope
                user.save()
                auth.login(self.request, user)
                return cleaned_data
            else:
                raise forms.ValidationError(_('User is inactive.'))
        else:
            raise forms.ValidationError(_('Password is incorrect.'))

    def submit(self):
        url = self.request.GET.get('next', '/admin/')
        return httprr(self.request, url, _('You have successfully logged in.'))
Esempio n. 9
0
def get_action_form(request, obj, action):
    action_function = action['function']
    action_verbose_name = action['verbose_name']
    initial = action['initial']
    action_input = action['input']
    action_choices = action['choices']
    action_display = action['display']
    app_label = get_metadata(type(obj), 'app_label')
    func = getattr(obj, action_function.__name__, action_function)

    if initial and hasattr(obj, initial):
        initial = getattr(obj, initial)()
    else:
        initial = {}
    if action_choices and hasattr(obj, action_choices):
        action_choices = getattr(obj, action_choices)()
    else:
        action_choices = {}

    if action_input:
        # it is a form name
        if type(action_input) in [str, str] and '.' not in action_input:
            full_app_name = settings.APP_MAPPING.get(app_label, app_label)
            fromlist = app_label
            module = __import__('{}.forms'.format(full_app_name),
                                fromlist=list(map(str, [app_label])))
            form_cls = getattr(module, action_input)

        # it is a model or model name
        else:
            if type(action_input) in [str, str]:
                app_name, class_name = action_input.split('.')
                action_input = apps.get_model(app_name, class_name)

            class Form(forms.ModelForm):
                class Meta:
                    model = action_input
                    fields = get_parameters_names(func)
                    title = action_verbose_name
                    submit_label = action_verbose_name

            form_cls = Form
    else:

        class Form(forms.ModelForm):
            class Meta:
                model = func.__self__.__class__
                fields = get_parameters_names(func)
                title = action_verbose_name
                submit_label = action_verbose_name

        form_cls = Form

    if issubclass(form_cls, forms.ModelForm):
        for key in list(initial.keys()):
            if hasattr(obj, key) and obj.pk and getattr(obj, key):
                del (initial[key])
        form = form_cls(request, instance=obj, initial=initial)
    else:
        form = form_cls(request, initial=initial)

    if action_display:
        for lookup in action_display:
            label = get_fiendly_name(func.__self__.__class__, lookup)
            value = getattr2(obj, lookup)
            form.fields[lookup] = forms.CharField(
                label=label,
                initial=value,
                required=False,
                widget=forms.widgets.DisplayInput(value))

    if action_choices:
        for field_name in action_choices:
            form.fields[field_name].queryset = action_choices[field_name]

    if not obj.pk:
        verbose_name = get_metadata(obj.__class__, 'verbose_name')
        form.fields['instance'] = forms.ModelChoiceField(
            type(obj).objects.all(), label=verbose_name)
        if form.fieldsets:
            form.fieldsets = ((verbose_name, {
                'fields': ('instance', )
            }), ) + form.fieldsets

    return form
Esempio n. 10
0
class LoginForm(forms.Form):
    
    ORGANIZATION = 'organization'
    UNIT = 'unit'
    
    username = forms.CharField(label=u'Usuário')
    password = forms.PasswordField(label=u'Senha',
                                   help_text=u'Caso tenha esquecido sua senha, clique aqui para '
                                   u'<a class="popup" href="/admin/reset_password/">alterá-la</a>.')

    def __init__(self, request, scope=None, organization=None, unit=None, *args, **kwargs):
        super(LoginForm, self).__init__(request, *args, **kwargs)
        self.scope = None
        self.fields['username'].widget.attrs['class'] = 'input-sm bounceIn animation-delay2'
        if scope:
            if scope == LoginForm.ORGANIZATION or scope == (loader.organization_model and loader.organization_model.__name__.lower()):
                if organization:
                    self.scope_display = organization
                else:
                    organizations = Organization.objects.exclude(pk=0)
                    self.fields['login_scope'] = forms.ModelChoiceField(organizations)
                self.scope = LoginForm.ORGANIZATION
            elif scope == LoginForm.UNIT or scope == (loader.unit_model and loader.unit_model.__name__.lower()):
                if unit:
                    self.scope_display = unit
                else:
                    if organization:
                        self.scope_display = organization
                        units = organization.get_units()
                    else:
                        units = Unit.objects.exclude(pk=0)
                    self.fields['login_scope'] = forms.ModelChoiceField(units)
                self.scope = LoginForm.UNIT
        self.organization = organization
        self.unit = unit

    def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        if not User.objects.filter(username=username).exists():
            raise forms.ValidationError(u'Usuário não cadastrado.')
        user = auth.authenticate(username=username, password=password)
        if user is not None:
            if user.active:
                user.permission_mapping = ''
                user.organization = None
                user.unit = None
                if self.scope == LoginForm.ORGANIZATION:
                    user.organization = self.cleaned_data.get('login_scope', self.organization)
                    is_organization_user = user.role_set.filter(organizations__in=(user.organization, 0)).exists()
                    if not is_organization_user:
                        raise forms.ValidationError(u'%s não é usuário de %s' % (username, user.organization))
                elif self.scope == LoginForm.UNIT:
                    user.unit = self.cleaned_data.get('login_scope', self.unit)
                    is_unit_user = user.role_set.filter(units__in=(user.unit, 0)).exists()
                    is_organization_user = loader.organization_model and user.role_set.filter(organizations__in=(user.unit.get_organization(), 0)).exists()
                    if not is_unit_user and not is_organization_user:
                        raise forms.ValidationError(u'%s não é usuário de %s' % (username, user.unit))
                user.save()
                auth.login(self.request, user)
                return self.cleaned_data
            else:
                raise forms.ValidationError(u'Usuário inativo.')
        else:
            raise forms.ValidationError(u'Senha não confere.')

    def submit(self):
        url = self.request.GET.get('next', '/admin/')
        return httprr(self.request, url, u'Usuário autenticado com sucesso.')