Beispiel #1
0
 def setUp(self):
     super().setUp()
     # We add a SocialApp as we get an error if it's not done
     app = SocialApp(pk=1, provider="facebook", name="Facebook", client_id="001122334455667",
                     secret="00112233445566778899aabbccddeeff")
     app.sites.add(Site.objects.get_current().id)
     app.save()
Beispiel #2
0
 def test_get_redir_user_demo(self):
     payload = {"user": {"username": self.demo["username"]}}
     self.client.login(username=payload["user"]["username"],
                       password="******")
     sapp = SocialApp(provider='github',
                      name='Github',
                      client_id='<test>',
                      secret='<test>')
     sapp.save()
     sacc = SocialAccount(uid=1001, user=self.test_user, provider="github")
     sacc.save()
     stoken = SocialToken(app=sapp, account=sacc, token="test_token")
     stoken.save()
     response = self.client.post('/accounts/profile', follow=True)
     first_url, first_response = response.redirect_chain[0]
     self.assertEqual(
         first_url,
         "/login?status=passed&token=test_token&username=testname&user_id=1001"
     )
     self.client.login(username=payload["user"]["username"],
                       password="******")
     stoken = SocialToken(app=sapp, account=sacc, token="test_token")
     stoken.save()
     response = self.client.post('/accounts/profile', follow=True)
     first_url, first_response = response.redirect_chain[0]
     self.assertEqual(
         first_url,
         "/login?status=passed&token=test_token&username=testname&user_id=1001"
     )
Beispiel #3
0
    def handle(self, *args, **options):
        # Check if FXA_* settings are configured, bail if not.
        if settings.FXA_CLIENT_ID is None or settings.FXA_SECRET_KEY is None:
            self.stdout.write("FXA_* settings unavailable; "
                              "skipping provider config.")
            return

        # Grab the credentials from settings
        data = dict(
            name='FxA',
            provider=FXA_PROVIDER_ID,
            client_id=settings.FXA_CLIENT_ID,
            secret=settings.FXA_SECRET_KEY
        )

        try:
            # Update the existing provider with current settings.
            app = SocialApp.objects.get(provider=FXA_PROVIDER_ID)
            self.stdout.write("Updating existing Firefox Accounts provider "
                              "(pk=%s)" % app.pk)
            for k, v in data.items():
                setattr(app, k, v)
            app.save()
        except ObjectDoesNotExist:
            # Create the provider if necessary.
            app = SocialApp(**data)
            app.save()
            self.stdout.write("Created new Firefox Accounts provider (pk=%s)" %
                              app.pk)

        # Ensure the provider applies to the current default site.
        sites_count = app.sites.count()
        if sites_count == 0:
            default_site = Site.objects.get(pk=settings.SITE_ID)
            app.sites.add(default_site)
Beispiel #4
0
    def handle(self, *args, **options):
        provider = options['provider']
        name = options.get('name') or provider.title()
        client_id = options['client_id']
        client_secret = options['client_secret']

        # Delete the specific provider if it exists.
        # Note that QuerySet.update_or_create is an alternative.
        SocialApp.objects.filter(provider=provider).delete()
        a = SocialApp(provider=provider,
                      name=name,
                      secret=client_secret,
                      client_id=client_id,
                      key='')
        a.save()

        # Now associate this provider with all site instances.
        site = Site.objects.get(pk=SITE_ID)
        site.domain = 'pk-db.com'
        site.name = 'pk-db.com'
        site.save()
        a.sites.add(site)

        self.stdout.write(
            self.style.SUCCESS("Provider '{}' -> client ID '{}'".format(
                a.name, a.client_id)))
        self.stdout.write(
            self.style.SUCCESS("Associated with site: {}".format(site)))
def init_social_providers():
    # Initialize social login providers.

    for name, data in settings.SOCIALACCOUNT_PROVIDERS.items():

        try:
            client_id = data.get('PROVIDER_KEY','')
            secret = data.get('PROVIDER_SECRET_KEY','')
            site = Site.objects.get(id=settings.SITE_ID)

            # Check that the provider is registered
            provider = providers.registry.by_id(name)

            # Code duplication since many2many fields cannot be initialized in one step
            exists = SocialApp.objects.filter(
                name=name, client_id=client_id, provider=name,
                secret=secret, sites=site
            )
            if not exists:
                app = SocialApp(
                    name=name,
                    client_id=client_id,
                    provider=name,
                    secret=secret, key='',
                )
                app.save()
                app.sites.add(site)
                app.save()
                logger.info("initializing social provider %s" % name)

        except Exception, exc:
            raise ImproperlyConfigured("error setting provider %s, %s" % (name, exc))
Beispiel #6
0
class InvitationTestCaseAllauth(InvitationTestCase):
    def setUp(self):
        super(InvitationTestCaseAllauth, self).setUp()
        #         self.saved_invitation_use_allauth = settings.INVITATION_USE_ALLAUTH
        #         settings.INVITATION_USE_ALLAUTH = True
        self.saved_invite_mode = getattr(settings, 'INVITE_MODE', None)
        settings.INVITE_MODE = True
        social_accounts = getattr(settings, 'SOCIALACCOUNT_PROVIDERS', None)
        self.saved_socialaccounts = social_accounts
        settings.SOCIALACCOUNT_PROVIDERS = {}

        self.facebook_app = SocialApp(provider='facebook',
                                      name='test',
                                      key='abc',
                                      secret='def')
        self.facebook_app.save()
        self.facebook_app.sites.add(Site.objects.get_current())

    def tearDown(self):
        super(InvitationTestCaseAllauth, self).tearDown()
        #         settings.INVITATION_USE_ALLAUTH = self.saved_invitation_use_allauth
        if self.saved_invite_mode is not None:
            settings.INVITE_MODE = self.saved_invite_mode
        if self.saved_socialaccounts is not None:
            settings.SOCIALACCOUNT_PROVIDERS = self.saved_socialaccounts
    def handle(self, *args, **options):
        # Check if FXA_* settings are configured, bail if not.
        if settings.FXA_CLIENT_ID is None or settings.FXA_SECRET_KEY is None:
            self.stdout.write("FXA_* settings unavailable; "
                              "skipping provider config.")
            return

        # Grab the credentials from settings
        data = dict(name='FxA',
                    provider=FXA_PROVIDER_ID,
                    client_id=settings.FXA_CLIENT_ID,
                    secret=settings.FXA_SECRET_KEY)

        try:
            # Update the existing provider with current settings.
            app = SocialApp.objects.get(provider=FXA_PROVIDER_ID)
            self.stdout.write("Updating existing Firefox Accounts provider "
                              "(pk=%s)" % app.pk)
            for k, v in data.items():
                setattr(app, k, v)
            app.save()
        except ObjectDoesNotExist:
            # Create the provider if necessary.
            app = SocialApp(**data)
            app.save()
            self.stdout.write("Created new Firefox Accounts provider (pk=%s)" %
                              app.pk)

        # Ensure the provider applies to the current default site.
        sites_count = app.sites.count()
        if sites_count == 0:
            default_site = Site.objects.get(pk=settings.SITE_ID)
            app.sites.add(default_site)
