예제 #1
0
    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"
예제 #2
0
    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']
예제 #3
0
    def setUp(self):
        super(PollAPITestCase, self).setUp()
        self.poll_1 = Poll.objects.get(pk=1)
        self.poll_2 = Poll.objects.get(pk=2)
        self.urls = {}
        kwargs = {'api_name': 'v1'}
        for api in ['choice', 'poll']:
            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)

        # Prepare OAuth Toolkit Access
        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()
        self.ot_token = 'TOKEN'
        ot_access_token = AccessToken(
            user=self.user,
            application=ot_application,
            expires=datetime.datetime.now() + datetime.timedelta(days=10),
            scope='read',
            token=self.ot_token
        )
        ot_access_token.save()
예제 #4
0
파일: tests.py 프로젝트: rowegie/baseup-api
	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'])
예제 #5
0
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)
예제 #6
0
    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']
예제 #7
0
    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")
예제 #8
0
    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()
예제 #9
0
    def post(self, request):
        try:
            name = request.DATA['name']
            username = request.user.username
            if (OauthApp.objects.filter(name=name).exists()):
                e_msg = ('application with name: %s already exists.' % name)
                handle_exception(Exception(e_msg), request)

            try:
                user = User.objects.get(username=username)
            except:
                e_msg = ('User with name: %s does not exist' % username)
                handle_exception(Exception(e_msg), request)

            client_type = OauthApplication.CLIENT_CONFIDENTIAL
            auth_grant_type = OauthApplication.GRANT_CLIENT_CREDENTIALS
            app = OauthApplication(name=name, client_type=client_type,
                                   authorization_grant_type=auth_grant_type,
                                   user=user.user)
            app.save()
            oauth_app = OauthApp(name=name, application=app, user=user)
            oauth_app.save()
            return Response(OauthAppSerializer(oauth_app).data)

        except RockStorAPIException:
            raise
        except Exception, e:
            handle_exception(e, request)
예제 #10
0
    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,
                                    })
예제 #11
0
파일: tests.py 프로젝트: rowegie/baseup-api
class RoleEndpointTest(TestCase):
	def setUp(self):
		self.client = APIClient()

		self.user = User.objects.create_user("Foo", "Bar", "*****@*****.**", "123456")
		self.dev_user = User.objects.create_user("Foo", "Bar1", "*****@*****.**", "123456")

		self.application = Application(
                    name="Test Application",
                    user=self.dev_user,
                    client_type=Application.CLIENT_PUBLIC,
                    authorization_grant_type=Application.GRANT_PASSWORD,
                )
		self.application.save()

		self.token = AccessToken(
					token="ABC123",
					user=self.user,
					expires=datetime.datetime.now() + datetime.timedelta(days=1),
					scope='read write',
					application=self.application
				)
		self.token.save()

		self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + self.token.token)

	def tearDown(self):
		self.application.delete()
		self.token.delete()
		self.user.delete()
		self.dev_user.delete()
예제 #12
0
    def post(self, request):
        with self._handle_exception(request):
            name = request.data.get("name")
            username = request.user.username
            if OauthApp.objects.filter(name=name).exists():
                e_msg = ("Application with name ({}) already exists. Choose a "
                         "different name.").format(name)
                handle_exception(Exception(e_msg), request, status_code=400)

            try:
                user = User.objects.get(username=username)
            except:
                e_msg = "User with name ({}) does not exist.".format(username)
                handle_exception(Exception(e_msg), request)

            client_type = OauthApplication.CLIENT_CONFIDENTIAL
            auth_grant_type = OauthApplication.GRANT_CLIENT_CREDENTIALS
            app = OauthApplication(
                name=name,
                client_type=client_type,
                authorization_grant_type=auth_grant_type,
                user=user.user,
            )
            app.save()
            oauth_app = OauthApp(name=name, application=app, user=user)
            oauth_app.save()
            return Response(OauthAppSerializer(oauth_app).data)
예제 #13
0
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)
예제 #14
0
    def post(self, request):
        try:
            name = request.DATA['name']
            username = request.user.username
            if (OauthApp.objects.filter(name=name).exists()):
                e_msg = ('application with name: %s already exists.' % name)
                handle_exception(Exception(e_msg), request)

            try:
                user = User.objects.get(username=username)
            except:
                e_msg = ('User with name: %s does not exist' % username)
                handle_exception(Exception(e_msg), request)

            client_type = OauthApplication.CLIENT_CONFIDENTIAL
            auth_grant_type = OauthApplication.GRANT_CLIENT_CREDENTIALS
            app = OauthApplication(name=name,
                                   client_type=client_type,
                                   authorization_grant_type=auth_grant_type,
                                   user=user.user)
            app.save()
            oauth_app = OauthApp(name=name, application=app, user=user)
            oauth_app.save()
            return Response(OauthAppSerializer(oauth_app).data)

        except RockStorAPIException:
            raise
        except Exception, e:
            handle_exception(e, request)
