def test_improperly_scoped_token_can_not_create_or_email( self, mock_auth, mock_mail, app, user, email_unconfirmed, data, url_base): token = ApiOAuth2PersonalToken( owner=user, name='Unauthorized Token', ) token.save() scope = ApiOAuth2ScopeFactory() scope.name = 'unauthorized scope' scope.save() token.scopes.add(scope) mock_cas_resp = CasResponse(authenticated=True, user=user._id, attributes={ 'accessToken': token.token_id, 'accessTokenScope': [s.name for s in token.scopes.all()] }) mock_auth.return_value = user, mock_cas_resp assert OSFUser.objects.filter(username=email_unconfirmed).count() == 0 res = app.post_json_api( '{}?send_email=true'.format(url_base), data, headers={'Authorization': 'Bearer {}'.format(token.token_id)}, expect_errors=True) assert res.status_code == 403 assert OSFUser.objects.filter(username=email_unconfirmed).count() == 0 assert mock_mail.call_count == 0
def test_admin_scoped_token_can_create_and_send_email( self, mock_auth, mock_mail, app, user, email_unconfirmed, data, url_base): token = ApiOAuth2PersonalToken( owner=user, name='Admin Token', ) scope = ApiOAuth2ScopeFactory() scope.name = 'osf.admin' scope.save() token.scopes.add(scope) mock_cas_resp = CasResponse(authenticated=True, user=user._id, attributes={ 'accessToken': token.token_id, 'accessTokenScope': [s.name for s in token.scopes.all()] }) mock_auth.return_value = user, mock_cas_resp assert OSFUser.objects.filter(username=email_unconfirmed).count() == 0 res = app.post_json_api( '{}?send_email=true'.format(url_base), data, headers={'Authorization': 'Bearer {}'.format(token.token_id)}) assert res.status_code == 201 assert res.json['data']['attributes']['username'] == email_unconfirmed assert OSFUser.objects.filter(username=email_unconfirmed).count() == 1 assert mock_mail.call_count == 1
def test_properly_scoped_token_can_create_without_username_but_not_send_email( self, mock_auth, mock_mail, app, user, data, url_base): token = ApiOAuth2PersonalToken(owner=user, name='Authorized Token', scopes='osf.users.create') mock_cas_resp = CasResponse(authenticated=True, user=user._id, attributes={ 'accessToken': token.token_id, 'accessTokenScope': [s for s in token.scopes.split(' ')] }) mock_auth.return_value = user, mock_cas_resp data['data']['attributes'] = {'full_name': 'No Email'} assert OSFUser.objects.filter(fullname='No Email').count() == 0 res = app.post_json_api( '{}?send_email=true'.format(url_base), data, headers={'Authorization': 'Bearer {}'.format(token.token_id)}) assert res.status_code == 201 username = res.json['data']['attributes']['username'] try: UUID(username) except ValueError: raise AssertionError('Username is not a valid UUID') assert OSFUser.objects.filter(fullname='No Email').count() == 1 assert mock_mail.call_count == 0
def test_non_admin_scoped_token_does_not_have_admin(self, mock_auth): token = ApiOAuth2PersonalToken( owner=self.user, name='Admin Token', scopes=' '.join([key for key in public_scopes if key != 'osf.admin']) ) mock_cas_resp = CasResponse( authenticated=True, user=self.user._id, attributes={ 'accessToken': token.token_id, 'accessTokenScope': [s for s in token.scopes.split(' ')] } ) mock_auth.return_value = self.user, mock_cas_resp res = self.app.get( self.url, headers={ 'Authorization': 'Bearer {}'.format(token.token_id) } ) assert_equal(res.status_code, 200) assert_not_in('admin', res.json['meta'].keys())
def test_admin_scoped_token_has_admin(self, mock_auth): token = ApiOAuth2PersonalToken( owner=self.user, name='Admin Token', ) token.save() scope = ApiOAuth2ScopeFactory() scope.name = 'osf.admin' scope.save() token.scopes.add(scope) mock_cas_resp = CasResponse(authenticated=True, user=self.user._id, attributes={ 'accessToken': token.token_id, 'accessTokenScope': [s.name for s in token.scopes.all()] }) mock_auth.return_value = self.user, mock_cas_resp res = self.app.get( self.url, headers={'Authorization': 'Bearer {}'.format(token.token_id)}) assert_equal(res.status_code, 200) assert_equal(res.json['meta'][ADMIN], True)
def test_properly_scoped_token_does_not_send_email_without_kwarg( self, mock_auth, mock_mail, app, user, email_unconfirmed, data, url_base): token = ApiOAuth2PersonalToken(owner=user, name='Authorized Token', scopes='osf.users.create') mock_cas_resp = CasResponse(authenticated=True, user=user._id, attributes={ 'accessToken': token.token_id, 'accessTokenScope': [s for s in token.scopes.split(' ')] }) mock_auth.return_value = user, mock_cas_resp assert OSFUser.objects.filter(username=email_unconfirmed).count() == 0 res = app.post_json_api( url_base, data, headers={'Authorization': 'Bearer {}'.format(token.token_id)}) assert res.status_code == 201 assert res.json['data']['attributes']['username'] == email_unconfirmed assert OSFUser.objects.filter(username=email_unconfirmed).count() == 1 assert mock_mail.call_count == 0
def create(self, validated_data): validate_requested_scopes(validated_data) instance = ApiOAuth2PersonalToken(**validated_data) try: instance.save() except ValidationError as e: detail = format_validation_error(e) raise exceptions.ValidationError(detail=detail) return instance
def create(self, validated_data): scopes = validate_requested_scopes(validated_data.pop('scopes', None)) if not scopes: raise exceptions.ValidationError( 'Cannot create a token without scopes.') instance = ApiOAuth2PersonalToken(**validated_data) try: instance.save() except ValidationError as e: detail = format_validation_error(e) raise exceptions.ValidationError(detail=detail) for scope in scopes: instance.scopes.add(scope) return instance
def personal_access_token_detail(auth, **kwargs): """Show detail for a single personal access token""" _id = kwargs.get('_id') # The ID must be an active and existing record, and the logged-in user must have permission to view it. try: record = ApiOAuth2PersonalToken.find_one(Q('_id', 'eq', _id)) except NoResultsFound: raise HTTPError(http.NOT_FOUND) if record.owner != auth.user: raise HTTPError(http.FORBIDDEN) if record.is_active is False: raise HTTPError(http.GONE) token_detail_url = api_v2_url('tokens/{}/'.format(_id)) # Send request to this URL return {'token_list_url': '', 'token_detail_url': token_detail_url, 'scope_options': get_available_scopes()}
def personal_access_token_detail(auth, **kwargs): """Show detail for a single personal access token""" _id = kwargs.get('_id') # The ID must be an active and existing record, and the logged-in user must have permission to view it. try: record = ApiOAuth2PersonalToken.find_one(Q('_id', 'eq', _id)) except NoResultsFound: raise HTTPError(http.NOT_FOUND) if record.owner != auth.user: raise HTTPError(http.FORBIDDEN) if record.is_active is False: raise HTTPError(http.GONE) token_detail_url = api_v2_url( 'tokens/{}/'.format(_id)) # Send request to this URL return { 'token_list_url': '', 'token_detail_url': token_detail_url, 'scope_options': get_available_scopes() }
def get_queryset(self): query = self.get_query_from_request() return ApiOAuth2PersonalToken.find(query)
def create(self, validated_data): validate_requested_scopes(validated_data) instance = ApiOAuth2PersonalToken(**validated_data) instance.save() return instance
def get_queryset(self): query = self.get_query_from_request() return ApiOAuth2PersonalToken.find(query)