Beispiel #8
0
    def handle(self, *args, **options):
        try:
            redditalpha_site = Site.objects.filter(name__iexact='redditalpha').first()
            provider = None

            for id, name in providers.registry.as_choices():
                if name.lower() == 'discord':
                    provider = id

            assert redditalpha_site is not None, "YOU NEED TO HAVE A SITE WITH THE NAME OF 'redditalpha'"

            if SocialApp.objects.filter(name='Discord').exists():
                self.stdout.write(self.style.SUCCESS("SocialApp for Discord already exists"))
            else:
                discord_app = SocialApp(
                    provider=provider,
                    name='Discord',
                    client_id='217852556863340544',
                    secret='Ckn3CucHno36b5yAPLQDva2URzAJIhll',
                    key=''
                )

                discord_app.save()
                discord_app.sites.add(redditalpha_site)
                self.stdout.write(self.style.SUCCESS("Created SocialApp for Discord"))
            self.stdout.write(self.style.SUCCESS("Finished successfully"))
        except Exception as ex:
            self.stdout.write(self.style.ERROR("Could not create SocialApp for Discord"))
            self.stdout.write(self.style.ERROR(str(ex)))
Beispiel #9
0
    def setUp(self):
        super(InvitationTestCaseAllauth, self).setUp()
        self.saved_invitation_use_allauth = settings.INVITATION_USE_ALLAUTH
        settings.INVITATION_USE_ALLAUTH = True
        self.saved_socialaccount_providers = settings.SOCIALACCOUNT_PROVIDERS
        settings.SOCIALACCOUNT_PROVIDERS = {}   

        self.facebook_app = SocialApp(site=Site.objects.get_current(), provider='facebook', name='test', key='abc', secret='def')
        self.facebook_app.save()
Beispiel #10
0
    def handle(self, *args, **options):
        try:
            site = Site.objects.get(id=settings.SITE_ID)
        except Site.DoesNotExist:
            self.stderr.write('No primary domain configured. Please run: '
                              'python manage.py devilry_setup_primary_domain')
            raise SystemExit()

        client_id = options['client_id']
        secret = getpass('Please type your Dataporten OAuth Client Secret: ')
        if not secret:
            self.stderr.write('Secret is required')
            raise SystemExit()
        try:
            socialapp = SocialApp.objects.get(
                provider=DevilryDataportenProvider.id)
        except SocialApp.DoesNotExist:
            socialapp = SocialApp(provider=DevilryDataportenProvider.id)
        socialapp.name = 'Devilry Dataporten'
        socialapp.client_id = client_id
        socialapp.secret = secret
        socialapp.full_clean()
        socialapp.save()

        if not socialapp.sites.filter(id=settings.SITE_ID).exists():
            socialapp.sites.add(site)

        self.stdout.write('Dataporten provider successfully configured.')
    def handle(self, *args, **options):
        try:
            site = Site.objects.get(id=settings.SITE_ID)
        except Site.DoesNotExist:
            self.stderr.write('No primary domain configured. Please run: '
                              'python manage.py devilry_setup_primary_domain')
            raise SystemExit()

        client_id = options['client_id']
        secret = getpass('Please type your Dataporten OAuth Client Secret: ')
        if not secret:
            self.stderr.write('Secret is required')
            raise SystemExit()
        try:
            socialapp = SocialApp.objects.get(provider=DevilryDataportenProvider.id)
        except SocialApp.DoesNotExist:
            socialapp = SocialApp(provider=DevilryDataportenProvider.id)
        socialapp.name = 'Devilry Dataporten'
        socialapp.client_id = client_id
        socialapp.secret = secret
        socialapp.full_clean()
        socialapp.save()

        if not socialapp.sites.filter(id=settings.SITE_ID).exists():
            socialapp.sites.add(site)

        self.stdout.write('Dataporten provider successfully configured.')
Beispiel #12
0
    def create_social_app(self):
        sapp = SocialApp(provider="facebook",
                         name="Facebook",
                         client_id="379368956094614",
                         secret=FACEBOOK_SOCIAL_APP_SECRET)
        sapp.save()
        sapp.sites.add(1)

        # change site name to a custom name
        site = Site.objects.get(id=1)
        site.domain = "mus.icu"
        site.name = "Free For Food"
        site.save()

        print(f"Created social app and changed default site")
    def test_complete_login(self, mocker, rf):
        get = mocker.patch("requests.get")
        userinfo_mock = mock.MagicMock()
        userinfo_mock.json.return_value = {
            "organization_id": "00D000000000001EAA",
            "user_id": "003000000000001",
            "preferred_username": "******",
            "language": "en_US",
            "urls": mock.MagicMock(),
        }
        get.side_effect = [userinfo_mock, mock.MagicMock(), mock.MagicMock()]
        request = rf.post("/")
        request.session = {"socialaccount_state": (None, "some-verifier")}
        adapter = SalesforceOAuth2Adapter(request)
        adapter.get_provider = mock.MagicMock()
        slfr = mock.MagicMock()
        slfr.account.extra_data = {}
        prov_ret = mock.MagicMock()
        prov_ret.sociallogin_from_response.return_value = slfr
        adapter.get_provider.return_value = prov_ret
        token = mock.MagicMock(app=SocialApp(provider="salesforce"))
        token.token = fernet_encrypt("token")

        ret = adapter.complete_login(
            request,
            None,
            token,
            response={"instance_url": "https://example.com"})
        assert ret.account.extra_data["instance_url"] == "https://example.com"
Beispiel #14
0
def site_get_or_create(sender, **kwargs):
    from django.contrib.sites.models import Site
    from allauth.socialaccount.models import SocialApp

    try:
        site = Site.objects.get(id=settings.SITE_ID)
    except Site.DoesNotExist:
        site = Site()

    site.__dict__.update(dict(
        id=settings.SITE_ID,
        domain=settings.SITE_DOMAIN,
        name=settings.SITE_NAME
    ))
    site.save()

    try:
        social_app = SocialApp.objects.get(id=settings.SITE_ID)
    except SocialApp.DoesNotExist:
        social_app = SocialApp()

    social_app.__dict__.update(dict(
        id=settings.ALLAUTH_GOOGLE_SOCIALAPP_ID,
        name=settings.ALLAUTH_GOOGLE_SOCIALAPP_NAME,
        client_id=settings.ALLAUTH_GOOGLE_SOCIALAPP_CLIENT_ID,
        secret_key=settings.ALLAUTH_GOOGLE_SOCIALAPP_SECRET_KEY,
    ))
    site.save()
