Beispiel #1
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
Beispiel #2
0
class MyGeneRankTestCase(TestCase):

    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 tearDown(self):
        oauth2_settings._SCOPES = ["read", "write"]
        AccessToken.objects.all().delete()
        Application.objects.all().delete()
        UserModel.objects.all().delete()
        models.Activity.objects.all().delete()
Beispiel #3
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
Beispiel #4
0
class BaseViewTest(APITestCase):

    @staticmethod
    def create_restaurant(name="", address=""):
        if name != "" and address != "":
            Restaurant.objects.create(name=name, address=address)

    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")
Beispiel #5
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)
    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']
Beispiel #7
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)
Beispiel #8
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)
Beispiel #9
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
Beispiel #10
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)
Beispiel #11
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)
    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']
Beispiel #13
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()
Beispiel #14
0
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()
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()
Beispiel #16
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']
Beispiel #17
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()
Beispiel #18
0
    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 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)
Beispiel #22
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
Beispiel #23
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
Beispiel #24
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)
     )
Beispiel #25
0
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()
Beispiel #26
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
Beispiel #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()
Beispiel #28
0
 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 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()
Beispiel #30
0
 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()
Beispiel #31
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)
Beispiel #32
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 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)
Beispiel #34
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
Beispiel #35
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)
Beispiel #36
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"
     }
Beispiel #37
0
class RedirectToAuthorizationViewTestCase(TestCase):

    def setUp(self):
        self.test_user = User.objects.create_user('test_user', '*****@*****.**', 'test')

        # Set up OAuth for the user.
        self.application = Application(
            name='Test Application',
            redirect_uris='http://localhost/',
            user=self.test_user,
            skip_authorization=True,
            authorization_grant_type=Application.GRANT_IMPLICIT,
            client_secret='',
            client_type=Application.CLIENT_PUBLIC,
        )
        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),
        )

    def test_authorize_no_redirect_with_valid_request(self):
        self.client.login(username='******', password='******')
        r = self.client.get('/o/authorize/', {
            'client_id': self.application.client_id,
            'response_type': 'token',
        })

        self.assertEqual(r.status_code, 302)
        self.assertNotRegex(r.url, r'http://localhost/\?next=%2F.*')

    def test_authorize_redirect_with_valid_request(self):
        self.client.login(username='******', password='******')
        r = self.client.get('/o/authorize/', {
            'next': '/',
            'client_id': self.application.client_id,
            'response_type': 'token',
        })

        self.assertEqual(r.status_code, 302)
        self.assertRegex(r.url, r'http://localhost/\?next=%2F.*')
Beispiel #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
Beispiel #39
0
    def post(self, request, *args, **kwargs):

        new_app = Application(
            name=request.POST['client_name'],
            redirect_uris=request.POST['redirect_uris'],
            client_type='confidential',  # ?
            authorization_grant_type='password',
            user=None,  # don't need to be logged in
        )

        new_app.save()

        result = {
            'id': new_app.id,
            'client_id': new_app.client_id,
            'client_secret': new_app.client_secret,
        }

        return JsonResponse(result)
Beispiel #40
0
 def setUp(self):
     self.user = User.objects.create(username='******')
     self.user.set_password('1234')
     self.user.save()
     self.profile = Profile.objects.create(name='Pedro', phone_number='3311995533', email='*****@*****.**',
                                           code='209528202', type='A', university='CUCEI', user=self.user)
     self.car = Car.objects.create(owner=self.profile, model='Sentra 2014', color='Rojo Oscuro', license_plate='ALD-F2SA-2')
     application = Application(
         name="Test Application",
         redirect_uris="http://localhost",
         user=self.user,
         client_type=Application.CLIENT_CONFIDENTIAL,
         authorization_grant_type=Application.GRANT_PASSWORD,
     )
     application.save()
     self.access_token = AccessToken.objects.create(
         user=self.user, token='1234567890',
         application=application, scope='read write',
         expires=timezone.now() + datetime.timedelta(days=1)
     )
Beispiel #41
0
    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)
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
Beispiel #43
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)