Giter Site home page Giter Site logo

social-app-django's Introduction

Python Social Auth - Django

Build Status Build Status PyPI version Donate

Python Social Auth is an easy to setup social authentication/registration mechanism with support for several frameworks and auth providers.

Description

This is the Django component of the python-social-auth ecosystem, it implements the needed functionality to integrate social-auth-core in a Django based project.

Django version

This project will focus on the currently supported Django releases as stated on the Django Project Supported Versions table.

Backward compatibility with unsupported versions won't be enforced.

Documentation

Project documentation is available at https://python-social-auth.readthedocs.org/.

Setup

$ pip install social-auth-app-django

Contributing

See the CONTRIBUTING.md document for details.

Versioning

This project follows Semantic Versioning 2.0.0.

License

This project follows the BSD license. See the LICENSE for details.

Donations

This project is maintained on my spare time, consider donating to keep it improving.

Donate

social-app-django's People

Contributors

adamchainz avatar alexpantyukhin avatar andreif avatar aniav avatar avibrazil avatar bradenmacdonald avatar ccurvey avatar clintonb avatar dependabot[bot] avatar dhendo avatar dulmandakh avatar falcon1kr avatar floorlamp avatar hassek avatar jasonsanford avatar jcouyang avatar jgsogo avatar maartenkos avatar mhluongo avatar nijel avatar noirbizarre avatar omab avatar pre-commit-ci[bot] avatar ryankicks avatar samkuehn avatar shepilov-vladislav avatar technickai avatar tell-k avatar vinhub avatar webjunkie avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

social-app-django's Issues

SAML IDP config in database

In a multi tenant environment, I want to let my admins specify the IDP in an admin interface. Is there a recommendation for how to CRUD the SOCIAL_AUTH_SAML_ENABLED_IDPS in the database?

BitbucketOAuth2 backend has no refresh_token method

from django.contrib.auth.models import User

user = User.objects.all().first()
social = user.social_auth.get(provider='bitbucket-oauth2')
social.refresh_token()

^^ raises NotImplementedError: Refresh tokens for Bitbucket have not been implemented

Please provide some way to solve this problem, because bitbucket auth tokens expire really often, they have an expiry time of 1 hour. Manually refreshing the tokens is really a hard job.

Error with a requst to facebook to get a token

hi every one i have an error, with my account on facebook, when i send request to get the token for login
Erreur d’application: Un problème est survenu lors de la récupération des données pour l’application que vous avez demandée. Cette application n’est peut-être pas valide ou une défaillance temporaire a eu lieu. Veuillez réessayer ultérieurement.
when i try another facebook account it works and the token has returned.
so i try this script to send the request : `

<script src="https://connect.facebook.net/en_US/all.js" type="text/javascript"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { FB.init({ appId: '174280429741376', cookie: true, xfbml: true, status: true }); FB.getLoginStatus(function (response) { if (response.authResponse) { $('#AccessToken').val(response.authResponse.accessToken); } else { // do something...maybe show a login prompt } }); }); </script> `

Issue when migrate version 1.0.0

After upgrading I'm getting this error:

Traceback (most recent call last):
  File "manage.py", line 9, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 345, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 348, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 399, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/showmigrations.py", line 36, in handle
    return self.show_list(connection, options['app_labels'])
  File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/showmigrations.py", line 44, in show_list
    loader = MigrationLoader(connection, ignore_no_migrations=True)
  File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/loader.py", line 49, in __init__
    self.build_graph()
  File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/loader.py", line 293, in build_graph
    _reraise_missing_dependency(migration, parent, e)
  File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/loader.py", line 276, in _reraise_missing_dependency
    raise exc
  File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/loader.py", line 286, in build_graph
    self.graph.add_dependency(migration, key, parent)
  File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/graph.py", line 126, in add_dependency
    parent
django.db.migrations.exceptions.NodeNotFoundError: Migration social_django.0006_partial dependencies reference nonexistent parent node ('social_django', '0005_auto_20160727_2333')

CSRF on login

The login URLs (login/<service>/) are not using CSRF protection, thus it's possible to authenticate users by following links from third party sites.

It can be simply fixed by adding @require_POST decorator on social_django.views.auth, but that will require all users to change their logins to use POST instead of GET which it used so far, so I'm not sure this is good change by default. Maybe having this as opt-it?

Anyway I've applied the decorator in urls for our case: WeblateOrg/weblate@bfd2988#diff-926cd04e84cfd0cbeab80af203e8f6d0R36

Originally reported at HackerOne against Weblate.

No module named 'social'

Exception Value:
No module named 'social'
Exception Location: /...../python3.5/site-packages/social_core/utils.py in import_module, line 53

`/python3.5/site-packages/social_django/utils.py in wrapper

            return func(request, backend, *args, **kwargs)

 `

Getting error when some users authenticate via twitter: "argument of type 'NoneType' is not iterable"

Internal Server Error: /oauth/complete/twitter/

TypeError at /oauth/complete/twitter/
argument of type 'NoneType' is not iterable

Request Method: GET
Request URL: http://readkorean.ips.waseda.ac.jp/oauth/complete/twitter/?redirect_state=8pamjXPJPmZ6wWLIK6TPmsWV08xpgOjV&oauth_token=L44N9QAAAAAA0IepAAABXIBFNDA&oauth_verifier=tKDCkyq3uLGfPEAPLjQgx2YeaSfAtVei
Django Version: 1.11
Python Executable: /opt/virtualenv/readkorean.org/bin/python
Python Version: 3.5.2
Python Path: ['/srv/www/readkorean.org', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/opt/virtualenv/readkorean.org/lib/python3.5/site-packages']
Server time: Wed, 7 Jun 2017 10:57:39 +0900
Installed Applications:
['survey_app',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'social_django',
'vinaigrette',
'pagedown',
'markdown_deux',
'el_pagination',
'simpleblog']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'social_django.middleware.SocialAuthExceptionMiddleware',
'django.middleware.locale.LocaleMiddleware']

Traceback:

File "/opt/virtualenv/readkorean.org/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/opt/virtualenv/readkorean.org/lib/python3.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)

File "/opt/virtualenv/readkorean.org/lib/python3.5/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)