Beispiel #15
0
 def setUp(self):
     self.saved_socialaccount_providers = settings.SOCIALACCOUNT_PROVIDERS
     settings.SOCIALACCOUNT_PROVIDERS = {}   
     self.saved_invitation_use_allauth = settings.INVITATION_USE_ALLAUTH
     settings.INVITATION_USE_ALLAUTH = False
     
     self.sample_user = User.objects.create_user(username='******',
                                                 password='******',
                                                 email='*****@*****.**')
     self.sample_key = InvitationKey.objects.create_invitation(user=self.sample_user)
     self.expired_key = InvitationKey.objects.create_invitation(user=self.sample_user)
     self.expired_key.date_invited -= datetime.timedelta(days=settings.ACCOUNT_INVITATION_DAYS + 1)
     self.expired_key.save()
     
     self.sample_registration_data = {
         'invitation_key': self.sample_key.key,
         'username': '******',
         'email': '*****@*****.**',
         'password1': 'secret',
         'password2': 'secret',
         'tos': '1'}
     
     if allauth_installed:
         self.facebook_app = SocialApp(site=Site.objects.get_current(), provider='facebook', name='test', key='abc', secret='def')
         self.facebook_app.save()
Beispiel #16
0
    def handle(self, *args, **options):
        Site.objects.all().delete()
        SocialApp.objects.all().delete()

        site = Site(id=0, domain=options['domain'], name='custom')
        site.save()

        google = SocialApp(provider='google',
                           name='Google',
                           client_id='391769807258-1m9ojltdvphurdmuslv4\
        aoriq4jkc5p5.apps.googleusercontent.com',
                           secret='KtzOBNQTsof9fkGlB8iC5rLK')
        google.save()
        google.sites.set([site.id])

        self.stdout.write(self.style.SUCCESS('Succesfully changed domain'))
Beispiel #17
0
class InvitationTestCaseAllauth(InvitationTestCase):
    
    def setUp(self):
        super(InvitationTestCaseAllauth, self).setUp()
        self.saved_invitation_use_allauth = settings.INVITATION_USE_ALLAUTH
        settings.INVITATION_USE_ALLAUTH = True
        self.saved_socialaccount_providers = settings.SOCIALACCOUNT_PROVIDERS
        settings.SOCIALACCOUNT_PROVIDERS = {}   

        self.facebook_app = SocialApp(provider='facebook', name='test', key='abc', secret='def')
        self.facebook_app.save()
        
        
    def tearDown(self):
        super(InvitationTestCaseAllauth, self).tearDown()
        settings.INVITATION_USE_ALLAUTH = self.saved_invitation_use_allauth 
        settings.SOCIALACCOUNT_PROVIDERS = self.saved_socialaccount_providers             
Beispiel #18
0
class InvitationTestCaseAllauth(InvitationTestCase):
    
    def setUp(self):
        super(InvitationTestCaseAllauth, self).setUp()
        self.saved_invitation_use_allauth = settings.INVITATION_USE_ALLAUTH
        settings.INVITATION_USE_ALLAUTH = True
        self.saved_socialaccount_providers = settings.SOCIALACCOUNT_PROVIDERS
        settings.SOCIALACCOUNT_PROVIDERS = {}   

        self.facebook_app = SocialApp(site=Site.objects.get_current(), provider='facebook', name='test', key='abc', secret='def')
        self.facebook_app.save()
        
        
    def tearDown(self):
        super(InvitationTestCaseAllauth, self).tearDown()
        settings.INVITATION_USE_ALLAUTH = self.saved_invitation_use_allauth 
        settings.SOCIALACCOUNT_PROVIDERS = self.saved_socialaccount_providers             
Beispiel #19
0
    def set_up_social(self):
        self.social_app = SocialApp(provider='GitHub',
                                    name='GitHub',
                                    client_id='B',
                                    secret='A')
        self.social_app.save()

        self.social_account = SocialAccount(user=self.user,
                                            provider='github',
                                            uid='A')
        self.social_account.save()

        self.social_token = SocialToken(app=self.social_app,
                                        account=self.social_account,
                                        token='A',
                                        token_secret='B')
        self.social_token.save()
Beispiel #20
0
 def test_get_redir_user_demo(self):
     payload = {"user": {"username": self.demo["username"]}}
     self.client.login(username=payload["user"]["username"], password="******")
     sapp = SocialApp(provider='github', name='Github', client_id='<test>', secret='<test>')
     sapp.save()
     sacc = SocialAccount(uid=1001, user=self.test_user, provider="github")
     sacc.save()
     stoken = SocialToken(app=sapp, account=sacc, token="test_token")
     stoken.save()
     response = self.client.post('/accounts/profile', follow=True)
     first_url, first_response = response.redirect_chain[0]
     self.assertEqual(first_url, "/login?status=passed&token=test_token&username=testname&user_id=1001")
     self.client.login(username=payload["user"]["username"], password="******")
     stoken = SocialToken(app=sapp, account=sacc, token="test_token")
     stoken.save()
     response = self.client.post('/accounts/profile', follow=True)
     first_url, first_response = response.redirect_chain[0]
     self.assertEqual(first_url, "/login?status=passed&token=test_token&username=testname&user_id=1001")
 def get_app(self, request):
     app = settings.SOCIAL_APPS.get(self.id)
     from allauth.socialaccount.models import SocialApp
     return SocialApp(id=app.get('id'),
                      name='SocialApp instance',
                      provider=self.id,
                      client_id=app.get('client_id'),
                      secret=app.get('secret'),
                      key='')
Beispiel #22
0
    def setUp(self):
        super(InvitationTestCaseAllauth, self).setUp()
        self.saved_invitation_use_allauth = settings.INVITATION_USE_ALLAUTH
        settings.INVITATION_USE_ALLAUTH = True
        self.saved_socialaccount_providers = settings.SOCIALACCOUNT_PROVIDERS
        settings.SOCIALACCOUNT_PROVIDERS = {}   

        self.facebook_app = SocialApp(provider='facebook', name='test', key='abc', secret='def')
        self.facebook_app.save()
