2018-11-23 02:25:35 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
2019-01-16 10:13:16 +00:00
|
|
|
from django.utils.translation import ugettext as _
|
2018-11-23 02:25:35 +00:00
|
|
|
from rest_framework import serializers
|
2019-02-28 09:58:53 +00:00
|
|
|
from ..models import User
|
2018-11-23 02:25:35 +00:00
|
|
|
|
2019-02-28 09:58:53 +00:00
|
|
|
from authentication.serializers import AccessKeySerializer
|
2018-11-23 02:25:35 +00:00
|
|
|
|
2019-03-18 03:34:13 +00:00
|
|
|
__all__ = ['ServiceAccountSerializer']
|
|
|
|
|
2018-11-23 02:25:35 +00:00
|
|
|
|
2019-01-16 10:13:16 +00:00
|
|
|
class ServiceAccountSerializer(serializers.ModelSerializer):
|
2018-11-23 02:25:35 +00:00
|
|
|
access_key = AccessKeySerializer(read_only=True)
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
model = User
|
|
|
|
fields = ['id', 'name', 'access_key']
|
2019-03-19 11:09:09 +00:00
|
|
|
read_only_fields = ['access_key']
|
2018-11-23 02:25:35 +00:00
|
|
|
|
|
|
|
def get_username(self):
|
|
|
|
return self.initial_data.get('name')
|
|
|
|
|
|
|
|
def get_email(self):
|
|
|
|
name = self.initial_data.get('name')
|
|
|
|
return '{}@serviceaccount.local'.format(name)
|
|
|
|
|
|
|
|
def validate_name(self, name):
|
|
|
|
email = self.get_email()
|
|
|
|
username = self.get_username()
|
2019-01-16 10:13:16 +00:00
|
|
|
if self.instance:
|
|
|
|
users = User.objects.exclude(id=self.instance.id)
|
|
|
|
else:
|
|
|
|
users = User.objects.all()
|
|
|
|
if users.filter(email=email) or \
|
|
|
|
users.filter(username=username):
|
|
|
|
raise serializers.ValidationError(_('name not unique'), code='unique')
|
2018-11-23 02:25:35 +00:00
|
|
|
return name
|
|
|
|
|
2019-01-16 10:13:16 +00:00
|
|
|
def save(self, **kwargs):
|
|
|
|
self.validated_data['email'] = self.get_email()
|
|
|
|
self.validated_data['username'] = self.get_username()
|
2020-07-28 09:53:01 +00:00
|
|
|
self.validated_data['role'] = User.ROLE.APP
|
2019-01-16 10:13:16 +00:00
|
|
|
return super().save(**kwargs)
|
|
|
|
|
2018-11-23 02:25:35 +00:00
|
|
|
def create(self, validated_data):
|
|
|
|
instance = super().create(validated_data)
|
|
|
|
instance.create_access_key()
|
|
|
|
return instance
|