File "/opt/virtualenv/readkorean.org/lib/python3.5/site-packages/social_django/utils.py" in wrapper
50. return func(request, backend, *args, **kwargs)

File "/opt/virtualenv/readkorean.org/lib/python3.5/site-packages/social_django/views.py" in complete
28. redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs)

File "/opt/virtualenv/readkorean.org/lib/python3.5/site-packages/social_core/actions.py" in do_complete
41. user = backend.complete(user=user, *args, **kwargs)

File "/opt/virtualenv/readkorean.org/lib/python3.5/site-packages/social_core/backends/base.py" in complete
39. return self.auth_complete(*args, **kwargs)

File "/opt/virtualenv/readkorean.org/lib/python3.5/site-packages/social_core/utils.py" in wrapper
253. return func(*args, **kwargs)

File "/opt/virtualenv/readkorean.org/lib/python3.5/site-packages/social_core/backends/oauth.py" in auth_complete
181. token = self.get_unauthorized_token()

File "/opt/virtualenv/readkorean.org/lib/python3.5/site-packages/social_core/backends/oauth.py" in get_unauthorized_token
200. raise AuthTokenError(self, 'Missing unauthorized token')

 During handling of the above exception (Token error: Missing unauthorized token), another exception occurred:

File "/opt/virtualenv/readkorean.org/lib/python3.5/site-packages/django/shortcuts.py" in resolve_url
147. return reverse(to, args=args, kwargs=kwargs)

File "/opt/virtualenv/readkorean.org/lib/python3.5/site-packages/django/urls/base.py" in reverse
91. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))

File "/opt/virtualenv/readkorean.org/lib/python3.5/site-packages/django/urls/resolvers.py" in _reverse_with_prefix
497. raise NoReverseMatch(msg)

 During handling of the above exception (Reverse for 'None' not found. 'None' is not a valid view function or pattern name.), another exception occurred:

File "/opt/virtualenv/readkorean.org/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)

File "/opt/virtualenv/readkorean.org/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)

File "/opt/virtualenv/readkorean.org/lib/python3.5/site-packages/django/core/handlers/base.py" in process_exception_by_middleware
227. response = middleware_method(request, exception)

File "/opt/virtualenv/readkorean.org/lib/python3.5/site-packages/social_django/middleware.py" in process_exception
51. return redirect(url)

File "/opt/virtualenv/readkorean.org/lib/python3.5/site-packages/django/shortcuts.py" in redirect
56. return redirect_class(resolve_url(to, *args, **kwargs))

File "/opt/virtualenv/readkorean.org/lib/python3.5/site-packages/django/shortcuts.py" in resolve_url
153. if '/' not in to and '.' not in to:

Exception Type: TypeError at /oauth/complete/twitter/
Exception Value: argument of type 'NoneType' is not iterable
Request information:
USER: taegukhandshake

GET:
oauth_token = 'L44N9QAAAAAA0IepAAABXIBFNDA'
oauth_verifier = 'tKDCkyq3uLGfPEAPLjQgx2YeaSfAtVei'
redirect_state = '8pamjXPJPmZ6wWLIK6TPmsWV08xpgOjV'

POST: No POST data

FILES: No FILES data

COOKIES:
_gat = '1'
_ga = 'GA1.3.1390045745.1496752345'
_gid = 'GA1.3.1894409811.1496752345'
sessionid = 'msgdrerhds3lo25k3vq27bd9thnesydr'
csrftoken = 'zP4qkhWFLeeoWfcdQoAVY1aP2a9U8dGxEjZ1MIX4PYOOyVchsJzBZo7T5tWafCRo'

META:
CONTEXT_DOCUMENT_ROOT = '/var/www/html'
CONTEXT_PREFIX = ''
CSRF_COOKIE = 'zP4qkhWFLeeoWfcdQoAVY1aP2a9U8dGxEjZ1MIX4PYOOyVchsJzBZo7T5tWafCRo'
DOCUMENT_ROOT = '/var/www/html'
GATEWAY_INTERFACE = 'CGI/1.1'
HTTP_ACCEPT = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8'
HTTP_ACCEPT_ENCODING = 'gzip, deflate'
HTTP_ACCEPT_LANGUAGE = 'en-PH,en-US;q=0.8,en;q=0.6'
HTTP_CONNECTION = 'keep-alive'
HTTP_COOKIE = '_gat=1; sessionid=msgdrerhds3lo25k3vq27bd9thnesydr; csrftoken=zP4qkhWFLeeoWfcdQoAVY1aP2a9U8dGxEjZ1MIX4PYOOyVchsJzBZo7T5tWafCRo; _ga=GA1.3.1390045745.1496752345; _gid=GA1.3.1894409811.1496752345'
HTTP_HOST = 'readkorean.ips.waseda.ac.jp'
HTTP_UPGRADE_INSECURE_REQUESTS = '1'
HTTP_USER_AGENT = 'Mozilla/5.0 (Linux; Android 5.1.1; SM-J500G Build/LMY48B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.89 Mobile Safari/537.36'
PATH_INFO = '/oauth/complete/twitter/'
PATH_TRANSLATED = '/srv/www/readkorean.org/survey_website/wsgi.py/oauth/complete/twitter/'
QUERY_STRING = 'redirect_state=8pamjXPJPmZ6wWLIK6TPmsWV08xpgOjV&oauth_token=L44N9QAAAAAA0IepAAABXIBFNDA&oauth_verifier=tKDCkyq3uLGfPEAPLjQgx2YeaSfAtVei'
REMOTE_ADDR = '112.198.68.141'
REMOTE_PORT = '21520'
REQUEST_METHOD = 'GET'
REQUEST_SCHEME = 'http'
REQUEST_URI = '/oauth/complete/twitter/?redirect_state=8pamjXPJPmZ6wWLIK6TPmsWV08xpgOjV&oauth_token=L44N9QAAAAAA0IepAAABXIBFNDA&oauth_verifier=tKDCkyq3uLGfPEAPLjQgx2YeaSfAtVei'
SCRIPT_FILENAME = '/srv/www/readkorean.org/survey_website/wsgi.py'
SCRIPT_NAME = ''
SERVER_ADDR = '133.9.48.105'
SERVER_ADMIN = '[email protected]'
SERVER_NAME = 'readkorean.ips.waseda.ac.jp'
SERVER_PORT = '80'
SERVER_PROTOCOL = 'HTTP/1.1'
SERVER_SIGNATURE = '