Beispiel #23
0
class InvitationTestCase(TestCase):
    """
    Base class for the test cases.
    
    This sets up one user and two keys -- one expired, one not -- which are 
    used to exercise various parts of the application.
    
    """
    def setUp(self):
        self.saved_socialaccount_providers = settings.SOCIALACCOUNT_PROVIDERS
        settings.SOCIALACCOUNT_PROVIDERS = {}   
        self.saved_invitation_use_allauth = settings.INVITATION_USE_ALLAUTH
        settings.INVITATION_USE_ALLAUTH = False
        
        self.sample_user = User.objects.create_user(username='******',
                                                    password='******',
                                                    email='*****@*****.**')
        self.sample_key = InvitationKey.objects.create_invitation(user=self.sample_user)
        self.expired_key = InvitationKey.objects.create_invitation(user=self.sample_user)
        self.expired_key.date_invited -= datetime.timedelta(days=settings.ACCOUNT_INVITATION_DAYS + 1)
        self.expired_key.save()
        
        self.sample_registration_data = {
            'invitation_key': self.sample_key.key,
            'username': '******',
            'email': '*****@*****.**',
            'password1': 'secret',
            'password2': 'secret',
            'tos': '1'}
        
        if allauth_installed:
            self.facebook_app = SocialApp(site=Site.objects.get_current(), provider='facebook', name='test', key='abc', secret='def')
            self.facebook_app.save()
        

    def assertRedirect(self, response, viewname):
        """Assert that response has been redirected to ``viewname``."""
        self.assertEqual(response.status_code, 302)
        expected_location = 'http://testserver' + reverse(viewname)
        self.assertEqual(response['Location'], expected_location)      

    def tearDown(self):
        settings.SOCIALACCOUNT_PROVIDERS = self.saved_socialaccount_providers 
        settings.INVITATION_USE_ALLAUTH = self.saved_invitation_use_allauth 
Beispiel #24
0
    def test_complete_login(self, mocker, rf):
        mocker.patch(
            "metecho.oauth2.github.views.GitHubOAuth2Adapter.complete_login")
        token = mock.MagicMock(app=SocialApp(provider="github"))
        request = rf.get("/")
        adapter = CustomGitHubOAuth2Adapter(request)
        adapter.complete_login(request, None, token)

        # make sure this created a SocialApp in the db
        assert token.app.pk is not None
Beispiel #25
0
    def get_app(self, request, provider):
        # NOTE: Avoid loading models at top due to registry boot...
        from allauth.socialaccount.models import SocialApp

        config = app_settings.PROVIDERS.get(provider, {}).get('APP')
        if config:
            app = SocialApp(provider=provider)
            for field in ['client_id', 'secret', 'key', 'certificate']:
                setattr(app, field, config.get(field))
        else:
            app = SocialApp.objects.get_current(provider, request)
        return app
Beispiel #26
0
def init_social_providers():
    # Initialize social login providers.

    for name, data in settings.SOCIALACCOUNT_PROVIDERS.items():

        try:
            client_id = data.get('PROVIDER_KEY', '')
            secret = data.get('PROVIDER_SECRET_KEY', '')
            site = Site.objects.get(id=settings.SITE_ID)

            # Check that the provider is registered
            provider = providers.registry.by_id(name)

            # Code duplication since many2many fields cannot be initialized in one step
            exists = SocialApp.objects.filter(name=name,
                                              client_id=client_id,
                                              provider=name,
                                              secret=secret,
                                              sites=site)
            if not exists:
                app = SocialApp(
                    name=name,
                    client_id=client_id,
                    provider=name,
                    secret=secret,
                    key='',
                )
                app.save()
                app.sites.add(site)
                app.save()
                logger.info("initializing social provider %s" % name)

        except Exception, exc:
            raise ImproperlyConfigured("error setting provider %s, %s" %
                                       (name, exc))
Beispiel #27
0
def run():
    # create postgres extension
    with connection.cursor() as cursor:
        try:
            cursor.execute('create extension hstore;')
        except django.db.ProgrammingError as ex:
            if 'already exists' not in str(ex):
                raise
            LOG.info(str(ex).strip())
        else:
            LOG.info('extension hstore created')
    # create superuser
    User = get_user_model()
    admin_email = settings.ENV_CONFIG.admin_email
    try:
        admin = User.objects.get(username='******')
    except User.DoesNotExist:
        LOG.info('create admin user')
        User.objects.create_superuser('admin', admin_email, 'admin')
    else:
        LOG.info('update admin user email')
        admin.email = admin_email
        admin.save()
    # update site
    root_url = urlparse(settings.ENV_CONFIG.root_url)
    LOG.info('update site info')
    site = Site.objects.get_current()
    site.domain = root_url.netloc
    site.name = root_url.netloc
    site.save()
    # create social app
    client_id = settings.SOCIAL_APP_GITHUB['client_id']
    secret = settings.SOCIAL_APP_GITHUB['secret']
    provider = GitHubProvider.id
    try:
        social_app = SocialApp.objects.get(provider=provider, name='github')
    except SocialApp.DoesNotExist:
        LOG.info('create github social app')
        social_app = SocialApp(provider=provider,
                               name='github',
                               client_id=client_id,
                               secret=secret)
    else:
        LOG.info('update github social app')
        social_app.client_id = client_id
        social_app.secret = secret
    social_app.save()
    if not social_app.sites.filter(pk=site.pk).exists():
        social_app.sites.add(site)
        social_app.save()
    def update_provider(self, data):
        # Update the existing provider with current settings.
        try:
            app = SocialApp.objects.get(provider=data['provider'])
            for k, v in data.items():
                setattr(app, k, v)
            app.save()
            self.stdout.write(
                "Updated existing authentication provider (pk=%s)" % app.pk)

        # Create the provider if necessary.
        except ObjectDoesNotExist:
            app = SocialApp(**data)
            app.save()
            self.stdout.write("Created new authentication provider (pk=%s)" %
                              app.pk)

        # Ensure the provider applies to the current default site.
        sites_count = app.sites.count()
        if sites_count == 0:
            default_site = Site.objects.get(pk=settings.SITE_ID)
            app.sites.add(default_site)
Beispiel #29
0
    def handle(self, *args, **options):
        for system in ("All", "Booking", "Search"):
            System(name=f"{system}").save()
        user = User.objects.filter(username="******")
        if not user:
            user = User(
                username="******",
                is_superuser=True,
                is_staff=True,
                is_active=True,
                password="******"
                "JQVxLuT1RoWZIehhr8s59FGg8=",
            )
            user.save()
        local_domain = "localhost:8000"
        site = None
        try:
            site = Site.objects.get(domain="example.com")
            site.domain = "localhost:8000"
            site.name = "localhost:8000"
            site.save()
        except Site.DoesNotExist:
            site = Site.objects.get(domain=local_domain)

        social_app = SocialApp(
            provider="google",
            name="google",
            client_id=os.getenv("DEVEL_GOOGLE_OAUTH_CLIENT_ID", "unspecified"),
            secret=os.getenv("DEVEL_GOOGLE_OAUTH_SECRET", "unspecified"),
        )
        social_app.save()
        social_app.sites.add(site)

        SyncUsersCommand().handle()
        InitInstanceCommand().handle()

        on_call_group = Group.objects.get(name="on_call")
        for user in User.objects.all():
            user.groups.add(on_call_group)
