def test_pipeline_returns_json_response_on_post(self): """pipeline step renders json response for POST request and inactive user""" request = create_request(data={"username": "******"}) strategy = load_strategy(request=request) backend = GithubOAuth2(strategy, "/") response = require_activation( strategy=strategy, details={}, backend=backend, user=self.user, pipeline_index=1, ) self.assertEqual(response.status_code, 200) self.assertEqual(response["content-type"], "application/json") self.assertJsonResponseEquals( response, { "step": "done", "backend_name": "GitHub", "activation": "admin", "email": "*****@*****.**", "username": "******", }, )
def do_auth(self, *args, **kwargs): # type: (*Any, **Any) -> Optional[HttpResponse] kwargs['return_data'] = {} request = self.strategy.request kwargs['realm_subdomain'] = get_subdomain(request) user_profile = None team_id = settings.SOCIAL_AUTH_GITHUB_TEAM_ID org_name = settings.SOCIAL_AUTH_GITHUB_ORG_NAME if (team_id is None and org_name is None): user_profile = GithubOAuth2.do_auth(self, *args, **kwargs) elif (team_id): backend = GithubTeamOAuth2(self.strategy, self.redirect_uri) try: user_profile = backend.do_auth(*args, **kwargs) except AuthFailed: logging.info("User is not member of GitHub team.") user_profile = None elif (org_name): backend = GithubOrganizationOAuth2(self.strategy, self.redirect_uri) try: user_profile = backend.do_auth(*args, **kwargs) except AuthFailed: logging.info("User is not member of GitHub organization.") user_profile = None return self.process_do_auth(user_profile, *args, **kwargs)
class TestGithubSocialAuth(VCRTestCase): strategy = None backend = GithubOAuth2(strategy=strategy) access_token = 'censored' def test_fetch_permissions_is_admin(self): user = User() social_auth.fetch_github_permissions( strategy=self.strategy, details={'username': '******'}, user=user, backend=self.backend, response={'access_token': self.access_token}, ) self.assertTrue(user.is_superuser) def test_fetch_permissions_not_admin(self): user = User() social_auth.fetch_github_permissions( strategy=self.strategy, details={'username': '******'}, user=user, backend=self.backend, response={'access_token': self.access_token}, ) self.assertFalse(user.is_superuser)
def test_user_created_activation_by_admin_nonverified_email(self): """inactive user is created for non-verified email and activation by admin""" form_data = { 'email': '*****@*****.**', 'username': '******', } request = create_request(data=form_data) strategy = load_strategy(request=request) backend = GithubOAuth2(strategy, '/') result = create_user_with_form( strategy=strategy, details={'email': ''}, backend=backend, user=None, pipeline_index=1, ) new_user = UserModel.objects.get(email='*****@*****.**') self.assertEqual(result, {'user': new_user, 'is_new': True}) self.assertNewUserIsCorrect(new_user, form_data, activation='admin', email_verified=False)
def test_form_ignore_inactive_agreement(self): """social register ignores inactive agreement""" form_data = { "email": "*****@*****.**", "username": "******", "terms_of_service": None, } request = create_request(data=form_data) strategy = load_strategy(request=request) backend = GithubOAuth2(strategy, "/") Agreement.objects.create(type=Agreement.TYPE_TOS, text="Lorem ipsum", is_active=False) result = create_user_with_form( strategy=strategy, details={"email": form_data["email"]}, backend=backend, user=None, pipeline_index=1, ) new_user = User.objects.get(email="*****@*****.**") self.assertEqual(result, {"user": new_user, "is_new": True}) self.assertEqual(new_user.agreements, []) self.assertEqual(new_user.useragreement_set.count(), 0)
def test_form_ignore_inactive_agreement(self): """social register ignores inactive agreement""" form_data = { 'email': '*****@*****.**', 'username': '******', 'terms_of_service': None, } request = create_request(data=form_data) strategy = load_strategy(request=request) backend = GithubOAuth2(strategy, '/') Agreement.objects.create( type=Agreement.TYPE_TOS, text="Lorem ipsum", is_active=False, ) result = create_user_with_form( strategy=strategy, details={'email': form_data['email']}, backend=backend, user=None, pipeline_index=1, ) new_user = UserModel.objects.get(email='*****@*****.**') self.assertEqual(result, {'user': new_user, 'is_new': True}) self.assertEqual(new_user.agreements, []) self.assertEqual(new_user.useragreement_set.count(), 0)
def test_skip_if_no_clean_username_passed(self): """pipeline step is skipped if cleaned username wasnt passed""" result = create_user( MockStrategy(), {'email': '*****@*****.**'}, GithubOAuth2(), ) self.assertIsNone(result)
def test_skip_if_email_is_taken(self): """pipeline step is skipped if email was taken""" result = create_user( MockStrategy(), {'email': self.user.email}, GithubOAuth2(), clean_username='******', ) self.assertIsNone(result)
def test_skip_if_no_email_passed(self): """pipeline step is skipped if no email was passed""" result = create_user( MockStrategy(), {}, GithubOAuth2(), clean_username='******', ) self.assertIsNone(result)
def test_partial_token_if_user_not_set_no_showstopper(self): """pipeline step handles set session token if user is not set""" request = create_request() strategy = load_strategy(request=request) strategy.request.session["partial_pipeline_token"] = "test-token" backend = GithubOAuth2(strategy, "/") require_activation(strategy=strategy, details={}, backend=backend, user=None, pipeline_index=1)
def test_skip_if_user_not_set(self): """pipeline step is skipped if user is not set""" request = create_request() strategy = load_strategy(request=request) backend = GithubOAuth2(strategy, "/") result = require_activation(strategy=strategy, details={}, backend=backend, user=None, pipeline_index=1) self.assertEqual(result, {})
def test_renders_form_if_not_post(self): """pipeline step renders form if not POST""" request = create_request() strategy = load_strategy(request=request) backend = GithubOAuth2(strategy, "/") response = create_user_with_form(strategy=strategy, details={}, backend=backend, user=None, pipeline_index=1) self.assertContains(response, "GitHub")
def test_user_created_activation_by_admin(self): """pipeline step creates in user for valid data and admin activation""" result = create_user( MockStrategy(), {"email": "*****@*****.**"}, GithubOAuth2(), clean_username="******", ) new_user = User.objects.get(email="*****@*****.**") self.assertEqual(result, {"user": new_user, "is_new": True}) self.assertEqual(new_user.username, "NewUser") self.assertNewUserIsCorrect(new_user, email_verified=True, activation="admin")
def test_skip_if_user_is_set(self): """pipeline step is skipped if user was passed""" request = create_request() strategy = load_strategy(request=request) backend = GithubOAuth2(strategy, '/') result = create_user_with_form( strategy=strategy, details={}, backend=backend, user=self.user, pipeline_index=1, ) self.assertEqual(result, {})
def test_user_created_activation_by_admin(self): """pipeline step creates in user for valid data and admin activation""" result = create_user( MockStrategy(), {'email': '*****@*****.**'}, GithubOAuth2(), clean_username='******', ) new_user = UserModel.objects.get(email='*****@*****.**') self.assertEqual(result, { 'user': new_user, 'is_new': True, }) self.assertEqual(new_user.username, 'NewUser') self.assertNewUserIsCorrect(new_user, email_verified=True, activation='admin')
def test_pipeline_returns_html_responseon_get(self): """pipeline step renders http response for GET request and inactive user""" request = create_request() strategy = load_strategy(request=request) backend = GithubOAuth2(strategy, '/') response = require_activation( strategy=strategy, details={}, backend=backend, user=self.user, pipeline_index=1, ) self.assertEqual(response.status_code, 200) self.assertEqual(response['content-type'], 'text/html; charset=utf-8')
def do_auth(self, *args, **kwargs): # type: (*Any, **Any) -> Optional[HttpResponse] """ This function is called once the OAuth2 workflow is complete. We override this function to: 1. Inject `return_data` and `realm_admin` kwargs. These will be used by `authenticate()` function to make the decision. 2. Call the proper `do_auth` function depending on whether we are doing individual, team or organization based GitHub authentication. The actual decision on authentication is done in SocialAuthMixin._common_authenticate(). """ kwargs['return_data'] = {} request = self.strategy.request kwargs['realm_subdomain'] = get_subdomain(request) user_profile = None team_id = settings.SOCIAL_AUTH_GITHUB_TEAM_ID org_name = settings.SOCIAL_AUTH_GITHUB_ORG_NAME if (team_id is None and org_name is None): try: user_profile = GithubOAuth2.do_auth(self, *args, **kwargs) except AuthFailed: logging.info("User authentication failed.") user_profile = None elif (team_id): backend = GithubTeamOAuth2(self.strategy, self.redirect_uri) try: user_profile = backend.do_auth(*args, **kwargs) except AuthFailed: logging.info("User is not member of GitHub team.") user_profile = None elif (org_name): backend = GithubOrganizationOAuth2(self.strategy, self.redirect_uri) try: user_profile = backend.do_auth(*args, **kwargs) except AuthFailed: logging.info("User is not member of GitHub organization.") user_profile = None return self.process_do_auth(user_profile, *args, **kwargs)
def test_empty_data_rejected(self): """form rejects empty data""" request = create_request(data={}) strategy = load_strategy(request=request) backend = GithubOAuth2(strategy, '/') response = create_user_with_form( strategy=strategy, details={}, backend=backend, user=None, pipeline_index=1, ) self.assertEqual(response.status_code, 400) self.assertJsonResponseEquals(response, { 'email': ["This field is required."], 'username': ["This field is required."], })
def test_skip_if_user_is_active(self): """pipeline step is skipped if user is active""" self.user.requires_activation = UserModel.ACTIVATION_NONE self.user.save() self.assertFalse(self.user.requires_activation) request = create_request() strategy = load_strategy(request=request) backend = GithubOAuth2(strategy, '/') result = require_activation( strategy=strategy, details={}, backend=backend, user=self.user, pipeline_index=1, ) self.assertEqual(result, {})
def test_taken_data_rejected(self): """form rejects taken data""" request = create_request(data={ 'email': self.user.email, 'username': self.user.username, }) strategy = load_strategy(request=request) backend = GithubOAuth2(strategy, '/') response = create_user_with_form( strategy=strategy, details={}, backend=backend, user=None, pipeline_index=1, ) self.assertEqual(response.status_code, 400) self.assertJsonResponseEquals(response, { 'email': ["This e-mail address is not available."], 'username': ["This username is not available."], })
def test_user_created_activation_by_admin_nonverified_email(self): """inactive user is created for non-verified email and activation by admin""" form_data = {"email": "*****@*****.**", "username": "******"} request = create_request(data=form_data) strategy = load_strategy(request=request) backend = GithubOAuth2(strategy, "/") result = create_user_with_form( strategy=strategy, details={"email": ""}, backend=backend, user=None, pipeline_index=1, ) new_user = User.objects.get(email="*****@*****.**") self.assertEqual(result, {"user": new_user, "is_new": True}) self.assertNewUserIsCorrect(new_user, form_data, activation="admin", email_verified=False)
def test_pipeline_returns_json_response_on_post(self): """pipeline step renders json response for POST request and inactive user""" request = create_request(data={'username': '******'}) strategy = load_strategy(request=request) backend = GithubOAuth2(strategy, '/') response = require_activation( strategy=strategy, details={}, backend=backend, user=self.user, pipeline_index=1, ) self.assertEqual(response.status_code, 200) self.assertEqual(response['content-type'], 'application/json') self.assertJsonResponseEquals(response, { 'step': 'done', 'backend_name': 'GitHub', 'activation': 'admin', 'email': '*****@*****.**', 'username': '******', })
def get_authenticated_user(self, *args: Any, **kwargs: Any) -> Optional[UserProfile]: """ This function is called once the OAuth2 workflow is complete. We override this function to call the proper `do_auth` function depending on whether we are doing individual, team or organization based GitHub authentication. The actual decision on authentication is done in SocialAuthMixin._common_authenticate(). """ user_profile = None team_id = settings.SOCIAL_AUTH_GITHUB_TEAM_ID org_name = settings.SOCIAL_AUTH_GITHUB_ORG_NAME if (team_id is None and org_name is None): try: user_profile = GithubOAuth2.do_auth(self, *args, **kwargs) except AuthFailed: logging.info("User authentication failed.") user_profile = None elif (team_id): backend = GithubTeamOAuth2(self.strategy, self.redirect_uri) try: user_profile = backend.do_auth(*args, **kwargs) except AuthFailed: logging.info("User is not member of GitHub team.") user_profile = None elif (org_name): backend = GithubOrganizationOAuth2(self.strategy, self.redirect_uri) try: user_profile = backend.do_auth(*args, **kwargs) except AuthFailed: logging.info("User is not member of GitHub organization.") user_profile = None return user_profile
def test_save_profile(self): backend = GithubOAuth2() response = Response() save_profile(backend, self.user, response, True) with self.assertRaises( get_user_model().userprofile.RelatedObjectDoesNotExist): self.user.userprofile save_profile(backend, self.user, response, False) with self.assertRaises( get_user_model().userprofile.RelatedObjectDoesNotExist): self.user.userprofile response['name'] = 'Tiago Costa' response['login'] = '******' response[ 'avatar_url'] = 'https://avatars1.githubusercontent.com/u/3596239?s=460&v=4' response['html_url'] = 'https://github.com/tcostam' save_profile(backend, self.user, response, False) with self.assertRaises( get_user_model().userprofile.RelatedObjectDoesNotExist): self.user.userprofile save_profile(backend, self.user, response, True) self.assertIsNotNone(self.user.userprofile)
def test_form_check_agreement(self): """social register checks agreement""" form_data = {"email": "*****@*****.**", "username": "******"} request = create_request(data=form_data) strategy = load_strategy(request=request) backend = GithubOAuth2(strategy, "/") agreement = Agreement.objects.create(type=Agreement.TYPE_TOS, text="Lorem ipsum", is_active=True) response = create_user_with_form( strategy=strategy, details={"email": form_data["email"]}, backend=backend, user=None, pipeline_index=1, ) self.assertEqual(response.status_code, 400) self.assertJsonResponseEquals( response, {"terms_of_service": ["This agreement is required."]}) # invalid agreement id form_data = { "email": "*****@*****.**", "username": "******", "terms_of_service": agreement.id + 1, } request = create_request(data=form_data) strategy = load_strategy(request=request) backend = GithubOAuth2(strategy, "/") response = create_user_with_form( strategy=strategy, details={"email": form_data["email"]}, backend=backend, user=None, pipeline_index=1, ) self.assertEqual(response.status_code, 400) self.assertJsonResponseEquals( response, {"terms_of_service": ["This agreement is required."]}) # valid agreement id form_data = { "email": "*****@*****.**", "username": "******", "terms_of_service": agreement.id, } request = create_request(data=form_data) strategy = load_strategy(request=request) backend = GithubOAuth2(strategy, "/") result = create_user_with_form( strategy=strategy, details={"email": form_data["email"]}, backend=backend, user=None, pipeline_index=1, ) new_user = User.objects.get(email="*****@*****.**") self.assertEqual(result, {"user": new_user, "is_new": True}) self.assertEqual(new_user.agreements, [agreement.id]) self.assertEqual(new_user.useragreement_set.count(), 1)
def test_form_check_agreement(self): """social register checks agreement""" form_data = { 'email': '*****@*****.**', 'username': '******', } request = create_request(data=form_data) strategy = load_strategy(request=request) backend = GithubOAuth2(strategy, '/') agreement = Agreement.objects.create( type=Agreement.TYPE_TOS, text="Lorem ipsum", is_active=True, ) response = create_user_with_form( strategy=strategy, details={'email': form_data['email']}, backend=backend, user=None, pipeline_index=1, ) self.assertEqual(response.status_code, 400) self.assertJsonResponseEquals(response, { 'terms_of_service': ['This agreement is required.'], }) # invalid agreement id form_data = { 'email': '*****@*****.**', 'username': '******', 'terms_of_service': agreement.id + 1, } request = create_request(data=form_data) strategy = load_strategy(request=request) backend = GithubOAuth2(strategy, '/') response = create_user_with_form( strategy=strategy, details={'email': form_data['email']}, backend=backend, user=None, pipeline_index=1, ) self.assertEqual(response.status_code, 400) self.assertJsonResponseEquals(response, { 'terms_of_service': ['This agreement is required.'], }) # valid agreement id form_data = { 'email': '*****@*****.**', 'username': '******', 'terms_of_service': agreement.id, } request = create_request(data=form_data) strategy = load_strategy(request=request) backend = GithubOAuth2(strategy, '/') result = create_user_with_form( strategy=strategy, details={'email': form_data['email']}, backend=backend, user=None, pipeline_index=1, ) new_user = UserModel.objects.get(email='*****@*****.**') self.assertEqual(result, {'user': new_user, 'is_new': True}) self.assertEqual(new_user.agreements, [agreement.id]) self.assertEqual(new_user.useragreement_set.count(), 1)
def main(): # strategy = load_strategy(request=request) # backend = load_backend() backend = GithubOAuth2() backend._user_data(token) user = backend.do_auth(access_token=token)
def test_skip_if_user_is_set(self): """pipeline step is skipped if user was passed""" result = create_user(MockStrategy(), {}, GithubOAuth2(), user=self.user) self.assertIsNone(result)