def post(self, request, *args, **kwargs): user = request.user resort = get_resort_for_user(user) operation = request.GET.get('operation', 'generate') # Only manager has the permission to access the resource if resort is not None: role = get_roleid_user(resort=resort, user=user) if role != 3: return Response( {_('detail'): _('you do not have permission to resource')}, status=400) else: return Response({_('detail'): _('no resort associated with user')}, status=400) if operation == 'generate': # If oauth app already exists then return existing credential try: app = ResortOauthApp.objects.get(resort=resort, is_active=True) app = app.oauth_app except: app = Application( user=user, authorization_grant_type='client-credentials', client_type='confidential', name=resort.resort_name) app.save() resort_oauth = ResortOauthApp(resort=resort, oauth_app=app) resort_oauth.save() elif operation == 'regenerate': try: app = ResortOauthApp.objects.get(resort=resort, is_active=True) oauth_app = app.oauth_app oauth_app.delete() except: pass app = Application(user=user, authorization_grant_type='client-credentials', client_type='confidential', name=resort.resort_name) app.save() resort_oauth = ResortOauthApp(resort=resort, oauth_app=app) resort_oauth.save() return Response( { 'client_id': app.client_id, 'client_secret': app.client_secret }, status=200)
def handle(self, *args, **options): if Application.objects.count() == 0: print("Initializing JupyterHub OAuth parameters") id_path = os.environ.get('OAUTH_CLIENT_ID_PATH') secret_path = os.environ.get('OAUTH_CLIENT_SECRET_PATH') app_name = 'jupyterhub' skip_auth = True redirect = os.environ['OAUTH_CALLBACK_URL'] client_type = Application.CLIENT_CONFIDENTIAL grant_type = Application.GRANT_AUTHORIZATION_CODE if id_path and secret_path and os.path.exists( id_path) and os.path.exists(secret_path): print( "Couldn't find existing ID and SECRET, generating new ones" ) client_id = open(id_path).read().strip() client_secret = open(secret_path).read().strip() jup = Application( name=app_name, redirect_uris=redirect, client_type=client_type, authorization_grant_type=grant_type, skip_authorization=skip_auth, client_id=client_id, client_secret=client_secret, ) jup.save() elif id_path and secret_path: print( "Couldn't find existing ID and SECRET, generating new ones" ) jup = Application( name=app_name, redirect_uris=redirect, client_type=client_type, authorization_grant_type=grant_type, skip_authorization=skip_auth, ) jup.save() open(id_path, 'w').write(jup.client_id) open(secret_path, 'w').write(jup.client_secret) else: print( "Provide both OAUTH_CLIENT_ID_PATH and OAUTH_CLIENT_SECRET_PATH in order to auto-generate these values" ) else: print( 'JupyterHub application is only created if no existing application exists' )
def setUp(self): self.client = APIClient() self.user = User.objects.create_user("Foo", "Bar", "*****@*****.**", "123456") self.user.is_active = True self.user.save() self.dev_user = User.objects.create_user("Foo", "Bar1", "*****@*****.**", "123456") self.dev_user.is_active = True self.dev_user.save() self.application = Application( name="Test Application", user=self.dev_user, client_type=Application.CLIENT_PUBLIC, authorization_grant_type=Application.GRANT_PASSWORD, ) self.application.save() token_request_data = { 'grant_type': 'password', 'username': '******', 'password': '******' } auth_headers = self.get_basic_auth_header(self.application.client_id, self.application.client_secret) response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data, **auth_headers) content = json.loads(response.content.decode("utf-8")) self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + content['access_token'])
def setUp(self): self.test_user = Client.objects.create_user('test', 'user', '*****@*****.**', 'testpassword') self.application = Application( name="Test Application", redirect_uris="http://localhost", user=self.test_user, client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE, ) self.application.save() self.test_account = Account(owner=self.test_user, name='test', domain='http://www.example.com') self.test_account.save() self.test_list = models.List(account=self.test_account, created_by=self.test_user, title="Foo List") self.test_list.save() self.create_url = reverse('lists:list_create', kwargs={'account': self.test_account.uaid}) self.retrieve_url = reverse('lists:retrieve_update_delete', kwargs={ 'ugid': self.test_list.ugid, 'account': self.test_account.uaid, })
def save(self, commit=True): app = Application(**self.cleaned_data) app.authorization_grant_type = Application.GRANT_CLIENT_CREDENTIALS app.user = self.user app.client_type = Application.CLIENT_CONFIDENTIAL app.save(commit) return app
def setUp(self): super(ProductCategoryTestCase, self).setUp() self.test_user = User.objects.create_user('user1', '*****@*****.**', 'qwer1234') self.application = Application( name="Test Application", user=self.test_user, client_type=Application.CLIENT_PUBLIC, authorization_grant_type=Application.GRANT_PASSWORD, ) self.application.save() self.app = Application.objects.get(name="Test Application") self.tok = AccessToken.objects.create(user=self.test_user, token='1234567890', application=self.application, scope='read write', expires=datetime.now() + timedelta(days=1)) self.test_user_category = UserCategory(title="shift head", ) self.test_user_category.save() self.test_user_system = UserSystem( user=self.test_user, user_categories=self.test_user_category, name='user1_name', ) self.test_user_system.save()
def setUp(self): super(PollAPITestCaseOAuthToolkit, self).setUp() # Prepare OAuth Toolkit Access from oauth2_provider.models import AccessToken, Application ot_application = Application( user=self.user, redirect_uris='http://example.com', client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE, name='Test Application') ot_application.save() for scope in self.scopes + (None, ): options = { 'user': self.user, 'application': ot_application, 'expires': datetime.datetime.now() + datetime.timedelta(days=10), 'token': self.token } if scope: scope_attrbute_name = "token_" + scope.replace(" ", "_") options.update({ 'scope': scope, 'token': getattr(self, scope_attrbute_name) }) ot_access_token = AccessToken(**options) ot_access_token.save() self.choice_url = self.urls['choice_toolkit'] self.poll_url = self.urls['poll_toolkit'] self.scoped_choice_url = self.urls['scoped_choice_toolkit'] self.scoped_poll_url = self.urls['scoped_poll_toolkit']
def register_application(request): if request.method == 'POST': app_name = request.POST['app_name'] redirect_url = request.POST['redirect_url'] app = None if Application.objects.filter(name=app_name).exists(): app = Application.objects.filter(name=app_name)[0] app.redirect_uris = app.redirect_uris + " " + redirect_url else: admin_user = User.objects.all()[0] app = Application( name=app_name, user=admin_user, redirect_uris=redirect_url, client_type="public", authorization_grant_type="Authorization code", ) app.save() return JsonResponse( { 'clientId': app.client_id, 'clientSecret': app.client_secret }, status=201) else: return HttpResponse(status=200)
def setUp(self): # Set up activities for study_id in settings.DEFAULT_STUDY_IDS: models.Activity.objects.create(study_task_identifier=study_id) self.test_user = UserModel.objects.create_user("bar_user", "*****@*****.**") self.application = Application( name="Test Application", redirect_uris="http://localhost http://example.com http://example.org", user=self.test_user, client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE, ) self.application.save() self.valid_token = AccessToken.objects.create( user=self.test_user, token="12345678901", application=self.application, expires=timezone.now() + datetime.timedelta(days=1), scope="read write" ) oauth2_settings._SCOPES = ["read", "write", "introspection", "dolphin"] oauth2_settings.READ_SCOPE = "read" oauth2_settings.WRITE_SCOPE = "write"
def get_or_create_app(name, redirect_uri, user, client_id=None, client_secret=None): """ Get or creates an OAuth2 application. """ try: application = Application.objects.get(name=name) except Application.DoesNotExist: application = Application() application.user = user if client_id and client_secret: application.client_id = client_id application.client_secret = client_secret application.name = name application.authorization_grant_type = Application.GRANT_AUTHORIZATION_CODE application.client_type = Application.CLIENT_CONFIDENTIAL application.redirect_uris = redirect_uri application.save() return application
def setUp(self): # add test data self.test_user = User.objects.create_user('test', 'test', '*****@*****.**') # Set Up a Test Application self.application = Application( name="Test Application", redirect_uris="http://localhost", user=self.test_user, client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE, ) self.application.save() self.tok = AccessToken.objects.create( user=self.test_user, token='1234567890', application=self.application, scope='read write', expires=datetime.datetime.now() + datetime.timedelta(days=1) ) self.create_restaurant("Restaurant 1", "Mikonkatu 1, Helsinki") self.create_restaurant("Restaurant 2", "Mikonkatu 5, Helsinki") self.create_restaurant("Restaurant 3", "Mikonkatu 10, Helsinki") self.create_restaurant("Restaurant 4", "Mikonkatu 15, Helsinki")
def register_application(request): if request.method == 'POST': app_name = request.POST['app_name'] redirect_url = request.POST['redirect_url'] app = None if Application.objects.filter(name=app_name).exists(): app = Application.objects.filter(name=app_name)[0] app.redirect_uris = app.redirect_uris + " " + redirect_url else: admin_user = User.objects.all()[0] app = Application( name=app_name, user=admin_user, redirect_uris=redirect_url, client_type=Application.CLIENT_PUBLIC, authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE, skip_authorization=True) app.save() return JsonResponse( { 'clientId': app.client_id, 'clientSecret': app.client_secret }, status=201) else: return HttpResponse(status=200)
def setUp(self): super(PollAPITestCaseOAuthToolkit, self).setUp() call_command('loaddata', 'polls_api_testdata.json', verbosity=0) self.client = Client() self.poll_1 = Poll.objects.get(pk=1) self.poll_2 = Poll.objects.get(pk=2) self.urls = {} kwargs = {'api_name': 'v1'} apis = [ 'choice_toolkit', 'scoped_choice_toolkit', 'poll_toolkit', 'scoped_poll_toolkit', ] for api in apis: kwargs['resource_name'] = api self.urls[api] = reverse('api_dispatch_list', kwargs=kwargs) # Create a user. username = '******' email = '*****@*****.**' password = '******' self.user = User.objects.create_user(username, email, password) self.scopes = ("read", "write", "read write") for scope in self.scopes: scope_attrbute_name = "token_" + scope.replace(" ", "_") setattr(self, scope_attrbute_name, "TOKEN" + scope) self.token = 'TOKEN' self.scoped_token = self.token_read_write ot_application = Application( user=self.user, redirect_uris='http://example.com', client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE, name='Test Application' ) ot_application.save() for scope in self.scopes + (None,): options = { 'user': self.user, 'application': ot_application, 'expires': datetime.datetime.now() + datetime.timedelta(days=10), 'token': self.token } if scope: scope_attrbute_name = "token_" + scope.replace(" ", "_") options.update({ 'scope': scope, 'token': getattr(self, scope_attrbute_name) }) ot_access_token = AccessToken(**options) ot_access_token.save() self.choice_url = self.urls['choice_toolkit'] self.poll_url = self.urls['poll_toolkit'] self.scoped_choice_url = self.urls['scoped_choice_toolkit'] self.scoped_poll_url = self.urls['scoped_poll_toolkit']
def setUp(self): self.factory = APIRequestFactory() self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******') self.js_frontend = Application( name="vue.js frontend", client_type="public", authorization_grant_type="Resource owner password-based").save()
def create_jwt_app(self) -> Application: """Create a jwt application.""" app = Application() app.name = self.jwt_app_name app.client_type = Application.CLIENT_CONFIDENTIAL app.authorization_grant_type = Application.GRANT_PASSWORD app.save() return app
def createApplication(self, user, name, id, secret): application = Application() application.user = user application.client_type = 'confidential' application.authorization_grant_type = 'password' application.name = name application.client_id = id application.client_secret = secret application.save()
def handle(self, *args, **options): new_application = Application( user=User.objects.filter(is_superuser=True)[0], client_type="confidential", authorization_grant_type="password", name=options["name"] or "socialauth_application", client_id=options["client_id"] or generate_client_id(), client_secret=options["client_secret"] or generate_client_secret(), ) new_application.save()
def setUp(self) -> None: self.user = User.objects.create( username="******", password="******", is_superuser=True ) self.user1 = User.objects.create( username="******", password="******", is_superuser=True ) self.stock1 = Stock.objects.create( name="stock1", description="This is a test stock", launch_date=datetime.now(), ) self.stock2 = Stock.objects.create( name="stock2", description="This is another test stock", launch_date=datetime.now(), ) self.stock1.update_price(13.12) self.stock1.update_price(13.13) self.stock1.add_director("Director1") self.stock1.add_director("Director2") self.stock2.update_price(43.21) self.stock2.update_price(43.22) self.stock2.add_director("Director3") self.stock2.add_director("Director4") self.app = Application( name="Test App", user=self.user, client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE, ) self.app.save() self.token = AccessToken.objects.create( user=self.user, token="123456789", application=self.app, scope="read write", expires=timezone.now() + timedelta(days=1), ) self.token1 = AccessToken.objects.create( user=self.user1, token="12345678911", application=self.app, scope="read", expires=timezone.now() + timedelta(days=1), ) self.auth_write = "Bearer {}".format(self.token.token) self.auth_read = "Bearer {}".format(self.token1.token)
def setUp(self): self.test_user = User.objects.create_user("*****@*****.**", "*****@*****.**", "hunter23") self.staff_user = User.objects.create_user("*****@*****.**", "*****@*****.**", "hunter23", is_staff=True) self.application = Application( name = "Django Test", user= self.test_user, client_type = Application.CLIENT_PUBLIC, authorization_grant_type = Application.GRANT_PASSWORD, ) self.application.save()
def create_application(self): app = Application.objects.filter(name="Myinstitute").first() if not app: app = Application( client_type=Application.CLIENT_PUBLIC, name="Myinstitute", user=self.superadmin, authorization_grant_type=Application.GRANT_PASSWORD, client_id=settings.CLIENT_ID, client_secret=settings.CLIENT_SECRET) # noqa app.save() return app
def create_app(): try: result = Application.objects.get(client_id=settings.TEST_CLIENT_ID) except Application.DoesNotExist: result = Application(client_id=settings.TEST_CLIENT_ID, ) result.name = settings.TEST_CLIENT_NAME result.client_secret = settings.TEST_CLIENT_SECRET result.redirect_uris = settings.TEST_REDIRECT_URIS result.client_type = Application.CLIENT_CONFIDENTIAL result.authorization_grant_type = Application.GRANT_AUTHORIZATION_CODE result.save() return result
def setUp(self): self.user = UserFactory() self.password = "******" self.user.set_password(self.password) self.user.save() self.app = Application( authorization_grant_type=Application.GRANT_PASSWORD, client_type=Application.CLIENT_CONFIDENTIAL, ) self.app.save() credentials = base64.b64encode('{}:{}'.format(self.app.client_id, self.app.client_secret).encode()).decode() self.client.defaults['HTTP_AUTHORIZATION'] = 'Basic ' + credentials
def setUp(self): application = Application( name="Test Application", redirect_uris="http://localhost", client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_CLIENT_CREDENTIALS, ) application.save() self.access_token = AccessToken.objects.create( token='1234567890', application=application, scope='read write', expires=timezone.now() + datetime.timedelta(days=1) )
def setUp(self): self.client = APIClient() self.test_user = User.objects.create_user("Edwin", "J", "*****@*****.**", "123456") self.application = Application( name="Test Application Client Credentials", redirect_uris="http://127.0.0.1:8000/api/", user=self.test_user, client_type=Application.CLIENT_PUBLIC, authorization_grant_type=Application.GRANT_CLIENT_CREDENTIALS, ) self.application.save()
def create_user_settings(sender, instance=None, created=False, **kwargs): """ For created user, creating Application instance for oauth2 model, use 'client_type = public' for authorization with client_id without client_secret, and 'grant_type = password' for password authenticate. Value for variable from oauth source code. """ if created: app = Application() app.user = instance app.name = 'default' app.authorization_grant_type = 'password' app.client_type = 'public' app.save()
def create_oath2_application(self, user_id): application = Application( name="library_management", client_id="c8fO42qEIvtn2NkHyBAmOwOHnQCYaAlkUTAZHBZW", client_secret= "SbkpN6VebOsjMKDaGYuEnquKwQwohi1UGdNmGdofUQbXI88cLuv6qqrCroDRYMuDKY8IJlQgOQQdctn6YRrOfcdbclfxeVTrkXfCw0AUPKliF35FNbGdfQ03IYHxSYQ3", client_type="confidential", authorization_grant_type="password", user_id=user_id) application.save() return application
def create_google_application(apps, schema_editor): # Application = apps.get_model('oauth2_provider', 'Application') from oauth2_provider.models import Application application = Application( client_id='4O9vihRrTRAlwcSOJjLxgZgtvWq5ZT4UQzc3NXYx', client_secret= 'QG9uGNUQy6lvGhSYRwkPFban14UMi3juWVw8Y5aV9pOaDdRXIWW4Q7TbuQdvcrnTgbqOn6PPgYKapbr8gIAoCOFoBWimmWjJvHhQI2y2TQBh7DoI1bZfxTVyxH3pM2Iv', name='google', redirect_uris= 'https://oauth-redirect.googleusercontent.com/r/budgie-bf791', client_type='public', authorization_grant_type='authorization-code', ) application.save()
def setUp(self): self.user = User.objects.create_user(first_name="test_name", last_name="test_last_name", password='******', phone_number='+911234567890', username="******") self.application = Application( name="Test Application", redirect_uris="http://localhost http://example.com", user=self.user, client_type="public", authorization_grant_type="password", ) self.application.save()
def setUp(self): user = MyUser.objects.create(username=self.username) self.client = APIClient() self.client.force_authenticate(user=user) self.user = user self.user.set_password(self.password) self.user.save() self.cl = APIClient() app= Application() app.client_id=self.client_id app.user=self.user app.authorization_grant_type="password" app.client_type="public" app.client_secret=self.client_secret app.save()
def save(self, *args, **kwargs): if hasattr(self, "application"): application = self.application else: application = Application() application.name = self.name application.user = self.coordinator.user application.client_type = Application.CLIENT_CONFIDENTIAL application.redirect_uris = self.redirect_url application.authorization_grant_type = Application.GRANT_AUTHORIZATION_CODE application.save() self.application = application super(OAuth2DataRequestProject, self).save(*args, **kwargs)