Beispiel #30
0
    def setUp(self):
        super(InvitationTestCaseAllauth, self).setUp()
#         self.saved_invitation_use_allauth = settings.INVITATION_USE_ALLAUTH
#         settings.INVITATION_USE_ALLAUTH = True
        self.saved_invite_mode = getattr(settings, 'INVITE_MODE', None)
        settings.INVITE_MODE = True
        social_accounts = getattr(settings, 'SOCIALACCOUNT_PROVIDERS', None)
        self.saved_socialaccounts = social_accounts
        settings.SOCIALACCOUNT_PROVIDERS = {}

        self.facebook_app = SocialApp(provider='facebook', name='test',
                                      key='abc', secret='def')
        self.facebook_app.save()
        self.facebook_app.sites.add(Site.objects.get_current())
Beispiel #31
0
    def get_app(self, request, provider):
        # NOTE: Avoid loading models at top due to registry boot...
        from allauth.socialaccount.models import SocialApp

        config = app_settings.PROVIDERS.get(provider, {}).get("APP")
        if config:
            if (app_settings.STORE_TOKENS
                    and SocialApp.objects.filter(provider=provider).exists()):
                # We already saved the app. Fetch and return it right away...

                # FIXME: Ideally there should be a way to specify specific sites
                # with settings-based credentials. We currently don't, so we can't
                # use the get_current method that consider sites as well.
                app = SocialApp.objects.get(provider=provider)
            else:
                app = SocialApp(provider=provider)
                for field in ["client_id", "secret", "key", "certificate_key"]:
                    setattr(app, field, config.get(field))
                if app_settings.STORE_TOKENS:
                    app.save()
        else:
            app = SocialApp.objects.get_current(provider, request)
        return app
    def handle(self, *args, **options):
        provider = options['provider']
        name = options.get('name') or provider.title()
        client_id = options['client_id']
        client_secret = options['client_secret']

        # Delete the specific provider if it exists.
        # Note that QuerySet.update_or_create is an alternative.
        SocialApp.objects.filter(provider=provider).delete()
        a = SocialApp(provider=provider, name=name, secret=client_secret,
                      client_id=client_id, key='')
        a.save()

        # Now associate this provider with all site instances.
        sites = [i for i in Site.objects.all()]
        a.sites.add(*sites)

        self.stdout.write(self.style.SUCCESS(
            "Provider '{}' -> client ID '{}'".format(a.name, a.client_id)
        ))
        self.stdout.write(self.style.SUCCESS(
            "Associated with site(s): {}".format(', '.join(s.name for s in sites))
        ))
Beispiel #33
0
    def handle(self, *args, **options):
        changed = False
        try:
            app = SocialApp.objects.get(provider=HelsinkiProvider.id)
        except SocialApp.DoesNotExist:
            app = SocialApp(provider=HelsinkiProvider.id)
            self.stdout.write(self.style.SUCCESS('Creating new SocialApp'))

        if not app.name:
            app.name = 'Helsingin kaupungin työntekijät'
            changed = True

        client_id = secret_key = None

        jwt_settings = getattr(settings, 'JWT_AUTH')
        if jwt_settings:
            client_id = jwt_settings.get('JWT_AUDIENCE')
            secret_key = jwt_settings.get('JWT_SECRET_KEY')

        if not client_id:
            raise ImproperlyConfigured(
                "You must set JWT_AUTH['JWT_AUDIENCE'] to correspond to your client ID"
            )
        if not secret_key:
            raise ImproperlyConfigured(
                "You must set JWT_AUTH['JWT_SECRET_KEY'] to correspond to your secret key"
            )

        if app.client_id != client_id:
            changed = True
            app.client_id = client_id
        if app.secret != secret_key:
            changed = True
            app.secret = secret_key
        if changed:
            app.save()

        if not app.sites.exists():
            from django.contrib.sites.models import Site

            app.sites.add(Site.objects.get(id=settings.SITE_ID))
            changed = True

        if changed:
            self.stdout.write(
                self.style.SUCCESS('SocialApp successfully updated'))
        else:
            self.stdout.write(
                self.style.NOTICE('Already synced -- no changes needed'))
def init_configuration():
    
    ### Obtain Config Values ###
    config = ConfigParser()
    config.read('secrets.cfg')

    SITE_DOMAIN = config.get('django.contrib.sites', 'domain')

    GOOGLE_SECRET = config.get('GoogleAuth', 'secret')
    GOOGLE_CLIENT_ID = config.get('GoogleAuth', 'client_id')

    FACEBOOK_SECRET = config.get('FacebookApp', 'secret')
    FACEBOOK_CLIENT_ID = config.get('FacebookApp', 'client_id')
    
    ### ### ### ### ###


    # I'm going to assume that there is an existing site defined.
    # Lets obtain it and modify the values.
    site = Site.objects.get()
    site.domain = SITE_DOMAIN
    site.name = SITE_DOMAIN
    site.save()

    # Add Google SocialApp
    google = SocialApp(
        provider='google',
        secret=GOOGLE_SECRET,
        client_id=GOOGLE_CLIENT_ID,
        name='Google Auth'
    )
    google.save()

    # Add Facebook SocialApp
    facebook = SocialApp(
        provider = 'facebook',
        secret=FACEBOOK_SECRET,
        client_id=FACEBOOK_CLIENT_ID,
        name='Facebook App'
    )
    facebook.save()

    # Associate Django site with Apps
    google.sites.add(site)
    facebook.sites.add(site)