예제 #15
0
    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']
예제 #16
0
 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()
예제 #17
0
 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()
예제 #18
0
    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()
예제 #19
0
    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)
예제 #20
0
 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
예제 #21
0
 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
예제 #22
0
 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()
예제 #23
0
 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)
     )
예제 #24
0
파일: tests.py 프로젝트: rowegie/baseup-api
	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()
예제 #25
0
    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
예제 #26
0
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()
예제 #27
0
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()
예제 #28
0
    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()
예제 #29
0
 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
예제 #30
0
    def test_login(self):
        data = {
            'code': '209528202',
            'nip': 'holapito',
            'email': '*****@*****.**',
            'phone_number': '3311995533',
            'password': '******'
        }
        auth = self._create_authorization_header()

        response = self.client.post('/api/profile/udg_signup/', data, format='json', HTTP_AUTHORIZATION=auth)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        first_response = response.data
        profile = Profile.objects.get(code='209528202')
        self.assertEqual(profile.type, 'A')
        user = User.objects.get(pk=response.data['id'])

        data = {
            'code': '208528202',
            'nip': 'pablito',
            'email': '*****@*****.**',
            'phone_number': '3311995533',
            'password': '******'
        }
        response = self.client.post('/api/profile/udg_signup/', data, format='json', HTTP_AUTHORIZATION=auth)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        #
        #  Login created user
        #
        application = Application(
            name="Test Application",
            redirect_uris="http://localhost",
            user=user,
            client_type=Application.CLIENT_CONFIDENTIAL,
            authorization_grant_type=Application.GRANT_PASSWORD,
        )
        application.save()
        self.access_token = AccessToken.objects.create(
            user=user, token='1234567891',
            application=application, scope='read write',
            expires=timezone.now() + datetime.timedelta(days=1)
        )
        auth = self._create_authorization_header()
        response = self.client.get('/api/profile/', HTTP_AUTHORIZATION=auth)
        self.assertEqual(first_response, response.data)
예제 #31
0
def setup_user_token():
    # create user
    user = User.objects.create_user('hongzhi', password='******')

    # create oauth application
    app = Application()
    app.user = user
    app.save()

    token = AccessToken()
    token.user = user
    token.expires = timezone.now().replace(year=timezone.now().year + 1)
    token.application = app
    token.token = '987654321'
    token.save()

    return user, token.token
예제 #32
0
 def setUp(self):
     self.client = APIClient()
     self.test_user = User.objects.create_user(
         first_name='test',
         last_name='user',
         username='******',
         email='*****@*****.**',
         password='******',
     )
     self.application = Application(
         name="Test Application",
         redirect_uris="http://localhost:8000",
         user=self.test_user,
         client_type=Application.CLIENT_CONFIDENTIAL,
         authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
     )
     self.application.save()
예제 #33
0
def setup_user_token():
    # create user
    user = User.objects.create_user('hongzhi', password='******')

    # create oauth application
    app = Application()
    app.user = user
    app.save()

    token = AccessToken()
    token.user = user
    token.expires = timezone.now().replace(year=timezone.now().year + 1)
    token.application = app
    token.token = '987654321'
    token.save()

    return user, token.token
def add_auth(entity, user, form):
    if "client_id" in form.cleaned_data:
        if "client_secret" in form.cleaned_data:
            if "token_end_point" in form.cleaned_data:
                id = form.cleaned_data['client_id']
                secret = form.cleaned_data['client_secret']
                end_point = form.cleaned_data['token_end_point']
                
                client = OAuthRemoteClient()
                client.client_id = id
                client.client_secret = secret
                client.token_endpoint = end_point
                client.entity = entity
                client.save()
    
    application = Application()
    application.user = user
    application.client_type = 'confidential'
    application.authorization_grant_type = 'client-credentials'
    application.name = entity.name
    application.save()
    
    entityOA = EntityOAuth()
    entityOA.entity = entity
    entityOA.application = application
    entityOA.save()
