def test_get_token_by_not_existed_username(self): self._set_user_settings() token_backend = InMemoryTokenBackend() user_model = UserSQLiteModel() user = self._create_simple_user(user_model) token_backend.save('api', 'my_test_token', user_id=user.id) token = token_backend.get_token_by_username('unknown', user.username) self.assertEqual(token, {})
def test_get_token_by_username(self): self._set_user_settings() token_backend = InMemoryTokenBackend() user_model = UserSQLiteModel() user = self._create_simple_user(user_model) token_data = { 'name': 'api', 'token': 'my_test_token', 'user_id': user.id } token_backend.save( token_data['name'], token_data['token'], user_id=token_data['user_id'] ) db_token = token_backend.get_token_by_username('api', user.username) self.assertEqual(db_token['name'], token_data['name']) self.assertEqual(db_token['token'], token_data['token']) self.assertEqual(db_token['user_id'], token_data['user_id'])
class LogIn(MethodBasedView): token_manager = JSONWebTokenManager() token_backend = InMemoryTokenBackend() user_manager = UserSQLiteModel() def get_or_create_token(self, user, *args, **kwargs): def get_token(user): return self.token_backend.get_token_by_username( 'admin', username=user.username ) def create_token(user, *args, **kwargs): jwt_kwargs = { "iss": "aiorest-ws", "exp": 60, "name": kwargs.get('username'), "authorized": True, "token_name": "admin" } kwargs.update(jwt_kwargs) api_token = self.token_manager.generate({}, **kwargs) self.token_backend.save('admin', api_token, user_id=user.id) return api_token return get_token(user) or create_token(user, *args, **kwargs) def post(self, request, *args, **kwargs): user = self.user_manager.get_user_by_username( request.data['username'], with_id=True ) if user.is_authenticated: api_token = self.get_or_create_token(user, *args, **kwargs) else: api_token = None return {'token': api_token}
def test_save(self): self._set_user_settings() token_backend = InMemoryTokenBackend() user_model = UserSQLiteModel() user = self._create_simple_user(user_model) token_backend.save('api', 'my_test_token', user_id=user.id)
def test_get_not_existed_token(self): self._set_user_settings() backend = InMemoryTokenBackend() user_model = UserSQLiteModel() # NOQA db_token = backend.get('unknown_token') self.assertEqual(db_token, {})
def test_init_with_user_settings(self): self._set_user_settings() backend = InMemoryTokenBackend() # NOQA
def test_init_by_default(self): settings.DATABASES = {} backend = InMemoryTokenBackend() # NOQA
def test_get_not_existed_token(self): self._set_user_settings() backend = InMemoryTokenBackend() db_token = backend.get('unknown_token') self.assertEqual(db_token, {})