Apache/2.4.18 (Ubuntu) Server at readkorean.ips.waseda.ac.jp Port 80\n'
SERVER_SOFTWARE = 'Apache/2.4.18 (Ubuntu)'
apache.version =
mod_wsgi.application_group = 'readkorean.ips.waseda.ac.jp|'
mod_wsgi.callable_object = 'application'
mod_wsgi.daemon_connects = '1'
mod_wsgi.daemon_restarts = '0'
mod_wsgi.daemon_start = '1496800659882731'
mod_wsgi.enable_sendfile = '0'
mod_wsgi.handler_script = ''
mod_wsgi.ignore_activity = '0'
mod_wsgi.listener_host = ''
mod_wsgi.listener_port = '80'
mod_wsgi.path_info = '/oauth/complete/twitter/'
mod_wsgi.process_group = 'readkorean.org'
mod_wsgi.queue_start = '1496800659882434'
mod_wsgi.request_handler = 'wsgi-script'
mod_wsgi.request_id = 'fsChD30VKMg'
mod_wsgi.request_start = '1496800659882110'
mod_wsgi.script_name = ''
mod_wsgi.script_reloading = '1'
mod_wsgi.script_start = '1496800659882898'
mod_wsgi.thread_id = 3
mod_wsgi.thread_requests = 24
mod_wsgi.total_requests = 73
mod_wsgi.version =
wsgi.errors = <_io.TextIOWrapper name='<wsgi.errors>' encoding='utf-8'>
wsgi.file_wrapper = ''
wsgi.input = <mod_wsgi.Input object at 0x7fe2b231e570>
wsgi.multiprocess = False
wsgi.multithread = True
wsgi.run_once = False
wsgi.url_scheme = 'http'
wsgi.version =

Model class social_django.models.UserSocialAuth doesn't declare an explicit app_label

Not sure if I am reading the documentation correctly, but after adding 'social.apps.django_app.default' to the installed apps I get this error when trying to migrate:

File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/user/git/venv/lib64/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "/home/user/git/venv/lib64/python3.5/site-packages/django/core/management/__init__.py", line 341, in execute
    django.setup()
  File "/home/user/git/venv/lib64/python3.5/site-packages/django/__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/user/git/venv/lib64/python3.5/site-packages/django/apps/registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "/home/user/git/venv/lib64/python3.5/site-packages/django/apps/config.py", line 199, in import_models
    self.models_module = import_module(models_module_name)
  File "/usr/lib64/python3.5/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 665, in exec_module
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "/home/user/git/venv/lib64/python3.5/site-packages/social/apps/django_app/default/models.py", line 1, in <module>
    from social_django.models import AbstractUserSocialAuth, UserSocialAuth, Nonce, Association, Code, DjangoStorage
  File "/home/user/git/venv/lib64/python3.5/site-packages/social_django/models.py", line 68, in <module>
    class UserSocialAuth(AbstractUserSocialAuth):
  File "/home/user/git/venv/lib64/python3.5/site-packages/django/db/models/base.py", line 113, in __new__
    "INSTALLED_APPS." % (module, name)
RuntimeError: Model class social_django.models.UserSocialAuth doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

Using:

  • Django 1.10.4
  • Python 3.5
  • social-auth-app-djang 0.1.0
  • social-auth-core 0.2.1

Exception on gmail login

Hi! I'm having the following exception when trying to login with gmail:

File "project/lib/python3.5/site-packages/social_django/fields.py" line 51 in to_python
ValidationError: ['Expecting property name enclosed in double quotes: line 1 column 2 (char 1)']

The value of the json response is '{\\"token_type\\": \\"Bearer\\", \\"access_toke...WVwbchW-i4gwE5-93rItgus\\", \\"expires\\": 3599}'

Thanks in advance!

the user who logined by python-social-auth can't access the page that is only logined user.(Django)

Any user who registers on my homepage directly can access the homepage (which requires the user to be logged in). But a user who registers with python-social-auth can log in, but can't @@access the homepage.

This is my settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'photo',
    'authentication',
    'social_django',
    'social.apps.django_app.default',
    'pipeline',
    'debug_toolbar',
]

MIDDLEWARE = [
    'django.contrib.sessions.middleware.SessionMiddleware',
    'social.apps.django_app.middleware.SocialAuthExceptionMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'social_django.middleware.SocialAuthExceptionMiddleware',
    'debug_toolbar.middleware.DebugToolbarMiddleware',

]
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'social.apps.django_app.context_processors.backends',
                'social.apps.django_app.context_processors.login_redirect',

            ],
        },
    },
]

AUTHENTICATION_BACKENDS = (
    'social.backends.kakao.KakaoOAuth2',
    'django.contrib.auth.backends.ModelBackend',
)


PIPELINE = {
    'PIPELINE_ENABLED': True,
    'JAVASCRIPT': {
        'stats': {
            'source_filenames': (
              'js/jquery.js',
              'js/d3.js',
              'js/collections/*.js',
              'js/application.js',
            ),
            'output_filename': 'js/stats.js',
        }
    }
}

SOCIAL_AUTH_PIPELINE = (
    'social.pipeline.social_auth.social_details',
    'social.pipeline.social_auth.social_uid',
    'social.pipeline.social_auth.auth_allowed',
    'social.pipeline.social_auth.social_user',
    'social.pipeline.user.get_username',
    'social.pipeline.user.user_details',
    'authentication.social.require_info',
    'social.pipeline.mail.mail_validation',
    'social.pipeline.social_auth.associate_by_email',
    'social.pipeline.user.create_user',
    'social.pipeline.social_auth.associate_user',
    'social.pipeline.social_auth.load_extra_data',

)

SOCIAL_AUTH_DISCONNECT_PIPELINE = (
    'social.pipeline.disconnect.allowed_to_disconnect',
    'social.pipeline.disconnect.get_entries',
    'social.pipeline.disconnect.revoke_tokens',
    'social.pipeline.disconnect.disconnect',
)

SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
SOCIAL_AUTH_KAKAO_KEY ='d3b5de655df7bbfc85916336a9c4a479'

SOCIAL_AUTH_KAKAO_SECRET = ''

