This repository has been archived on 2023-02-21. You can view files and clone it, but cannot push or open issues or pull requests.
veridic/acs/forms.py

396 lines
12 KiB
Python

'''
VERIDIC - Towards a centralized access control system
Copyright (C) 2011 Mikael Ates
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 <http://www.gnu.org/licenses/>.
'''
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.forms.widgets import CheckboxSelectMultiple
from django.contrib.auth.models import User
from registration.forms import RegistrationForm
from models import Action, Activity, AcsObject, Role, View
from abac.models import Source, LdapSource
attrs_dict = {'class': 'required'}
class AuthenticRegistrationForm(RegistrationForm):
username = forms.RegexField(regex=r'^\w+$',
max_length=30,
widget=forms.TextInput(attrs=attrs_dict),
label=_(u'username'),
error_messages = {'invalid': \
_(u'your username must contain only letters, numbers and no spaces')})
#class AcsUserCreationForm(UserCreationForm):
# make_it_admin = forms.BooleanField(required=False, \
# label=_("Tick to make this user able \
# to administrate the access control policy."))
'''
def mk_authz_who_list(user):
ret = []
administration = Action.objects.get(name='administration')
users = User.objects.all()
for it in users:
if isAuthorizedRBAC2(user, it, administration):
ret.append((it.username, it.username))
roles = Role.objects.all()
for it in roles:
if isAuthorizedRBAC2(user, it, administration):
ret.append((it.name, it.name))
return ret
'''
'''I was unable to modify query sets to only contain the authorized objects as
computed in mk_authz_who_list for instance.
We restrict at display giving an another list to the template.
class AddPermissionForm(forms.Form):
# def __init__(self, *args, **kwargs):
# super(AddPermissionForm, self).__init__(*args, **kwargs)
# self.fields["who"].widget = CheckboxSelectMultiple()
# self.fields["who"].help_text = None
# self.fields["what"].widget = CheckboxSelectMultiple()
# self.fields["what"].help_text = None
# self.fields["how"].widget = CheckboxSelectMultiple()
# self.fields["how"].help_text = None
# class Meta:
# model = AcsPermissions2
who_matches = forms.ChoiceField(
choices = mk_who_list()
)
what_matches = forms.ChoiceField(
choices = mk_what_list()
)
how_matches = forms.ChoiceField(
choices = mk_how_list()
)
# def __init__(self, *args, **kwargs):
# self.user = kwargs.pop('user', None)
# import sys
# print >> sys.stderr, str(self.user)
# self.who_matches.choices = mk_authz_who_list(self.user)
# self.what_matches.choices = mk_authz_what_list(self.user)
# self.how_matches.choices = mk_authz_how_list(self.user)
# forms.Form.__init__(self, *args, **kwargs)
'''
class AddRoleForm(forms.ModelForm):
name = forms.RegexField(label=_("name"),
max_length=30, regex=r'^[\w.@+-]+$',
help_text = \
_("30 characters or fewer. Letters, digits and @/./+/-/_ only."),
error_messages = \
{'invalid': _("This value may contain only letters, \
numbers and @/./+/-/_ characters.")})
class Meta:
model = Role
fields = ("name",)
def clean_name(self):
name = self.cleaned_data["name"]
try:
Role.objects.get(name=name)
except Role.DoesNotExist:
return name
raise forms.ValidationError(\
_("A role with that name already exists."))
def save(self, commit=True):
role = super(AddRoleForm, self).save(commit=False)
if commit:
role.save()
return role
class AddObjectForm(forms.ModelForm):
name = forms.RegexField(label=_("name"),
max_length=30, regex=r'^[\w.@+-]+$',
help_text = \
_("30 characters or fewer. Letters, digits and @/./+/-/_ only."),
error_messages = \
{'invalid': _("This value may contain only letters, \
numbers and @/./+/-/_ characters.")})
regex = forms.CharField(label=_("Regular expression"), required=False)
class Meta:
model = AcsObject
fields = ("name",)
# def clean_name(self):
# name = self.cleaned_data["name"]
# try:
# AcsObject.objects.get(name=name)
# except AcsObject.DoesNotExist:
# return name
# raise forms.ValidationError(\
# _("An object with that name already exists."))
def save(self, commit=True):
acs_object = super(AddObjectForm, self).save(commit=False)
if commit:
acs_object.save()
return acs_object
class AddViewForm(forms.ModelForm):
name = forms.RegexField(label=_("name"),
max_length=30, regex=r'^[\w.@+-]+$',
help_text = \
_("30 characters or fewer. Letters, digits and @/./+/-/_ only."),
error_messages = \
{'invalid': _("This value may contain only letters, \
numbers and @/./+/-/_ characters.")})
class Meta:
model = View
fields = ("name",)
def clean_name(self):
name = self.cleaned_data["name"]
try:
View.objects.get(name=name)
except View.DoesNotExist:
return name
raise forms.ValidationError(\
_("A view with that name already exists."))
def save(self, commit=True):
view = super(AddViewForm, self).save(commit=False)
if commit:
view.save()
return view
class AddActionForm(forms.ModelForm):
name = forms.RegexField(label=_("name"),
max_length=30, regex=r'^[\w.@+-]+$',
help_text = \
_("30 characters or fewer. Letters, digits and @/./+/-/_ only."),
error_messages = \
{'invalid': _("This value may contain only letters, \
numbers and @/./+/-/_ characters.")})
class Meta:
model = Action
fields = ("name",)
def clean_name(self):
name = self.cleaned_data["name"]
try:
Action.objects.get(name=name)
except Action.DoesNotExist:
return name
raise forms.ValidationError(\
_("An action with that name already exists."))
def save(self, commit=True):
action = super(AddActionForm, self).save(commit=False)
if commit:
action.save()
return action
class AddActivityForm(forms.ModelForm):
name = forms.RegexField(label=_("name"),
max_length=30, regex=r'^[\w.@+-]+$',
help_text = \
_("30 characters or fewer. Letters, digits and @/./+/-/_ only."),
error_messages = \
{'invalid': _("This value may contain only letters, \
numbers and @/./+/-/_ characters.")})
class Meta:
model = Activity
fields = ("name",)
def clean_name(self):
name = self.cleaned_data["name"]
try:
Activity.objects.get(name=name)
except Activity.DoesNotExist:
return name
raise forms.ValidationError(\
_("An activity with that name already exists."))
def save(self, commit=True):
activity = super(AddActivityForm, self).save(commit=False)
if commit:
activity.save()
return activity
class AddSourceForm(forms.ModelForm):
name = forms.RegexField(label=_("name"),
max_length=30, regex=r'^[\w.@+-]+$',
help_text = \
_("30 characters or fewer. Letters, digits and @/./+/-/_ only."),
error_messages = \
{'invalid': _("This value may contain only letters, \
numbers and @/./+/-/_ characters.")})
class Meta:
model = Source
fields = ("name",)
def clean_name(self):
name = self.cleaned_data["name"]
try:
Source.objects.get(name=name)
except Source.DoesNotExist:
return name
raise forms.ValidationError(\
_("A source with that name already exists."))
def save(self, commit=True):
source = super(AddSourceForm, self).save(commit=False)
if commit:
source.save()
return source
class AddLdapSourceForm(forms.ModelForm):
name = forms.RegexField(label=_("name"),
max_length=30, regex=r'^[\w.@+-]+$',
help_text = \
_("30 characters or fewer. Letters, digits and @/./+/-/_ only."),
error_messages = \
{'invalid': _("This value may contain only letters, \
numbers and @/./+/-/_ characters.")})
server = forms.RegexField(label=_("LDAP host"),
max_length=100, regex=r'^[\w.@+-]+$',
help_text = \
_("Provide a hostname or an IP address."),
error_messages = \
{'invalid': _("This value may contain only letters, \
numbers and @/./+/-/_ characters.")})
user = forms.RegexField(label=_("Username"), required=False,
max_length=100, regex=r'^[\w.@+-]+$',
help_text = \
_("Provide a user account if it is necessary to authenticate for binding."),
error_messages = \
{'invalid': _("This value may contain only letters, \
numbers and @/./+/-/_ characters.")})
password = forms.RegexField(label=_("Password"), required=False,
max_length=100, regex=r'^[\w.@+-]+$',
help_text = \
_("Provide a user account if it is necessary to authenticate for binding."),
error_messages = \
{'invalid': _("This value may contain only letters, \
numbers and @/./+/-/_ characters.")})
base = forms.RegexField(label=_("Base DN"),
max_length=100, regex=r'^[\w.@+-,=]+$',
help_text = \
_("Provide the base DN for searching, e.g. dc=organization,dc=org."),
error_messages = \
{'invalid': _("This value may contain only letters, \
numbers and @/./+/-/_ characters.")})
is_auth_backend = forms.BooleanField(required=False,
help_text = \
_("Check if this LDAP is also used as an authentication backend"))
class Meta:
model = LdapSource
fields = ("name", "server", "user", "password", "base", "is_auth_backend")
def save(self, commit=True):
source = super(AddLdapSourceForm, self).save(commit=False)
if commit:
source.save()
return source
class RoleChangeForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(RoleChangeForm, self).__init__(*args, **kwargs)
self.fields["users"].widget = CheckboxSelectMultiple()
self.fields["users"].help_text = None
self.fields["roles"].widget = CheckboxSelectMultiple()
self.fields["roles"].help_text = None
class Meta:
model = Role
class AcsObjectChangeForm(forms.ModelForm):
class Meta:
model = AcsObject
class ViewChangeForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ViewChangeForm, self).__init__(*args, **kwargs)
self.fields["acs_objects"].widget = CheckboxSelectMultiple()
self.fields["acs_objects"].help_text = None
self.fields["views"].widget = CheckboxSelectMultiple()
self.fields["views"].help_text = None
self.fields["users"].widget = CheckboxSelectMultiple()
self.fields["users"].help_text = None
self.fields["roles"].widget = CheckboxSelectMultiple()
self.fields["roles"].help_text = None
self.fields["actions"].widget = CheckboxSelectMultiple()
self.fields["actions"].help_text = None
self.fields["activities"].widget = CheckboxSelectMultiple()
self.fields["activities"].help_text = None
class Meta:
model = View
def save(self, *args, **kwargs):
super(ViewChangeForm, self).save(*args, **kwargs)
self.instance.users = self.cleaned_data.get('users')
if len(args) > 0 and isinstance(args[0], User):
self.instance.users.add(args[0])
self.instance.save()
class ActionChangeForm(forms.ModelForm):
class Meta:
model = Action
class ActivityChangeForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ActivityChangeForm, self).__init__(*args, **kwargs)
self.fields["actions"].widget = CheckboxSelectMultiple()
self.fields["actions"].help_text = None
self.fields["activities"].widget = CheckboxSelectMultiple()
self.fields["activities"].help_text = None
class Meta:
model = Activity