mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-01-24 08:14:16 +03:00
Implement option to reset User token
This commit is contained in:
parent
34c38e0cfe
commit
d2459710ca
|
@ -9,19 +9,33 @@ UserModel = get_user_model()
|
|||
class Command(BaseCommand):
|
||||
help = 'Create DRF Token for a given user'
|
||||
|
||||
def create_user_token(self, username):
|
||||
def create_user_token(self, username, reset_token):
|
||||
user = UserModel._default_manager.get_by_natural_key(username)
|
||||
|
||||
if reset_token:
|
||||
Token.objects.filter(user=user).delete()
|
||||
|
||||
token = Token.objects.get_or_create(user=user)
|
||||
return token[0]
|
||||
|
||||
def add_arguments(self, parser):
|
||||
parser.add_argument('username', type=str, nargs='+')
|
||||
|
||||
parser.add_argument(
|
||||
'-r',
|
||||
'--reset',
|
||||
action='store_true',
|
||||
dest='reset_token',
|
||||
default=False,
|
||||
help='Reset existing User token and create a new one',
|
||||
)
|
||||
|
||||
def handle(self, *args, **options):
|
||||
username = options['username']
|
||||
reset_token = options['reset_token']
|
||||
|
||||
try:
|
||||
token = self.create_user_token(username)
|
||||
token = self.create_user_token(username, reset_token)
|
||||
except UserModel.DoesNotExist:
|
||||
raise CommandError(
|
||||
'Cannot create the Token: user {0} does not exist'.format(
|
||||
|
|
|
@ -44,11 +44,27 @@ class AuthTokenCommandTests(TestCase):
|
|||
self.user = User.objects.create_user(username='test_user')
|
||||
|
||||
def test_command_create_user_token(self):
|
||||
token = AuthTokenCommand().create_user_token(self.user.username)
|
||||
token = AuthTokenCommand().create_user_token(self.user.username, False)
|
||||
assert token is not None
|
||||
token_saved = Token.objects.first()
|
||||
assert token.key == token_saved.key
|
||||
|
||||
def test_command_create_user_token_invalid_user(self):
|
||||
with pytest.raises(User.DoesNotExist):
|
||||
AuthTokenCommand().create_user_token('not_existing_user')
|
||||
AuthTokenCommand().create_user_token('not_existing_user', False)
|
||||
|
||||
def test_command_reset_user_token(self):
|
||||
AuthTokenCommand().create_user_token(self.user.username, False)
|
||||
first_token_key = Token.objects.first().key
|
||||
AuthTokenCommand().create_user_token(self.user.username, True)
|
||||
second_token_key = Token.objects.first().key
|
||||
|
||||
assert first_token_key != second_token_key
|
||||
|
||||
def test_command_do_not_reset_user_token(self):
|
||||
AuthTokenCommand().create_user_token(self.user.username, False)
|
||||
first_token_key = Token.objects.first().key
|
||||
AuthTokenCommand().create_user_token(self.user.username, False)
|
||||
second_token_key = Token.objects.first().key
|
||||
|
||||
assert first_token_key == second_token_key
|
||||
|
|
Loading…
Reference in New Issue
Block a user