SOCIAL_AUTH_ADMIN_USER_SEARCH_FIELDS = ['username', 'email']
SOCIAL_AUTH_SLUGIFY_USERNAMES = True

SOCIAL_AUTH_LOGIN_REDIRECT_URL ='/home'
SOCIAL_AUTH_LOGIN_URL ='/accounts.kakao.com/login'
SOCIAL_AUTH_URL_NAMESPACE = 'social'
SESSION_EXPIRE_AT_BROWSER_CLOSE = True

this is urls.py

#login
url(r'^accounts/login/$', auth_views.login, {'template_name':'registration/login.html', 'authentication_form': LoginForm}, name='login'),
url(r'^accounts/logout/$', auth_views.logout, {'next_page':'/accounts/login'}, name='logout'),
url('', include('social.apps.django_app.urls', namespace='social')),
url(r'^accounts/register/$', UserCreateView.as_view(), name='register'),
url(r'^accounts/getinfo/$', authentication_views.acquire_info, name='acquire_info'),
]

this is templates

<div class="container">
    <div class="center-form panel">
        <div class="panel-body">
            <h4 class="text-center"><i class="ion-log-in"></i>Log in</h4>

            <form method="post" action="{% url 'login' %}">
            {% csrf_token %}
                <div class="form-group has-feedback">
                <p>{{user.username}} 반갑습니다.</p>

                {{ form.username }}
                <span class="ion-person form-control-feedback"></span>
                </div>
                <div class="form-group has-feedback">
                {{ form.password }}
                    <span class="ion-key form-control-feedback"></span>
                </div> 

                <button type="submit" class="btn btn-block btn-success" value="login">Log in</button>

                <br />

                <p class="text-center text-muted">
                    <small>Don't have an account yet? <a href="{% url 'register' %}">Sign up</a></small>
                </p>

                <div class="signup-or-separator">
                    <h6 class="text">or</h6>
                    <hr>
                </div>
                <input type="hidden" name="next" value="{{next}}" />
            </form>
            <a href="{% url 'social:begin' backend='kakao' %}?next={{request.path}}" class="btn btn-block btn-kakao">
                카카오계정으로 로그인
            </a>
        </div>
 </div>
</div>   

Support for Chrome App OAuth2

I'm trying to use the chrome.identity api to authenticate within a chrome extension. The only way to use chrome.identity however, is to register a chrome app as opposed to a standard web application like this:
credentials_-_shakespeare-dev

Unfortunately this type of registration doesn't give you a client secret, which appears to be a requirement in the docs here.

oauth_client_-_shakespeare-dev

VS.

oauth_client_-_shakespeare-dev

Is it even possible to oauth2 without a client secret?

400 request error

I have this working in development, but when we move to production it breaks with the following:

args
(<social_core.backends.facebook.FacebookOAuth2 object at 0x80e3a3910>,)
err
HTTPError(u'400 Client Error: Bad Request for url: https://graph.facebook.com/v2.8/oauth/access_token?code=AQCbjbjU1gf0OgTp4cliPv4r0CNsB8BjZ2hdyvpREv8uK2sqydb3nMmaRBb_-mZ1VjpRSYyAvcAeXmB4mzq0FZYdsGRdqRP8RqeEhebw_O27xzzDcRhkpPmTanOTRkXC0JM5RfQWloC3F38UEHSSfMr2Kebze_Pfn1i5ZhNPEobZQIcpJTCcT19mvqZu2IzOWy6KtGgH8PixKZ9PQXt2e1ebYK4-_xcgNJ43PJK_qVliGua_N5VnZGiDOWUY3xxymZZc8m8Mr1Nk1qU5enSu2sNOcLS-saxvfNynmABJIP_jKfzRPAcspWcVX72jgZ4UjuA&client_secret=998984df8de85466cff9ea17d0c6e48b&redirect_uri=http%3A%2F%2Fwww.kinkbnb.com%2Fcomplete%2Ffacebook%2F%3Fredirect_state%3Don180Ub9p28DlVdkllwWAePGi2kph4qY&client_id=349131495278188',)
func
<function auth_complete at 0x80e16e398>
kwargs
{'user': None}

Why would this work in development and not production? Mind you, I'm not talking about localhost - I literally have it running on dev.mydomain.com but when we move to www.mydomain.com it breaks.

Unable to log into GitHub in same Tab on Firefox

Hi, in our project we have a django backend running on port 8000 and an angular 4 frontend that used to be served from the same django instance, but is now being served on port 4200.

In Firefox we are now unable to authenticate with GitHub via social-app-django when visiting the respective address localhost:8000/auth/login/github in the current tab. Navigating to that address in a new tab or via window.open(...) works fine. In chrome this does not pose a problem.

We are unsure about the cause of this, but suspect it might be a problem in social-app-django.

Our specific issue is further discussed here in the repo of our backend. You can find the frontend in progress here.

We are using Django: 1.9 and Python: 3.6.1

Thanks in advance!

Migrations failure

When applying the migrations from the new django specific app the following error is thrown.

Traceback (most recent call last):
  File "./manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/tim/.virtualenvs/api-kk/lib/python3.5/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line
    utility.execute()
  File "/home/tim/.virtualenvs/api-kk/lib/python3.5/site-packages/django/core/management/__init__.py", line 346, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/tim/.virtualenvs/api-kk/lib/python3.5/site-packages/django/core/management/base.py", line 394, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/tim/.virtualenvs/api-kk/lib/python3.5/site-packages/django/core/management/base.py", line 445, in execute
    output = self.handle(*args, **options)
  File "/home/tim/.virtualenvs/api-kk/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 93, in handle
    executor = MigrationExecutor(connection, self.migration_progress_callback)
  File "/home/tim/.virtualenvs/api-kk/lib/python3.5/site-packages/django/db/migrations/executor.py", line 19, in __init__
    self.loader = MigrationLoader(self.connection)
  File "/home/tim/.virtualenvs/api-kk/lib/python3.5/site-packages/django/db/migrations/loader.py", line 47, in __init__
    self.build_graph()
  File "/home/tim/.virtualenvs/api-kk/lib/python3.5/site-packages/django/db/migrations/loader.py", line 308, in build_graph
    _reraise_missing_dependency(migration, parent, e)
  File "/home/tim/.virtualenvs/api-kk/lib/python3.5/site-packages/django/db/migrations/loader.py", line 291, in _reraise_missing_dependency
    raise exc
  File "/home/tim/.virtualenvs/api-kk/lib/python3.5/site-packages/django/db/migrations/loader.py", line 301, in build_graph
    self.graph.add_dependency(migration, key, parent)
  File "/home/tim/.virtualenvs/api-kk/lib/python3.5/site-packages/django/db/migrations/graph.py", line 116, in add_dependency
    parent
