2014-09-30 09:49:07 +00:00
|
|
|
from django.contrib.auth import get_user_model
|
|
|
|
from django.forms import widgets
|
|
|
|
from django.utils.translation import ugettext, ugettext_lazy as _
|
|
|
|
from rest_framework import serializers
|
|
|
|
|
|
|
|
from orchestra.apps.accounts.serializers import AccountSerializerMixin
|
|
|
|
from orchestra.core.validators import validate_password
|
|
|
|
|
2014-09-30 16:39:47 +00:00
|
|
|
from .models import SystemUser
|
2014-09-30 09:49:07 +00:00
|
|
|
|
2014-09-30 16:39:47 +00:00
|
|
|
|
|
|
|
class SystemUserSerializer(AccountSerializerMixin, serializers.HyperlinkedModelSerializer):
|
2014-09-30 09:49:07 +00:00
|
|
|
password = serializers.CharField(max_length=128, label=_('Password'),
|
|
|
|
validators=[validate_password], write_only=True, required=False,
|
|
|
|
widget=widgets.PasswordInput)
|
2014-09-30 16:39:47 +00:00
|
|
|
groups = serializers.RelatedField(many=True)
|
2014-09-30 09:49:07 +00:00
|
|
|
|
|
|
|
class Meta:
|
2014-09-30 16:39:47 +00:00
|
|
|
model = SystemUser
|
2014-09-30 09:49:07 +00:00
|
|
|
fields = (
|
2014-09-30 16:39:47 +00:00
|
|
|
'url', 'username', 'password', 'home', 'shell', 'groups', 'is_active',
|
2014-09-30 09:49:07 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
def validate_password(self, attrs, source):
|
|
|
|
""" POST only password """
|
2014-10-01 16:42:40 +00:00
|
|
|
if self.object:
|
2014-09-30 09:49:07 +00:00
|
|
|
if 'password' in attrs:
|
|
|
|
raise serializers.ValidationError(_("Can not set password"))
|
|
|
|
elif 'password' not in attrs:
|
|
|
|
raise serializers.ValidationError(_("Password required"))
|
|
|
|
return attrs
|
|
|
|
|
|
|
|
def save_object(self, obj, **kwargs):
|
|
|
|
# FIXME this method will be called when saving nested serializers :(
|
|
|
|
if not obj.pk:
|
|
|
|
obj.set_password(obj.password)
|
2014-09-30 16:39:47 +00:00
|
|
|
super(SystemUserSerializer, self).save_object(obj, **kwargs)
|