Beispiel #35
0
    def social_app_setting(self, domain, client_id, secret):
        default_site_1 = Site.objects.get(id=1)
        default_site_1.domain = domain
        default_site_1.name = domain
        default_site_1.save()

        new_social_app = SocialApp(
            id=1,
            provider='google',
            name=domain,
            client_id=client_id,
            secret=secret,
            key='',
        )

        new_social_app.save()
        new_social_app.sites.add(default_site_1)
        new_social_app.save()
    def handle(self, *args, **options):
        changed = False
        try:
            app = SocialApp.objects.get(provider=HelsinkiProvider.id)
        except SocialApp.DoesNotExist:
            app = SocialApp(provider=HelsinkiProvider.id)
            self.stdout.write(self.style.SUCCESS('Creating new SocialApp'))

        if not app.name:
            app.name = 'Helsingin kaupungin työntekijät'
            changed = True

        client_id = secret_key = None

        jwt_settings = getattr(settings, 'JWT_AUTH')
        if jwt_settings:
            client_id = jwt_settings.get('JWT_AUDIENCE')
            secret_key = jwt_settings.get('JWT_SECRET_KEY')

        if not client_id:
            raise ImproperlyConfigured("You must set JWT_AUTH['JWT_AUDIENCE'] to correspond to your client ID")
        if not secret_key:
            raise ImproperlyConfigured("You must set JWT_AUTH['JWT_SECRET_KEY'] to correspond to your secret key")

        if app.client_id != client_id:
            changed = True
            app.client_id = client_id
        if app.secret != secret_key:
            changed = True
            app.secret = secret_key
        if changed:
            app.save()

        if not app.sites.exists():
            from django.contrib.sites.models import Site

            app.sites.add(Site.objects.get(id=settings.SITE_ID))
            changed = True

        if changed:
            self.stdout.write(self.style.SUCCESS('SocialApp successfully updated'))
        else:
            self.stdout.write(self.style.NOTICE('Already synced -- no changes needed'))
    def handle(self, *args, **options):
        if verify_socialaccount() is True and verify_google() is True:
            from allauth.socialaccount.models import SocialApp

            self.stdout.write(self.style.SUCCESS(
                'GENERATING GOOGLE APPS from server/base/sites.py...'
            ))

            for site in SITES.keys():
                if 'GOOGLE_CLIENT_ID' and 'GOOGLE_SECRET' in SITES[site].keys():
                    if SITES[site]['GOOGLE_CLIENT_ID'] != '' and SITES[site]['GOOGLE_CLIENT_ID'] != '':
                        try:
                            social_app = SocialApp.objects.get(
                                name = SITES[site]['SITE_NAME'],
                                provider = 'google'
                            )
                            if social_app.client_id != SITES[site]['GOOGLE_CLIENT_ID'] or social_app.secret != SITES[site]['GOOGLE_SECRET']:
                                social_app.client_id = SITES[site]['GOOGLE_CLIENT_ID']
                                social_app.secret = SITES[site]['GOOGLE_SECRET']
                                social_app.save()
                                self.stdout.write(self.style.SUCCESS('UPDATED: %s social app key and secret with current values.' % (social_app.name)))
                            else:
                                self.stdout.write(self.style.WARNING('SOCIAL APP ALREADY EXISTS: %s social app key and secret unchanged.' % (social_app.name)))
                        except ObjectDoesNotExist:
                            picked_site = Site.objects.get(name=SITES[site]['SITE_NAME'])
                            social_app = SocialApp(
                                provider = 'google',
                                name = SITES[site]['SITE_NAME'],
                                client_id = SITES[site]['GOOGLE_CLIENT_ID'],
                                secret = SITES[site]['GOOGLE_SECRET']
                            )
                            social_app.save()
                            social_app.sites = [picked_site]
                            social_app.save()
                            self.stdout.write(self.style.SUCCESS('LINKED GOOGLE APP: %s' % (SITES[site]['SITE_NAME'])))
            self.stdout.write(self.style.SUCCESS('...DONE'))

        else:
            self.stdout.write(self.style.WARNING(
                'Google provider not in INSTALLED_APPS. Please check /base/settings.py'
            ))
Beispiel #38
0
    def handle(self, *args, **options):

        site = Site.objects.first()
        if site.domain != 'localhost:8000':
            site.domain = 'www.spyrelabs.org'
            site.name = 'www.spyrelabs.org'
            site.save()

        try:
            SocialApp.objects.get(name='Paypal Application')
        except SocialApp.DoesNotExist:
            paypal_app = SocialApp(
                provider='paypal',
                name='Paypal Application',
                client_id=
                'AX0UovJTfneT-r-vR7eIv8o-jvin6Dw3RwM_5qWtKLJcJO443yH3c-QqJ_JLaBgAfWkN-zKzcCVQREGJ',
                secret=
                'ECpTS7SBU9oxRcwTYZLuxRikSXB9Usaw9Lguy_G8Mm1gaS70no6He83JkQ7D7JYzysxVi3pxY54H0nqF',
            )
            paypal_app.save()
            paypal_app.sites.add(site)
            paypal_app.save()

        admin = User.objects.filter(username='******').first()
        if admin is None:
            call_command('createsuperuser2',
                         email='*****@*****.**',
                         username="******",
                         password='******')
            admin = User.objects.filter(username='******').first()

        task = self.create_task()
        self.root = Task.add_root(instance=task)
        tasks = [task]
        for _ in range(10):
            task = self.create_task()
            parent: Task = random.choice(tasks)
            parent.add_child(instance=task)
            tasks.append(task)
Beispiel #39
0
from django.contrib.sites.models import Site
from allauth.socialaccount.models import SocialApp
import os

# More about the following here: https://wsvincent.com/django-allauth-tutorial/
first_site = Site.objects.get(pk=1)
first_site.name = os.environ['TWITTER_HOST']
first_site.domain = os.environ['TWITTER_HOST']
first_site.save()

# More about the following here: https://django-allauth.readthedocs.io/en/latest/providers.html
social_app = SocialApp.objects.filter(provider='twitter')
if not social_app:
    social_app = SocialApp()
else:
    social_app = social_app[0]
social_app.provider = 'twitter'
social_app.name = 'Twitter'
social_app.client_id = os.environ['TWITTER_CONSUMER_KEY']
social_app.secret = os.environ['TWITTER_CONSUMER_SECRET']
social_app.save()