django.db.migrations.graph.NodeNotFoundError: Migration social_django.0004_auto_20160423_0400 dependencies reference nonexistent parent node ('social_django', '0003_alter_email_max_length')

Backend for Azure Active Directory B2C

There's Azure service called AD B2C for IAM. The differences between Azure AD and Azure AD B2C are different API endpoints and request/response parameters. Therefore there's a necessity to develop new backend for this service.

Functionality to be developed is common: login, sign up, logout and token refresh.

Set JSONField's default to callable

Current implementation is kwargs.setdefault('default', {}).
This makes all the model instances share same object reference. So, updating one object's data effects all of the objects and will result in data corruption.
changing to kwargs.setdefault('default', dict) will fix the issue.

e-mail as username when using facebook not working

I have set SOCIAL_AUTH_USERNAME_IS_FULL_EMAIL = True in my settings, but still username for users registering via facebook have username FirstnameLastname. What should Ido to make the setting work?

KeyError in state_forwards During 0005_auto_20160727_2333.py Migration

When migrating from python-social-auth to the new Django-specific app, the following exception is being thrown when running migrations:

$ python manage.py migrate social_django
Operations to perform:
  Apply all migrations: social_django
Running migrations:
  Applying social_django.0005_auto_20160727_2333...Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/vagrant/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "/vagrant/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 359, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/vagrant/venv/lib/python3.4/site-packages/django/core/management/base.py", line 294, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/vagrant/venv/lib/python3.4/site-packages/django/core/management/base.py", line 345, in execute
    output = self.handle(*args, **options)
  File "/vagrant/venv/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 204, in handle
    fake_initial=fake_initial,
  File "/vagrant/venv/lib/python3.4/site-packages/django/db/migrations/executor.py", line 115, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/vagrant/venv/lib/python3.4/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/vagrant/venv/lib/python3.4/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/vagrant/venv/lib/python3.4/site-packages/django/db/migrations/migration.py", line 119, in apply
    operation.state_forwards(self.app_label, project_state)
  File "/vagrant/venv/lib/python3.4/site-packages/django/db/migrations/operations/models.py", line 521, in state_forwards
    model_state = state.models[app_label, self.name_lower]
KeyError: ('social_django', 'association')

Current state of the associated social_auth migrations and existing tables:

$ psql dev -c '\d' | grep social_auth
 public | social_auth_association                                         | table    | vagrant
 public | social_auth_association_id_seq                                  | sequence | vagrant
 public | social_auth_code                                                | table    | vagrant
 public | social_auth_code_id_seq                                         | sequence | vagrant
 public | social_auth_nonce                                               | table    | vagrant
 public | social_auth_nonce_id_seq                                        | sequence | vagrant
 public | social_auth_usersocialauth                                      | table    | vagrant
 public | social_auth_usersocialauth_id_seq                               | sequence | vagrant
$ psql dev -c "SELECT * FROM django_migrations WHERE app = 'social_auth'"
 id  |     app     |            name             |            applied
-----+-------------+-----------------------------+-------------------------------
 118 | social_auth | 0005_auto_20160727_2333     | 2016-08-15 15:41:28.565237+00
 119 | social_auth | 0003_alter_email_max_length | 2016-08-15 15:41:29.247433+00
 120 | social_auth | 0004_auto_20160423_0400     | 2016-08-15 15:41:29.249949+00
 121 | social_auth | 0001_initial                | 2016-08-15 15:41:29.251842+00
 122 | social_auth | 0002_add_related_name       | 2016-08-15 15:41:29.253419+00
(5 rows)

How to convert code to access_token

Hello! I do a REST API to authenticate via social networks.

If I login via /login/backend/ Backend-class will receive parameter code and make a request to ACCESS_TOKEN_URL to get the access_token. Normal behavior for the Authorization Code Flow.

But in the FAQ you propose to use request.backend.do_auth(access_token) for the REST API. But I have no access_token! My client has only code! How do I convert a code in the access_token using the methods of class request.backend?

Conflicting migrations detected

Using 1bbc42d (*) I'm getting

$ python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).

You have 1 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): social_django.
Run 'python manage.py migrate' to apply them.
...
$ python manage.py migrate
CommandError: Conflicting migrations detected; multiple leaf nodes in the migration graph: (0004_auto_20160423_0400, 0006_partial in social_django).
To fix them run 'python manage.py makemigrations --merge'
$ python manage.py makemigrations --merge
No conflicts detected to merge.

The content of social_django/migrations/0004_auto_20160423_0400.py is

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models

from ..fields import JSONField


class Migration(migrations.Migration):
    replaces = [
        ('default', '0004_auto_20160423_0400'),
        ('social_auth', '0004_auto_20160423_0400')
    ]

    dependencies = [
        ('social_django', '0003_alter_email_max_length'),
    ]

    operations = [
        migrations.AlterField(
            model_name='usersocialauth',
            name='extra_data',
            field=JSONField(default={}),
        )
    ]

and the content of social_django/migrations/0006_partial.py is

# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-02 11:54
from __future__ import unicode_literals

from django.db import migrations, models
import social_django.fields
import social_django.storage


class Migration(migrations.Migration):

    dependencies = [
        ('social_django', '0005_auto_20160727_2333'),
    ]

    operations = [
        migrations.CreateModel(
            name='Partial',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('token', models.CharField(db_index=True, max_length=32)),
                ('next_step', models.PositiveSmallIntegerField(default=0)),
                ('backend', models.CharField(max_length=32)),
                ('data', social_django.fields.JSONField(default={})),
            ],
            options={
                'db_table': 'social_auth_partial',
            },
            bases=(models.Model, social_django.storage.DjangoPartialMixin),
        ),
    ]

(*) I'm actually using 1832fa7 that is the pull request that I sent.

KeyError with non ascii username on django 1.8

