Python rest_framework.authtoken.models.Token() Examples
The following are 30
code examples of rest_framework.authtoken.models.Token().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
rest_framework.authtoken.models
, or try the search function
.
Example #1
Source File: test_config.py From controller with MIT License | 6 votes |
def test_unauthorized_user_cannot_modify_config(self, mock_requests): """ An unauthorized user should not be able to modify other config. Since an unauthorized user can't access the application, these requests should return a 403. """ app_id = self.create_app() unauthorized_user = User.objects.get(username='autotest2') unauthorized_token = Token.objects.get(user=unauthorized_user).key self.client.credentials(HTTP_AUTHORIZATION='Token ' + unauthorized_token) url = '/v2/apps/{}/config'.format(app_id) body = {'values': {'FOO': 'bar'}} response = self.client.post(url, body) self.assertEqual(response.status_code, 403)
Example #2
Source File: test_config.py From controller with MIT License | 6 votes |
def test_admin_can_create_config_on_other_apps(self, mock_requests): """If a non-admin creates an app, an administrator should be able to set config values for that app. """ user = User.objects.get(username='autotest2') token = Token.objects.get(user=user).key self.client.credentials(HTTP_AUTHORIZATION='Token ' + token) app_id = self.create_app() url = "/v2/apps/{app_id}/config".format(**locals()) # set an initial config value self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token) body = {'values': json.dumps({'PORT': '5000'})} response = self.client.post(url, body) self.assertEqual(response.status_code, 201, response.data) self.assertIn('PORT', response.data['values']) return response
Example #3
Source File: views.py From onehome-server with MIT License | 6 votes |
def post(self, request, format=None): data = request.data filetype = data.get('filetype') # if request.user.is_authenticated: # 构建鉴权对象 q = Auth(configs.get('qiniu').get('AK'), configs.get('qiniu').get('SK')) # 生成图片名 salt = ''.join(random.sample(string.ascii_letters + string.digits, 8)) key = salt + '_' + str(int(time.time())) + '.' + filetype # 生成上传 Token,可以指定过期时间等 token = q.upload_token(configs.get('qiniu').get('bucket_name'), key, 3600) return Response({"stateCode": 200, "token": token, "key": key}, 200) # else: # return Response({"stateCode": 201, "msg": "您没有权限执行此操作"}, 201) # 上传用户头像
Example #4
Source File: test_pods.py From controller with MIT License | 6 votes |
def test_scale_with_unauthorized_user_returns_403(self, mock_requests): """An unauthorized user should not be able to access an app's resources. If an unauthorized user is trying to scale an app he or she does not have access to, it should return a 403. """ app_id = self.create_app() # post a new build url = "/v2/apps/{app_id}/builds".format(**locals()) body = { 'image': 'autotest/example', 'sha': 'a'*40, 'procfile': {'web': 'node server.js', 'worker': 'node worker.js'} } response = self.client.post(url, body) unauthorized_user = User.objects.get(username='autotest2') unauthorized_token = Token.objects.get(user=unauthorized_user).key self.client.credentials(HTTP_AUTHORIZATION='Token ' + unauthorized_token) # scale up with unauthorized user url = "/v2/apps/{app_id}/scale".format(**locals()) body = {'web': 4} response = self.client.post(url, body) self.assertEqual(response.status_code, 403)
Example #5
Source File: test_build.py From controller with MIT License | 6 votes |
def test_unauthorized_user_cannot_modify_build(self, mock_requests): """ An unauthorized user should not be able to modify other builds. Since an unauthorized user can't access the application, these requests should return a 403. """ app_id = self.create_app() unauthorized_user = User.objects.get(username='autotest2') unauthorized_token = Token.objects.get(user=unauthorized_user).key self.client.credentials(HTTP_AUTHORIZATION='Token ' + unauthorized_token) url = '/v2/apps/{}/builds'.format(app_id) body = {'image': 'foo'} response = self.client.post(url, body) self.assertEqual(response.status_code, 403)
Example #6
Source File: test_domain.py From controller with MIT License | 6 votes |
def test_unauthorized_user_cannot_modify_domain(self): """ An unauthorized user should not be able to modify other domains. Since an unauthorized user should not know about the application at all, these requests should return a 404. """ app_id = self.create_app() unauthorized_user = User.objects.get(username='autotest2') unauthorized_token = Token.objects.get(user=unauthorized_user).key self.client.credentials(HTTP_AUTHORIZATION='Token ' + unauthorized_token) url = '/v2/apps/{}/domains'.format(app_id) response = self.client.post(url, {'domain': 'example.com'}) self.assertEqual(response.status_code, 403)
Example #7
Source File: test_auth.py From controller with MIT License | 6 votes |
def test_regenerate(self): """ Test that token regeneration works""" url = '/v2/auth/tokens/' self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.admin_token) response = self.client.post(url, {}) self.assertEqual(response.status_code, 200, response.data) self.assertNotEqual(response.data['token'], self.admin_token) self.admin_token = Token.objects.get(user=self.admin).key self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.admin_token) response = self.client.post(url, {"username": "autotest2"}) self.assertEqual(response.status_code, 200, response.data) self.assertNotEqual(response.data['token'], self.user1_token) response = self.client.post(url, {"all": "true"}) self.assertEqual(response.status_code, 200, response.data) response = self.client.post(url, {}) self.assertEqual(response.status_code, 401, response.data)
Example #8
Source File: api_views.py From django-aws-template with MIT License | 6 votes |
def get(self, request, format=None): """ Update thumbnail and tiny file field """ if request.user.is_anonymous: # User most login before they can get a token # This not only ensures the user has registered, and has an account # but that the account is active return Response('User not recognized.', status=status.HTTP_403_FORBIDDEN) account = request.user serialized = AccountSerializer(account) data = serialized.data # Add the token to the return serialization try: token = Token.objects.get(user=account) except: token = Token.objects.create(user=account) data['token'] = token.key return Response(data)
Example #9
Source File: api_views.py From django-aws-template with MIT License | 6 votes |
def get(self, request, format=None): """ Update thumbnail and tiny file field """ if request.user.is_anonymous: # User most login before they can get a token # This not only ensures the user has registered, and has an account # but that the account is active return Response('User not recognized.', status=status.HTTP_403_FORBIDDEN) data_dic = {} try: token = Token.objects.get(user=request.user) mystatus = status.HTTP_200_OK except: token = Token.objects.create(user=request.user) mystatus = status.HTTP_201_CREATED data_dic['token'] = token.key return Response(data_dic, status=mystatus)
Example #10
Source File: test_mixins.py From drf-tracking with ISC License | 6 votes |
def test_log_auth_inactive_user(self): # set up inactive user with token user = User.objects.create_user(username='myname', password='secret') token = Token.objects.create(user=user) token_header = 'Token %s' % token.key user.is_active = False user.save() # force login because regular client.login doesn't work for inactive users self.client.get('/token-auth-logging', HTTP_AUTHORIZATION=token_header) # test log = APIRequestLog.objects.first() self.assertIsNone(log.user) self.assertIn("User inactive or deleted", log.response)
Example #11
Source File: test_hooks.py From controller with MIT License | 6 votes |
def test_admin_can_hook(self, mock_requests): """Administrator should be able to create build hooks on non-admin apps. """ """Test creating a Push via the API""" user = User.objects.get(username='autotest2') token = Token.objects.get(user=user).key self.client.credentials(HTTP_AUTHORIZATION='Token ' + token) app_id = self.create_app() # prepare a push body DOCKERFILE = """ FROM busybox CMD /bin/true """ body = {'receive_user': 'autotest', 'receive_repo': app_id, 'image': '{app_id}:v2'.format(**locals()), 'sha': 'ecdff91c57a0b9ab82e89634df87e293d259a3aa', 'dockerfile': DOCKERFILE} url = '/v2/hooks/build' response = self.client.post(url, body, HTTP_X_DEIS_BUILDER_AUTH=settings.BUILDER_KEY) self.assertEqual(response.status_code, 200, response.data) self.assertEqual(response.data['release']['version'], 2)
Example #12
Source File: test_build.py From controller with MIT License | 6 votes |
def test_admin_can_create_builds_on_other_apps(self, mock_requests): """If a user creates an application, an administrator should be able to push builds. """ # create app as non-admin user = User.objects.get(username='autotest2') token = Token.objects.get(user=user).key self.client.credentials(HTTP_AUTHORIZATION='Token ' + token) app_id = self.create_app() # post a new build as admin self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token) url = "/v2/apps/{app_id}/builds".format(**locals()) body = {'image': 'autotest/example'} response = self.client.post(url, body) self.assertEqual(response.status_code, 201, response.data) build = Build.objects.get(uuid=response.data['uuid']) self.assertEqual(str(build), "{}-{}".format( response.data['app'], str(response.data['uuid'])[:7]))
Example #13
Source File: test_perm.py From controller with MIT License | 6 votes |
def test_unauthorized_user_cannot_modify_perms(self): """ An unauthorized user should not be able to modify other apps' permissions. Since an unauthorized user should not know about the application at all, these requests should return a 404. """ app_id = 'autotest' url = '/v2/apps' body = {'id': app_id} response = self.client.post(url, body) url = '{}/{}/perms'.format(url, app_id) body = {'username': self.user2.username} self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token2) response = self.client.post(url, body) self.assertEqual(response.status_code, 403)
Example #14
Source File: test_release.py From controller with MIT License | 6 votes |
def test_admin_can_create_release(self, mock_requests): """If a non-user creates an app, an admin should be able to create releases.""" user = User.objects.get(username='autotest2') token = Token.objects.get(user=user).key self.client.credentials(HTTP_AUTHORIZATION='Token ' + token) app_id = self.create_app() # check that updating config rolls a new release url = '/v2/apps/{app_id}/config'.format(**locals()) body = {'values': json.dumps({'NEW_URL1': 'http://localhost:8080/'})} self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token) response = self.client.post(url, body) self.assertEqual(response.status_code, 201, response.data) self.assertIn('NEW_URL1', response.data['values']) # check to see that an initial release was created url = '/v2/apps/{app_id}/releases'.format(**locals()) response = self.client.get(url) self.assertEqual(response.status_code, 200, response.data) # account for the config release as well self.assertEqual(response.data['count'], 2)
Example #15
Source File: test_certificate_use_case_2.py From controller with MIT License | 6 votes |
def setUp(self): self.user = User.objects.get(username='autotest') self.token = Token.objects.get(user=self.user).key self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token) self.url = '/v2/certs' self.app = App.objects.create(owner=self.user, id='test-app-use-case-2') self.domains = { 'foo.com': Domain.objects.create(owner=self.user, app=self.app, domain='foo.com'), 'bar.com': Domain.objects.create(owner=self.user, app=self.app, domain='bar.com'), } # only foo.com has a cert self.domain = 'foo.com' self.certificates = {self.domain: {'name': self.domain.replace('.', '-')}} with open('{}/certs/{}.key'.format(TEST_ROOT, self.domain)) as f: self.certificates[self.domain]['key'] = f.read() with open('{}/certs/{}.cert'.format(TEST_ROOT, self.domain)) as f: self.certificates[self.domain]['cert'] = f.read() # add expires and fingerprints self.certificates['foo.com']['expires'] = '2017-01-14T23:55:59Z' self.certificates['foo.com']['fingerprint'] = 'AC:82:58:80:EA:C4:B9:75:C1:1C:52:48:40:28:15:1D:47:AC:ED:88:4B:D4:72:95:B2:C0:A0:DF:4A:A7:60:B6' # noqa
Example #16
Source File: expiry_token_authentication.py From substra-backend with Apache License 2.0 | 5 votes |
def authenticate_credentials(self, key): _, token = super(ExpiryTokenAuthentication, self).authenticate_credentials(key) is_expired = is_token_expired(token) if is_expired: token.delete() raise AuthenticationFailed('The Token is expired') return token.user, token
Example #17
Source File: tests.py From DRF-TDD-example with MIT License | 5 votes |
def test_delete_current(self): response = self.client.delete(self.url('current')) self.assertEqual(204, response.status_code) self.assertFalse(Token.objects.filter(key=self.token.key).exists())
Example #18
Source File: tests.py From DRF-TDD-example with MIT License | 5 votes |
def test_delete_by_key(self): response = self.client.delete(self.url(self.token.key)) self.assertEqual(204, response.status_code) self.assertFalse(Token.objects.filter(key=self.token.key).exists())
Example #19
Source File: tests.py From DRF-TDD-example with MIT License | 5 votes |
def test_delete_unauthorized(self): response = self.client.delete(self.url(self.token_2.key)) self.assertEqual(404, response.status_code) self.assertTrue(Token.objects.filter(key=self.token_2.key).exists())
Example #20
Source File: test_api.py From GovLens with MIT License | 5 votes |
def test_POST_Authorized(self): user = User.objects.create_user( username="test", email="test@test.test", password="test" ) token = Token.objects.create(user=user) data = {"id": 5, "name": "Test POST Agency"} self.client.credentials(HTTP_AUTHORIZATION="Token " + token.key) response = self.client.post("/api/agencies/", data=data, format="json") self.assertEqual(201, response.status_code) json_response = json.loads(response.content.decode("utf-8")) expected_results = { "id": 5, "name": "Test POST Agency", "website": "", "twitter": "", "facebook": "", "phone_number": "", "address": "", "description": "", "notes": "", "last_successful_scrape": None, "scrape_counter": 0, } self.assertEqual(json_response, expected_results)
Example #21
Source File: expiry_token_authentication.py From substra-backend with Apache License 2.0 | 5 votes |
def token_expire_handler(token): is_expired = is_token_expired(token) if is_expired: token.delete() token = Token.objects.create(user=token.user) return is_expired, token
Example #22
Source File: test_login_logout_api.py From karrot-backend with GNU Affero General Public License v3.0 | 5 votes |
def test_use_token(self): token = Token.objects.create(user=self.user) response = self.client.get('/api/auth/user/', **{'HTTP_AUTHORIZATION': 'Token {}'.format(token.key)}) self.assertEqual(response.status_code, status.HTTP_200_OK, response.data) self.assertEqual(response.data['email'], self.user.email)
Example #23
Source File: test_login_logout_api.py From karrot-backend with GNU Affero General Public License v3.0 | 5 votes |
def test_get_token(self): response = self.client.post(self.url, {'username': self.user.email, 'password': self.user.display_name}) self.assertEqual(response.status_code, status.HTTP_200_OK) token = Token.objects.filter(user=self.user).first() self.assertEqual(response.data, {'token': token.key})
Example #24
Source File: test_api.py From django-celery-inspect with MIT License | 5 votes |
def test_200_celery_inspect_scheduled(self): self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key) response = self.client.get(reverse('celery_inspect:scheduled')) self.assertEqual(response.status_code, status.HTTP_200_OK)
Example #25
Source File: test_api.py From django-celery-inspect with MIT License | 5 votes |
def test_501_celery_inspect_active_status(self): if "djcelery" not in settings.INSTALLED_APPS: self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key) response = self.client.get(reverse('celery_inspect:active_status')) self.assertEqual(response.status_code, status.HTTP_501_NOT_IMPLEMENTED)
Example #26
Source File: test_api.py From django-celery-inspect with MIT License | 5 votes |
def test_404_celery_inspect_active_status(self): if "djcelery" in settings.INSTALLED_APPS: from djcelery.models import WorkerState self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key) WorkerState.objects.create(hostname='worker1@localhot:8000') response = self.client.get(reverse('celery_inspect:active_status')) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
Example #27
Source File: test_api.py From django-celery-inspect with MIT License | 5 votes |
def test_200_celery_inspect_active(self): self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key) response = self.client.get(reverse('celery_inspect:active')) self.assertEqual(response.status_code, status.HTTP_200_OK)
Example #28
Source File: test_api.py From django-celery-inspect with MIT License | 5 votes |
def test_200_celery_inspect_ping(self): self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key) response = self.client.get(reverse('celery_inspect:ping')) self.assertEqual(response.status_code, status.HTTP_200_OK)
Example #29
Source File: test_api.py From django-celery-inspect with MIT License | 5 votes |
def setUp(self): self.client = APIClient(enforce_csrf_checks=True) self.user = get_user_model().objects.create_user( name='test', email='test@example.com', password='safe#passw0rd!' ) self.token = Token.objects.get(user=self.user)
Example #30
Source File: views.py From FIR with GNU General Public License v3.0 | 5 votes |
def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance)