11import hashlib
22
33import uuid_utils .compat as uuid
4+ from django .core .exceptions import ObjectDoesNotExist
45from django .db .models import QuerySet
56from django .utils import timezone
67from django .utils .translation import gettext_lazy as _
1415
1516
1617class ApplicationKeySerializerModel (serializers .ModelSerializer ):
18+ user = serializers .SerializerMethodField ()
19+
1720 class Meta :
1821 model = ApplicationApiKey
1922 fields = "__all__"
2023
24+ @staticmethod
25+ def get_user (obj ):
26+ if not obj .user_id :
27+ return None
28+ try :
29+ user = obj .user
30+ except ObjectDoesNotExist :
31+ return None
32+ return {
33+ "id" : obj .user_id ,
34+ "username" : user .username ,
35+ "nick_name" : user .nick_name ,
36+ }
37+
2138
2239class EditApplicationKeySerializer (serializers .Serializer ):
2340 is_active = serializers .BooleanField (required = False , label = _ ("Availability" ))
@@ -36,6 +53,7 @@ class EditApplicationKeySerializer(serializers.Serializer):
3653class ApplicationKeySerializer (serializers .Serializer ):
3754 workspace_id = serializers .CharField (required = False , allow_null = True , allow_blank = True , label = _ ("Workspace ID" ))
3855 application_id = serializers .UUIDField (required = True , label = _ ('application id' ))
56+ user_id = serializers .UUIDField (required = False , allow_null = True , label = _ ('user id' ))
3957 order_by = serializers .CharField (required = False , label = _ ('order by' ), allow_null = True , allow_blank = True )
4058
4159 def is_valid (self , * , raise_exception = False ):
@@ -51,18 +69,20 @@ def generate(self, with_valid=True):
5169 if with_valid :
5270 self .is_valid (raise_exception = True )
5371 application_id = self .data .get ("application_id" )
72+ user_id = self .data .get ("user_id" )
5473 secret_key = 'agent-' + hashlib .md5 (str (uuid .uuid7 ()).encode ()).hexdigest ()
5574 application_api_key = ApplicationApiKey (id = uuid .uuid7 (),
5675 secret_key = secret_key ,
57- application_id = application_id )
76+ application_id = application_id ,
77+ user_id = user_id )
5878 application_api_key .save ()
5979 return ApplicationKeySerializerModel (application_api_key ).data
6080
6181 def page (self , current_page : int , page_size : int , with_valid = True ):
6282 if with_valid :
6383 self .is_valid (raise_exception = True )
6484 application_id = self .data .get ("application_id" )
65- query_set = QuerySet (ApplicationApiKey ).filter (application_id = application_id )
85+ query_set = QuerySet (ApplicationApiKey ).filter (application_id = application_id ). select_related ( 'user' )
6686 order_by = '-create_time' if self .data .get ('order_by' ) is None or self .data .get (
6787 'order_by' ) == '' else self .data .get ('order_by' )
6888 query_set = query_set .order_by (order_by )
0 commit comments