Traceback : https://travis-ci.org/zestedesavoir/zds-site/jobs/238820914#L1041

Url in traceback : http://localhost:8000/membres/connexion/?next=/membres/voir/%C3%AF%C3%A9%C3%A0%C3%A7%C3%8A%C3%803/

Pseudo in traceback : ïéàçÊÀ3

Source code : https://github.com/gustavi/zds-site/tree/6f30616cfb49992455dd5f7ad03d5db8e9cc324b (from zestedesavoir/zds-site#4357)

Versions :

python==2.7 (archlinux compiled from source)
django==1.8.18
social-auth-app-django==1.2.0
social-auth-core==1.3.0

Note : I have a patch but I try to make a test that fail on actual master to fix it.

Feature: Configure maximum session length

Currently, some backends can provide an expiration length on the identity that they provide. However, others do not, and by default, the sessions produced by these providers will be equal to the Django platform default (2 weeks, if no other settings are made).

In some cases, it may be desirable to restrict SSO login users to a shorter session length, or even set their sessions to expire on browser close. The pull request accompanying this issue adds a setting that can be checked to determine the maximum length of session that should be set up for the incoming user (setting this variable to 0 will set a session cookie that will be discarded on browser close).

Return from partial pipeline crashing in Django 1.11

social-auth-app-django==1.1.0
social-auth-core==1.3.0
Django==1.11
Python 3.4

After successfully pausing the auth pipeline, and asking the user to provide an email, when I redirect to /complete/backend/ django crashes with "clean_authenticate_args() got multiple values for argument 'request'".

After some debug, I found that Django is adding the 'request' in the 'args' argument, and psa is also adding the 'request' in the 'kwargs' argument when it loads the partial object. So when the method clean_authenticate_args is called, the argument 'request' is provided twice.

Migration failure

Migrating from python-social-auth to social-core / social-django,

$ docker-compose exec web python manage.py migrate
Traceback (most recent call last):
  File "manage.py", line 9, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 377, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 338, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 63, in handle
    executor = MigrationExecutor(connection, self.migration_progress_callback)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 17, in __init__
    self.loader = MigrationLoader(self.connection)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/loader.py", line 48, in __init__
    self.build_graph()
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/loader.py", line 233, in build_graph
    self.graph.add_dependency(migration, key, parent)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/graph.py", line 42, in add_dependency
    raise KeyError("Migration %s dependencies reference nonexistent parent node %r" % (migration, parent))
KeyError: u"Migration social_django.0002_add_related_name dependencies reference nonexistent parent node (u'social_django', u'0001_initial')"

New method in AbstractUserSocialAuth

New method suggestion for AbstractUserSocialAuth.

Objective: Get an always updated access_token easily.

Something like this:

 from social_django.utils import load_strategy
 ...
@classmethod
def get_access_token(cls, provider, uid):
    if (cls.extra_data['auth_time'] + cls.extra_data['expires_in']) <= int(time.time()):
        strategy = load_strategy()
        social.refresh_token(strategy)
    return self.extra_data['access_token']

I haven't tested it, nor think about exceptions, but I can do it and do fork request. Do you agree with adding this method?

python manage.py migrate failed

Operations to perform:
Apply all migrations: admin, app_search, auth, captcha, contenttypes, sessions, social_django
Running migrations:
Applying social_django.0005_auto_20160727_2333...Traceback (most recent call last):
File "manage.py", line 10, in
execute_from_command_line(sys.argv)
File "C:\Python27\lib\site-packages\django\core\management_init_.py", line 367, in execute_from_command_line
utility.execute()
File "C:\Python27\lib\site-packages\django\core\management_init_.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python27\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Python27\lib\site-packages\django\core\management\base.py", line 345, in execute
output = self.handle(*args, **options)
File "C:\Python27\lib\site-packages\django\core\management\commands\migrate.py", line 204, in handle
fake_initial=fake_initial,
File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 115, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 145, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "C:\Python27\lib\site-packages\django\db\migrations\migration.py", line 129, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "C:\Python27\lib\site-packages\django\db\migrations\operations\models.py", line 532, in database_forwards
getattr(new_model._meta, self.option_name, set()),
File "C:\Python27\lib\site-packages\django\db\backends\base\schema.py", line 333, in alter_unique_together
self.execute(self._create_unique_sql(model, columns))
File "C:\Python27\lib\site-packages\django\db\backends\base\schema.py", line 112, in execute
cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\utils.py", line 94, in exit
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\mysql\base.py", line 110, in execute
return self.cursor.execute(query, args)
File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 201, in execute
self.errorhandler(self, exc, value)
File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
django.db.utils.OperationalError: (1071, 'Specified key was too long; max key length is 1000 bytes')

Django crash

I am getting this error while doing social authentication with facebook

TypeError at /social-auth/complete/facebook/
unsupported operand type(s) for +: 'NoneType' and 'int'
Request Method: GET
Request URL: http://mysite.com:8000/social-auth/complete/facebook/?redirect_state=TAQXEiEM8ybAubXtpIaNWj2OVNkGvOIH&code=AQCKcmP7l_ac1XW6iOTxp3I8PtiQeVeUE7tS8hJDroWZIq4kv6G9PM5M-TQ69XPKVCSMFsAOUpYp_uuXaCONsaVhhbWwQRdcp4iJCV5Y3EbJlr53uPzx1OsQgNJz0B8Oigv1w922ME0NpAt1EEL8CXGzAPDy1bELFNOC8bmfPIGU8lh06EDp1vSg1vYy3cxC_6e1ZZp8yiyrgqTHhC9yG1WTG6WeXSQUlHrnQimF5ha6U46ZEEVwFd7sKTEZPVkhzx9ZLATIEralQvrvD1PMi0LHh3p9o2Pf3d1v9SnXI7QCmp1zsLDfOzaM_hIxbFS69ZkpY76uWCZB0GpAryXCscdMCyA62eagGY2synbdn01Puw&state=TAQXEiEM8ybAubXtpIaNWj2OVNkGvOIH
Django Version: 1.11.2
Exception Type: TypeError
Exception Value:
unsupported operand type(s) for +: 'NoneType' and 'int'
Exception Location: C:\Python34\lib\site-packages\social\backends\base.py in run_pipeline, line 110
Python Executable: C:\Python34\python.exe
Python Version: 3.4.3
Python Path:
['C:\Users\bvsr\PycharmProjects\bookmarks',
'C:\Users\bvsr\PycharmProjects\bookmarks',
'C:\WINDOWS\SYSTEM32\python34.zip',
'C:\Python34\DLLs',
'C:\Python34\lib',
'C:\Python34',
'C:\Python34\lib\site-packages']
Server time: Tue, 27 Jun 2017 22:53:02 +0000
capture