예제 #35
0
 def setUp(self):
     self.username = "******"
     self.password = "******"
     self.tearDown()
     self.credentials = {
         'username': self.username,
         'password': self.password
     }
     u = User.objects.create_user(**self.credentials)
     u.is_staff = True
     u.save()
     app = Application(client_type='confidential',
                       authorization_grant_type='password',
                       name='Owner',
                       user=u)
     app.save()
     self.user = u
     self.emptyCode = ''
     self.invalidCode = 'code123'
     self.fullname = "BSD Zero Clause License"
     self.shortIdentifier = "0BSD"
     self.sourceUrl = "http://landley.net/toybox/license.html"
     self.urls = [self.sourceUrl]
     self.incorrectOsiApproved = "no"  # "no" is not a valid choice for osi
     self.osiApproved = "Rejected"
     self.comments = ""
     self.notes = ""
     self.licenseHeader = ""
     self.text = '<text> <copyrightText> <p>Copyright (C) 2006 by Rob Landley &lt;[email protected]&gt;</p> </copyrightText> <p>Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted.</p> <p>THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.</p> </text>'
     self.userEmail = "*****@*****.**"
     self.licenseAuthorName = ""
     self.listVersionAdded = ""
     self.xml = '<SPDXLicenseCollection xmlns="http://www.spdx.org/license"> <license isOsiApproved="false" licenseId="0BSD" listVersionAdded="" name="BSD Zero Clause License"> <crossRefs> <crossRef> http://landley.net/toybox/license.html</crossRef> </crossRefs> <standardLicenseHeader /> <notes /> <text> <p> &lt;text&gt; &lt;copyrightText&gt; &lt;p&gt;Copyright (C) 2006 by Rob Landley &amp;lt;[email protected]&amp;gt;&lt;/p&gt; &lt;/copyrightText&gt; &lt;p&gt;Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted.&lt;/p&gt; &lt;p&gt;THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.&lt;/p&gt; &lt;/text&gt;</p> </text> </license> </SPDXLicenseCollection> '
     self.data = {
         "fullname": self.fullname,
         "shortIdentifier": self.shortIdentifier,
         "sourceUrl": self.sourceUrl,
         'osiApproved': self.osiApproved,
         'notes': self.notes,
         "licenseHeader": self.licenseHeader,
         "text": self.text,
         "userEmail": self.userEmail,
         "licenseAuthorName": self.licenseAuthorName,
         "urlType": "tests"
     }
예제 #36
0
 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
예제 #37
0
    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)
예제 #38
0
    def post(self, request):
        setup = Setup.objects.all()[0]
        setup.setup_user = True
        setup.save()

        # Create user
        res = super(SetupUserView, self).post(request)
        # Create cliapp id and secret for oauth
        name = "cliapp"
        user = User.objects.get(username=request.DATA["username"])
        client_type = OauthApplication.CLIENT_CONFIDENTIAL
        auth_grant_type = OauthApplication.GRANT_CLIENT_CREDENTIALS
        app = OauthApplication(
            name=name, client_type=client_type, authorization_grant_type=auth_grant_type, user=user.user
        )
        app.save()
        oauth_app = OauthApp(name=name, application=app, user=user)
        oauth_app.save()
        return res
예제 #39
0
 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
예제 #40
0
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
예제 #41
0
    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)
예제 #42
0
    def post(self, request):
        with self._handle_exception(request):
            name = request.data.get('name')
            username = request.user.username
            if (OauthApp.objects.filter(name=name).exists()):
                e_msg = ('Application with name ({}) already exists. Choose a '
                         'different name.').format(name)
                handle_exception(Exception(e_msg), request, status_code=400)

            try:
                user = User.objects.get(username=username)
            except:
                e_msg = 'User with name ({}) does not exist.'.format(username)
                handle_exception(Exception(e_msg), request)

            client_type = OauthApplication.CLIENT_CONFIDENTIAL
            auth_grant_type = OauthApplication.GRANT_CLIENT_CREDENTIALS
            app = OauthApplication(name=name, client_type=client_type,
                                   authorization_grant_type=auth_grant_type,
                                   user=user.user)
            app.save()
            oauth_app = OauthApp(name=name, application=app, user=user)
            oauth_app.save()
            return Response(OauthAppSerializer(oauth_app).data)
예제 #43
0
파일: views.py 프로젝트: Ell/goonauth
    def form_valid(self, form):
        if Application.objects.filter(name=form.cleaned_data["application_name"]).exists():
            messages.warning(self.request, "Application with this name already exists.")
        else:
            oapp = OAuthApplication()
            oapp.description = form.cleaned_data["description"]
            oapp.website = form.cleaned_data["website"]

            omodel = Application()
            omodel.user = self.request.user
            omodel.redirect_uris = form.cleaned_data["callback_url"]
            omodel.client_type = "confidential"
            omodel.authorization_grant_type = "authorization-code"
            omodel.name = form.cleaned_data["application_name"]
            omodel.save()

            oapp.client = omodel
            oapp.save()

            messages.success(self.request, "Application Created!")

        return super(OAuthClientCreateView, self).form_valid(form)