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 #2
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 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 #4
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 #5
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 #6
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 #7
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.')
Beispiel #8
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()
 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 #10
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 #11
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 #12
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()
Beispiel #13
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'))
Beispiel #14
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")
Beispiel #15
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 #16
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 #17
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 #18
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 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 #20
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 #21
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 #22
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
        main_site.save()

        current_home_page = main_site.root_page
        if current_home_page.content_type_id == 1:
            print("No Homepage, creating default")
            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" %}
        if len(SocialApp.objects.all()) == 0:
            print("No Social Apps, creating defaults")
            facebook = SocialApp(provider="facebook",
                                 name="Facebook Oauth",
                                 client_id=getattr(settings, "INIT_AUTH_FACEBOOK_CLIENT_ID", "changeme"),
                                 secret=getattr(settings, "INIT_AUTH_FACEBOOK_SECRET_KEY", "changeme"))
            facebook.save()
            facebook.sites.add(1)
            google = SocialApp(provider="google",
                               name="Google Oauth",
                               client_id=getattr(settings, "INIT_AUTH_GOOGLE_CLIENT_ID", "changeme"),
                               secret=getattr(settings, "INIT_AUTH_GOOGLE_SECRET_KEY", "changeme"))
            google.save()
            google.sites.add(1)
{% endif -%}
Beispiel #24
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 #25
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 #26
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')
Beispiel #27
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 #28
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 #29
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)