Migration error when calling runserver after upgrade from PSA

Got this error when trying to upgrade from python-social-auth, when running runserver:

django.db.migrations.graph.NodeNotFoundError: Migration social_django.0005_auto_20160727_2333 dependencies reference nonexistent parent node (u'social_django', u'0004_auto_20160423_0400')

As far as I can see, there is a migration social_django/migrations/0004_auto_20160423_0400.py, so not sure yet of the problem.

I am running Django 1.8.17.

ImportError: cannot import name Facebook2OAuth2

I've upgraded to social-app-django. I'm getting this ImportError on trying to log in using any social service. Here's the traceback:

File "/home/sourav/myapp/venv/local/lib/python2.7/site-packages/social_core/backends/utils.py", line 35, in load_backends
backend = module_member(auth_backend)
File "/home/sourav/myapp/venv/local/lib/python2.7/site-packages/social_core/utils.py", line 59, in module_member
module = import_module(mod)
File "/home/sourav/myapp/venv/local/lib/python2.7/site-packages/social_core/utils.py", line 53, in import_module
__import__(name)
File "/home/sourav/myapp/venv/local/lib/python2.7/site-packages/social/backends/facebook.py", line 1, in <module>
from social_core.backends.facebook import FacebookOAuth2, FacebookAppOAuth2, \ ImportError: cannot import name Facebook2OAuth2

docs for saml instructions have old path .. apps.django_app.utils import load_strategy, load_backend

I posted an issue here about an import error for strategy. I first made the s uppercase to allow the import, but I think this is likely just an outdated docs, and can be fixed by changing the line to:

from social_django.utils import load_strategy, load_backend

instead of:

from social.apps.django_app.utils import load_strategy, load_backend

the instructions I was reading are here and the reason I did the second for import is because it was in the saml.py backend code. Is this the correct approach?

Google OAuth2 fails with Django 1.11

Hello,

while trying to upgrade to the last version of Django, I encountered this error.
I only use Google OAuth2, it works well with Python 3.5.2 and Django 1.10.2.

Here are some infos about the exception thrown :

TypeError at /complete/google-oauth2/
unsupported operand type(s) for +: 'NoneType' and 'int'

Django Version: 	1.11
Exception Type: 	TypeError
Exception Value: 	unsupported operand type(s) for +: 'NoneType' and 'int'
Exception Location: 	/opt/local/lib/python3.5/site-packages/social_core/backends/base.py in run_pipeline, line 105
Python Executable: 	/usr/bin/python3
Python Version: 	3.5.2

social_core/backends/base.py:105

for idx, name in enumerate(pipeline[pipeline_index:]):
    out['pipeline_index'] = pipeline_index + idx     # Here, values : None + 0
    func = module_member(name)
    result = func(*args, **out) or {}
    if not isinstance(result, dict):
        return result
    out.update(result)
return out

Tell me if you need more infos.
Thanks

Custom pipeline or extend user model

Hi,

I am implementing social-app-django with django 1.11 (not using Mongo). My application will need to store and manipulate a lot of data on users other than that which is fetched from their social media accounts at login. I don't need to fetch or collect any extra data when the user authenticates, but various actions they perform on my site will need to be saved to their user. I am wondering which of the following approaches is preferred (I've searched extensively online, but can't find a specific explanation of the differences):

  • Create my own user model in my app's models.py (call it MyUser) that doesn't extend anything special, and then add a function in the authentication pipeline that associates the social-app-django user with a corresponding instance of MyUser. or...

  • Create my own user model in my app's models.py, and in the project's settings.py set AUTH_USER_MODEL and SOCIAL_AUTH_USER_MODEL to point to MyUser. In this case, I was wondering whether someone could clarify what MyUser and its manager should extend, and what I need to import in modules.py (I am confused because a lot of stack overflow posts are referring to deprecated versions of this module and I keep getting errors). Also, in this case should I be setting both AUTH_USER_MODEL and SOCIAL_AUTH_USER_MODEL, or just one of them?

Do these two methods essentially achieve the same thing? Is one more reliable/preferred for some reason? Or, should I be doing both? Thanks very much for any assistance.

Oh, and one more thing--I would like to be able to access the User database not only from the app I am currently building, but also from other apps (within the same Django project) that I will build in the future. Does this affect anything?

Crashes with Django 1.11

With Django 1.11 you get following crash:

  File "/home/nijel/work/weblate/django/contrib/auth/__init__.py", line 86, in authenticate
    user = backend.authenticate(*args, **credentials)
  File "/home/nijel/work/weblate/social_core/backends/base.py", line 78, in authenticate
    return self.pipeline(pipeline, *args, **kwargs)
  File "/home/nijel/work/weblate/social_core/backends/base.py", line 81, in pipeline
    out = self.run_pipeline(pipeline, pipeline_index, *args, **kwargs)
  File "/home/nijel/work/weblate/social_core/backends/base.py", line 104, in run_pipeline
    out['pipeline_index'] = pipeline_index + idx
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

The problem is that Django now adds positional request parameter to authenticate call and social auth accepts it as pipeline, see Django code for more details how it is done: https://github.com/django/django/blob/stable/1.11.x/django/contrib/auth/__init__.py#L69

Migration broken from 0.2.19 (and older)

This is followup for #16.

With #25 the migration from 0.2.20 and 0.2.21 is working fine, however users upgrading from 0.2.19 and older will still end up with error.

It can end up with error described in #16:

KeyError: u"Migration social_django.0002_add_related_name dependencies reference nonexistent parent node (u'social_django', u'0001_initial')"