social_app.sites.add(first_site)
Beispiel #40
0
    def handle(self, *args, **options):
        # add superuser
        # u = User(username='******', email='*****@*****.**')
        # u.set_password('a')
        # u.is_superuser = True
        # u.is_staff = True
        # u.save()

        User = get_user_model()
        user = User.objects.create_superuser(email='*****@*****.**',
                                             username='******',
                                             password='******')
        EmailAddress.objects.create(user=user,
                                    email=user.email,
                                    verified=True,
                                    primary=True)

        # add social app

        sapp = SocialApp(
            provider='google',
            name='google app',
            client_id=
            '205782653310-fjjullvs7cklq6su4qp0o7e8def79vfg.apps.googleusercontent.com',
            secret='sMv5Xrje1aP_f__HS3g3Jt2B')

        site = Site.objects.get()
        site.domain = 'musicroom.ml'
        site.name = 'musicroom'
        site.save()

        sapp.save()
        sapp.sites.add(site)  # or your site id

        # add social account

        # sacc = SocialAccount(uid="<your facebook uid>", user=user, provider='facebook')
        # sacc.save()

        # ----------------------------------------------------------------------------------------------------

        user = User.objects.get(email='*****@*****.**')

        p = p1

        playlist = models.Playlist.objects.create(is_public=p['is_public'],
                                                  name=p['name'],
                                                  creator=user,
                                                  place=p['place'])
        playlist.owners.add(user)

        for track in p['tracks']:
            models.Track.objects.create(playlist=playlist,
                                        order=track['order'],
                                        creator=user,
                                        data=track['data'])

        playlist = models.Playlist.objects.create(
            is_public=True, name='private playlist of user b', creator=user)
        playlist.owners.add(user)

        p = p2

        playlist = models.Playlist.objects.create(is_public=p['is_public'],
                                                  name=p['name'],
                                                  creator=user,
                                                  place=p['place'])
        playlist.owners.add(user)

        for track in p['tracks']:
            models.Track.objects.create(playlist=playlist,
                                        order=track['order'],
                                        creator=user,
                                        data=track['data'])

        # ----------------------------------------------------------------------------------------------------

        user = User.objects.create(email='*****@*****.**',
                                   username='******',
                                   password='******')
        EmailAddress.objects.create(user=user,
                                    email=user.email,
                                    verified=True,
                                    primary=True)

        playlist = models.Playlist.objects.create(
            is_public=True, name='public playlist of user b', creator=user)
        playlist.owners.add(user)

        track_1 = models.Track.objects.create(playlist=playlist,
                                              order=1,
                                              creator=user)
        track_2 = models.Track.objects.create(playlist=playlist,
                                              order=2,
                                              creator=user)
        track_3 = models.Track.objects.create(playlist=playlist,
                                              order=3,
                                              creator=user)

        playlist = models.Playlist.objects.create(
            is_public=True, name='private playlist of user b', creator=user)
        playlist.owners.add(user)

        track_1 = models.Track.objects.create(playlist=playlist,
                                              order=1,
                                              creator=user)
        track_2 = models.Track.objects.create(playlist=playlist,
                                              order=2,
                                              creator=user)
        track_3 = models.Track.objects.create(playlist=playlist,
                                              order=3,
                                              creator=user)
Beispiel #41
0
class GitManagerTestCases(TestCase):
    def setUp(self):
        call_command('loaddata', 'fixtures/steps.json', verbosity=0)
        call_command('loaddata',
                     'fixtures/package_categories_languages.json',
                     verbosity=0)
        call_command('loaddata', 'fixtures/cookiecutter.json', verbosity=0)

        self.user = User.objects.create_user('test', '*****@*****.**', 'test')
        self.workbench_user = WorkbenchUser.objects.get(user=self.user)
        self.second_user = User.objects.create_user('test2', '*****@*****.**',
                                                    'test2')
        self.git_repo = GitRepository.objects.create(
            name='Experiment',
            owner=self.workbench_user,
            github_url='https://github')
        schema = DataSchema(name='main')
        schema.save()
        self.experiment = Experiment.objects.create(title='Experiment',
                                                    description='test',
                                                    owner=self.workbench_user,
                                                    git_repo=self.git_repo,
                                                    language_id=1,
                                                    template_id=2,
                                                    schema=schema)
        self.client = Client()
        self.client.login(username='******', password='******')

        if self._testMethodName is not 'test_init_github_helper_no_socialtoken':
            self.set_up_social()

    def set_up_social(self):
        self.social_app = SocialApp(provider='GitHub',
                                    name='GitHub',
                                    client_id='B',
                                    secret='A')
        self.social_app.save()

        self.social_account = SocialAccount(user=self.user,
                                            provider='github',
                                            uid='A')
        self.social_account.save()

        self.social_token = SocialToken(app=self.social_app,
                                        account=self.social_account,
                                        token='A',
                                        token_secret='B')
        self.social_token.save()

    def test_init_github_helper_no_socialtoken(self):
        github_helper = GitHubHelper
        args = [self.user, 'test']
        self.assertRaises(ValueError, github_helper, *args)

    @patch('git_manager.helpers.github_helper.GitHubHelper._get_github_object')
    def test_init_github_helper(self, mock_github):
        mock_github.return_value = GithubMock()
        github_helper = GitHubHelper(self.user, 'test')
        self.assertIsNotNone(github_helper)

    @patch('git_manager.helpers.github_helper.GitHubHelper._get_github_object')
    def test_init_github_helper_create(self, mock_github):
        mock_github.return_value = GithubMock()
        github_helper = GitHubHelper(self.user, 'test', create=True)
        self.assertIsNotNone(github_helper)
        self.assertEqual(github_helper.github_repository.repo_name,
                         'newly_created_repo')

    @patch('git_manager.helpers.github_helper.GitHubHelper._get_github_object')
    def test_github_owner(self, mock_github):
        mock_github.return_value = GithubMock()
        github_helper = GitHubHelper(self.user, 'test')
        self.assertIsNotNone(github_helper)
        self.assertEqual(github_helper.owner, 'test')

    @patch('git_manager.helpers.github_helper.GitHubHelper._get_github_object')
    def test_init_github_helper(self, mock_github):
        mock_github.return_value = GithubMock()
        github_helper = GitHubHelper(self.user, 'test')
        self.assertIsNotNone(github_helper)
        self.assertEqual(github_helper.get_clone_url(), 'https://A@clone-url')

    @patch('git_manager.helpers.github_helper.GitHubHelper._get_github_object')
    def test_github_list_folder(self, mock_github):
        mock_github.return_value = GithubMock()
        github_helper = GitHubHelper(self.user, 'test')
        self.assertIsNotNone(github_helper)
        self.assertEqual(github_helper.list_files_in_folder('test1'),
                         GithubMockRepo.TEST1_LIST)

    @patch('git_manager.helpers.github_helper.GitHubHelper._get_github_object')
    def test_github_list_folder_with_slash(self, mock_github):
        mock_github.return_value = GithubMock()
        github_helper = GitHubHelper(self.user, 'test')
        self.assertIsNotNone(github_helper)
        self.assertEqual(github_helper.list_files_in_folder('/test1'),
                         GithubMockRepo.TEST1_LIST)

    @patch('git_manager.helpers.github_helper.GitHubHelper._get_github_object')
    def test_github_list_folder_empty(self, mock_github):
        mock_github.return_value = GithubMock()
        github_helper = GitHubHelper(self.user, 'test')
        self.assertIsNotNone(github_helper)
        self.assertEqual(github_helper.list_files_in_folder(),
                         GithubMockRepo.TEST2_LIST)

    @patch('git_manager.helpers.github_helper.GitHubHelper._get_github_object')
    def test_view_file_in_repo(self, mock_github):
        mock_github.return_value = GithubMock()
        github_helper = GitHubHelper(self.user, 'test')
        self.assertIsNotNone(github_helper)
