from django.contrib.auth.models import User # django default user model
# Use following instead for customized user from django.contrib.auth.models import AbstractUser # use inherit property to modify complex model
#get current user from django.contrib.auth import get_user_model
User = get._user_model() #return a current user class
classToken(models.Model):
# user UUID to define token, id equals to model's name # primary_key=True refers to using this name as id in DATABASE # default refers to automatically calling a generator function every time a new token is generated, if we wish not to provide the duplicatedcommand every time id = models.UUIDFiled(primary_key=True, default=uid.uuid4)
# let id has one-to-one relationship with a user # user = models.ForeignKey(User, on_delete=models.CASCADE) # to specify that token will be deleted as user is deleted
Use a controller to manage login
我们需要设计一个 controller 来配合 token 进行登录
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#app -> veiws.py
from django.http.response import JsonResponse
defindex(request, *args, **kwargs): # judger if current user has logged in using self-contained method in django if request.user.is_authenticated:# return T/F return JsonResponse({ # request.user returns the current user class, within information like username 'username': request.user.username, }) else: return JsonResponse({ 'message': "not Authenticated", }, status=401)
from django.core.management.base import BaseCommand from authtoken.models import Token from django.contrib.auth import get_user_model
classCommand(BaseCommand):
# a complete command includes command name and arguments,like: npm run serve, where run is a command, and serve is the argument # now the command is token, here we can specify the arguments defadd_arguments(self, parser): # add receivers of argument parser.add_argument( 'action', help="blabla" )
parser.add_argument( '--user', # a format of optional arguments )
returnsuper().add_arguments(parser)
# we will handle the received arguments here # the argument option stores the args that user send from cmd,in coordinate with the args defined in function add_arguments defhandle(self, action *args, **options): # designate which function to handle an argument actions = { 'list': self.list_token, 'generate': self.generate_token, } if action in actions.keys(): raise CommandError("unsupported actions")
# call these functions according to user's input (we stored it in action, or in options[action]) actions[action](*args, *options)
# to generate a token, we need to add a optional arguments defgenerate_token(self, *args, **options): user = self.fet_user(*args,**options) # we have defined the token model to have to arguments, user and id ,while id is defaulted to have a generated function, so we only need to provide a user
token = Token(user=user) token.save() self.print_token(token) self.stdout.write(self.style.SUCCESS('successfully generate a token'))
defget_user(self, *args, **options): # get user input # since we only generate token for registered user, we need to look for him in the database: if options['user']: username_or_id = options['user'] # get all users User = get_user_model() # find user: compare input with database try: user = User.objects.filter(pk=username_or_id).get() except (User.DoesNotExist, valueError): try: user=User.objects.Filter(username=username_or_id).get() except: User.DoeseNotExist("balbal") # return user if we find him in database return user
to design a command, first we need to design argument receiver according if needed, then we use these inputs to implement the according handler function
interaction methods:
1 2 3 4 5 6
defhandler_function(self, *args, **kwargs): # need user's input confirm = input(self.style.ERROR('some txt')) # judge according to user's input if comfirm != 'y': self.stdout.write('exit')