Or it can pop up as error while validating relations (see WeblateOrg/weblate#1344):

ValueError: The field accounts.VerifiedEmail.social was declared with a lazy reference to 'social_django.usersocialauth', but app 'social_django' isn't installed.

The problem is that Django does not see the old migrations as they are just half applied (due to missing social_auth ones):

manage.py showmigrations
...
social_django
 [ ] 0005_auto_20160727_2333 (1 squashed migrations)
 [ ] 0006_partial
...

This is what is stored in the database:

id app name applied
70 default 0001_initial 2017-02-01 15:03:35.625824
112 default 0002_add_related_name 2017-02-01 15:03:41.684870
113 default 0003_alter_email_max_length 2017-02-01 15:03:41.739056
114 default 0004_auto_20160423_0400 2017-02-01 15:03:41.877357

``expires_in`` and OAuth2 RFC

Hello,

OAuth2 RFC provides the following information on the successful response:

  • access_token (REQUIRED)
  • token_type (REQUIRED)
  • expires_in (RECOMMENDED; The lifetime in seconds of the access token. If omitted, the authorization server SHOULD provide the expiration time via other means or document the default value.)
  • refresh_token(OPTIONAL)
  • scope (OPTIONAL, if identical to the scope requested by the client; otherwise, REQUIRED.)

Having this in mind some parameters could be common in the extra data for OAuth2:

  • access_token
  • token_type
  • expires_in

Having this in mind I I purpose that in BaseOAuth2 we start having something like this: EXPIRES_IN_KEY = 'expires_in' and EXPIRES_IN_DEFAULT = None.

This can be used in extra_data() to save the lifetime in seconds of the access token complementing the auth_time and making it possible to use access_token expired() at all times (for OAuth2).

PS: Is there any reason why currently the expires_in is expire in most backends and also the name used for expiration_timedelta()?
In my opinion, this method should be changed from expires to expires_in to comply with the RFC and backward compatible assured.

This discussion started in StackOverflow and I think it should be continued here.

Cannot import name engines

I'm now encountering an error, it says ImportError at /
cannot import name engines
it traced back to /lib/python2.7/site-packages/social_django/strategy.py in this line
from django.template import TemplateDoesNotExist, RequestContext, loader, engines

Social Django Related Model Migration Error

Im migrating a django 1.10 app from PSA==0.3.5 to social-auth-app-django==1.0.0 +
social-auth-core==1.0.1 and am running into some migration issues on a related table.

While applying this migration:

class Migration(migrations.Migration):

    dependencies = [
        ('social_django', '0006_partial'),
        ('accounts', '0041_merge_20170105_1912'),
    ]

    operations = [
        migrations.CreateModel(
            name='SocialAuthExpiration',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('updated_at', models.DateTimeField(auto_now=True)),
                ('expires_at', models.DateTimeField()),
                ('refresh_failed', models.NullBooleanField()),
                ('social_auth', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='token_expiration', to='social_django.UserSocialAuth')),
            ],
            managers=[
                ('expirations', django.db.models.manager.Manager()),
            ],
        ),
    ]

For this model:

class SocialAuthExpiration(models.Model):
    social_auth = models.OneToOneField(
        UserSocialAuth,
        on_delete=models.CASCADE,
        related_name='token_expiration'
    )
    ...

Im encountering this error:
ValueError: Related model u'social_django.UserSocialAuth' cannot be resolved

Social Django is installed. Plus I'm able to create new UserSocialAuth objects. I've attempted changing the to field to 'social.UserSocialAuth' as well, to no avail.

INSTALLED_APPS = [
    ...
    # Social Auth
    'social_django',
    # Local dev utils/runserver
    'django_extensions',
    # Hueya Apps
    'accounts', <<< New model and migration live here
    ...
]

django_migrations table relevant rows:

124 | social_auth   | 0005_auto_20160727_2333                  | 2016-12-21 15:40:36.562573+00
 125 | social_auth   | 0001_initial                                            | 2016-12-21 15:40:36.567864+00
 126 | social_auth   | 0003_alter_email_max_length              | 2016-12-21 15:40:36.571+00
 127 | social_auth   | 0004_auto_20160423_0400                | 2016-12-21 15:40:36.57382+00
 128 | social_auth   | 0002_add_related_name                      | 2016-12-21 15:40:36.576405+00
 146 | social_django | 0006_partial                                        | 2017-01-28 19:05:27.811943+00

Im hoping someone has had some experience with this and might be able to point me in the right direction. Thanks.

Allow For Configuration of Redirect URI

Subtitle: Don't build redirect_uri based on current URL if x is set

This MIGHT be a no-op, but after a few hours of poking I couldn't find a solution in the current config. I might just be dense about Django internals; if so, I apologize.

Scenario

Nginx proxy/static resource server (docker container: my_proxy)
Django app in the backend configured (docker app: my_portal)

When a user hits "awesome.example.com/login/github", my_proxy receives it and relays it to the my_portal. The Django app then redirects over to Github for the authentication flow, but it uses the url name it sees on the HTTP request from the proxy: http://my_portal/complete/github/redirect_state/....

Obviously Github doesn't handle this well after I authenticate on their end, when it redirects back to my top-level domain,with this value I get a redirect_uri error:

Authentication failed: The redirect_uri MUST match the registered callback URL for this application.

Work Around

To work around this I think I can rewriting the headers on the proxy from Nginx to use the top-level domain host that I'm working on (i.e. forwarding awesome.example.com to my_portal instead of addressing it as my_portal). But I believe this prevents (or at least increasingly restricts) me from spinning up multiple Django app backends to serve the application.

Ask

Being able to name my application servers whatever internal name I want, but configure the redirection URL would allow me to keep.

The idea that I think works is allowing the hostname to be overwritten by a setting in Django. I'm bad at naming such things, but SOCIAL_APP_FQDN or REDIRECTION_BASE_URL would let me configure the plugin to generate redirect_uri values that match my app domain, rather than a container host or internal server IP/FQDN.

Alternatives

The answer could very well be "this overcomplicates the social stack" or "nobody does it the way you're describing you madperson". If anyone has any guidance or feedback here that I could work into some documentation I would appreciate it!

KeyError: 'partial_pipeline'

Hi, i've updated form python social auth to social app Django, but i have a problem with custom partial pipeline when it redirecting to complete url:

backend = self.request.session['partial_pipeline']['backend']
return redirect(reverse('social:complete', args=[backend]))

this raises: KeyError: 'partial_pipeline'

how i solve this?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.