Beispiel #42
0
        super_user = User.objects.filter(is_superuser=1).first()
        if not super_user:
            User.objects.create_superuser(username='******', password='******', email='')
{%if cookiecutter.install_wagtail == "y" %}
        root_page = Page.objects.get(slug='root')

        main_site = Site.objects.get(is_default_site=1)
        current_home_page = main_site.root_page
        if current_home_page.content_type_id == 1:
            new_home_page = HomePage(slug='{{cookiecutter.project_slug}}-home', title='{{cookiecutter.project_name}} HomePage')
            root_page.add_child(instance=new_home_page)
            new_home_page.save_revision().publish()
            main_site.root_page = new_home_page
            main_site.save()
            current_home_page.delete()
            current_home_page = new_home_page

{% endif %}

        {%if cookiecutter.install_allauth == "y" %}
        from allauth.socialaccount.models import SocialApp
        if len(SocialApp.objects.all()) == 0:
            print("No Social Apps creating defaults")
            facebook = SocialApp(provider='facebook', name='Facebook Oauth', client_id='changeme', secret='changeme')
            facebook.save()
            facebook.sites.add(1)
            google = SocialApp(provider='google', name='Google Oauth', client_id='changeme', secret='changeme')
            google.save()
            google.sites.add(1)
        {% endif %}
Beispiel #43
0
fillDatabase()
# user1 is a customer
# users 2-9 are service providers
# admin is staff and superuser
# pass is admin

# default site, for password reset
site = Site.objects.all()[0]
name = settings.PRODUCTION_URL.split('//')[1]
site.domain = name
site.name = name
site.save()

from allauth.socialaccount.models import SocialApp

fb = SocialApp()
fb.provider = "facebook"
fb.name = "Facebook"
fb.client_id = "207371922661306"
fb.key = ''
fb.secret = "67e595cb85d9836c305fe4b9985180df"
fb.save()

g = SocialApp()
g.provider = "google"
g.name = "Google"
g.client_id = "236816371004-c46h64qimvsqffbrdt8k5o5hq90iigjh.apps.googleusercontent.com"
g.key = ''
g.secret = "n6NuvZ1_jAqKq_r6V6pWQ8Ii"
g.save()
Beispiel #44
0
fillDatabase()
# user1 is a customer
# users 2-9 are service providers
# admin is staff and superuser
# pass is admin

# default site, for password reset
site = Site.objects.all()[0]
name = settings.PRODUCTION_URL.split('//')[1]
site.domain = name
site.name = name
site.save()

from allauth.socialaccount.models import SocialApp

fb = SocialApp()
fb.provider = "facebook"
fb.name = "Facebook"
fb.client_id = "207371922661306"
fb.key = ''
fb.secret = "67e595cb85d9836c305fe4b9985180df"
fb.save()

g = SocialApp()
g.provider = "google"
g.name = "Google"
g.client_id = "236816371004-c46h64qimvsqffbrdt8k5o5hq90iigjh.apps.googleusercontent.com"
g.key = ''
g.secret = "n6NuvZ1_jAqKq_r6V6pWQ8Ii"
g.save()
Beispiel #45
0
def migrate(read_only: bool = False) -> bool:
    """
    Create and configure database social apps.

    Configure backends only for the first Site object.

    :param read_only:
    :return: True if (read_only and a migrate is required) or (not read_only and modifications were performed)
    """
    # noinspection PyPackageRequirements,PyUnresolvedReferences
    from allauth.socialaccount.models import SocialApp
    from django.contrib.sites.models import Site

    expected_configurations = {}
    for config in get_loaded_configurations().values():
        expected_configurations[(config.name, config.provider_id)] = config
    action_required = False
    to_remove_db_app_ids = []
    to_create_db_apps = []
    db_apps = {}
    for social_app in SocialApp.objects.filter(
        name__startswith=SocialProviderConfiguration.name_prefix
    ):
        key = (social_app.name, social_app.provider)
        if key not in expected_configurations:
            to_remove_db_app_ids.append(social_app.pk)
            continue
        else:
            db_apps[key] = social_app
    for key, configuration in expected_configurations.items():
        if key not in db_apps:
            to_create_db_apps.append(
                SocialApp(
                    name=configuration.name,
                    provider=configuration.provider_id,
                    **configuration.values
                )
            )
            continue
        app = db_apps[key]
        save = False
        for k, v in configuration.values.items():
            if getattr(app, k) != v:
                setattr(app, k, v)
                save = True
        if save:
            action_required = True
            if not read_only:
                app.save()
    if to_remove_db_app_ids:
        action_required = True
        if not read_only:
            SocialApp.objects.filter(pk__in=to_remove_db_app_ids).delete()
    if to_create_db_apps:
        action_required = True
        if not read_only:
            SocialApp.objects.bulk_create(to_create_db_apps)

    db_site = Site.objects.filter(pk=1).first()
    if db_site:
        required_db_ids = {
            x[0]
            for x in SocialApp.objects.filter(
                name__startswith=SocialProviderConfiguration.name_prefix
            ).values_list("id")
        }
        q = SocialApp.sites.through
        existing_db_ids = {
            x[0]
            for x in q.objects.filter(
                site_id=db_site.pk, socialapp_id__in=required_db_ids
            ).values_list("socialapp_id")
        }
        to_create_db_through_app = [
            q(site_id=db_site.pk, socialapp_id=x)
            for x in required_db_ids
            if x not in existing_db_ids
        ]
        if to_create_db_through_app:
            action_required = True
            if not read_only:
                q.objects.bulk_create(to_create_db_through_app)
    return action_required
Beispiel #46
0
from course.models import Teacher, Course
from django.contrib.sites.models import Site
from allauth.socialaccount.models import SocialApp

Site.objects.all().delete()
SocialApp.objects.all().delete()
Teacher.objects.all().delete()
Course.objects.all().delete()

site = Site(id=0, domain='localhost:8000', name='localhost')
site.save()

google = SocialApp(provider='google',
                   name='Google',
                   client_id='391769807258-1m9ojltdvphurdmuslv4\
aoriq4jkc5p5.apps.googleusercontent.com',
                   secret='KtzOBNQTsof9fkGlB8iC5rLK')
google.save()
google.sites.set([site.id])

print(f'Default domain is localhost:8000 if you want to \
change it run "make changedomain DOMAIN=your_domain"')

# SCC
roseli = Teacher(name='Roseli Ap. Francelin Romero')
ponce = Teacher(name='André Carlos Ponce de Leon Ferreira de Carvalho')
caetano = Teacher(name='Caetano Traina Junior')
agma = Teacher(name='Agma Juci Machado Traina')
mariac = Teacher(name='Maria Cristina Ferreira de Oliveira')
mariag = Teacher(name='Maria da Graça Campos Pimentel')
rosa = Teacher(name='João Luis Garcia Rosa')