django-orchestra/orchestra/contrib/systemusers/serializers.py

50 lines
1.8 KiB
Python
Raw Normal View History

from django.forms import widgets
from django.shortcuts import get_object_or_404
2015-04-04 18:10:39 +00:00
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
2015-04-23 14:34:04 +00:00
from orchestra.api.serializers import SetPasswordHyperlinkedSerializer
2015-04-05 10:46:24 +00:00
from orchestra.contrib.accounts.serializers import AccountSerializerMixin
2014-09-30 16:39:47 +00:00
from .models import SystemUser
from .validators import validate_home
2014-09-30 16:39:47 +00:00
class GroupSerializer(AccountSerializerMixin, serializers.HyperlinkedModelSerializer):
2014-10-07 13:08:59 +00:00
class Meta:
model = SystemUser
fields = ('url', 'username',)
2014-10-07 13:08:59 +00:00
def from_native(self, data, files=None):
queryset = self.opts.model.objects.filter(account=self.account)
return get_object_or_404(queryset, username=data['username'])
2014-10-07 13:08:59 +00:00
2015-04-23 14:34:04 +00:00
class SystemUserSerializer(AccountSerializerMixin, SetPasswordHyperlinkedSerializer):
groups = GroupSerializer(many=True, required=False)
class Meta:
2014-09-30 16:39:47 +00:00
model = SystemUser
fields = (
2014-11-18 13:59:21 +00:00
'url', 'username', 'password', 'home', 'directory', 'shell', 'groups', 'is_active',
)
2015-04-23 14:34:04 +00:00
postonly_fields = ('username', 'password')
def validate(self, attrs):
2015-04-23 14:34:04 +00:00
attrs = super(SystemUserSerializer, self).validate(attrs)
user = SystemUser(
2015-04-23 14:34:04 +00:00
username=attrs.get('username') or self.instance.username,
shell=attrs.get('shell') or self.instance.shell,
)
validate_home(user, attrs, self.account)
return attrs
def validate_groups(self, attrs, source):
groups = attrs.get(source)
if groups:
for group in groups:
if group.username == attrs['username']:
raise serializers.ValidationError(
_("Do not make the user member of its group"))
return attrs