<s> from __future__ import absolute_import <EOL> from django . conf import settings <EOL> from rest_framework import serializers , status <EOL> from rest_framework . response import Response <EOL> from sentry . api . bases . user import UserEndpoint <EOL> from sentry . api . serializers import serialize <EOL> from sentry . models import User <EOL> class BaseUserSerializer ( serializers . ModelSerializer ) : <EOL> def validate_username ( self , attrs , source ) : <EOL> value = attrs [ source ] <EOL> if User . objects . filter ( username__iexact = value ) . exclude ( id = self . object . id ) . exists ( ) : <EOL> raise serializers . ValidationError ( '<STR_LIT>' ) <EOL> return attrs <EOL> def validate ( self , attrs ) : <EOL> attrs = super ( BaseUserSerializer , self ) . validate ( attrs ) <EOL> if self . object . email == self . object . username : <EOL> if attrs . get ( '<STR_LIT:username>' , self . object . email ) != self . object . email : <EOL> attrs . setdefault ( '<STR_LIT:email>' , attrs [ '<STR_LIT:username>' ] ) <EOL> return attrs <EOL> def restore_object ( self , attrs , instance = None ) : <EOL> instance = super ( BaseUserSerializer , self ) . restore_object ( attrs , instance ) <EOL> instance . is_active = attrs . get ( '<STR_LIT>' , instance . is_active ) <EOL> return instance <EOL> class UserSerializer ( BaseUserSerializer ) : <EOL> class Meta : <EOL> model = User <EOL> fields = ( '<STR_LIT:name>' , '<STR_LIT:username>' , '<STR_LIT:email>' ) <EOL> def validate_username ( self , attrs , source ) : <EOL> value = attrs [ source ] <EOL> if User . objects . filter ( username__iexact = value ) . exclude ( id = self . object . id ) . exists ( ) : <EOL> raise serializers . ValidationError ( '<STR_LIT>' ) <EOL> return attrs <EOL> def validate ( self , attrs ) : <EOL> for field in settings . SENTRY_MANAGED_USER_FIELDS : <EOL> attrs . pop ( field , None ) <EOL> attrs = super ( UserSerializer , self ) . validate ( attrs ) <EOL> return attrs <EOL> class AdminUserSerializer ( BaseUserSerializer ) : <EOL> isActive = serializers . BooleanField ( source = '<STR_LIT>' ) <EOL> class Meta : <EOL> model = User <EOL> fields = ( '<STR_LIT:name>' , '<STR_LIT:username>' , '<STR_LIT>' , '<STR_LIT:email>' ) <EOL> class UserDetailsEndpoint ( UserEndpoint ) : <EOL> def get ( self , request , user ) : <EOL> data = serialize ( user , request . user ) <EOL> return Response ( data ) <EOL> def put ( self , request , user ) : <EOL> if request . is_superuser ( ) : <EOL> serializer_cls = AdminUserSerializer <EOL> else : <EOL> serializer_cls = UserSerializer <EOL> serializer = serializer_cls ( user , data = request . DATA , partial = True ) <EOL> if serializer . is_valid ( ) : <EOL> user = serializer . save ( ) <EOL> return Response ( serialize ( user , request . user ) ) <EOL> return Response ( serializer . errors , status = status . HTTP_400_BAD_REQUEST ) </s>
