omab / python-social-auth Goto Github PK
View Code? Open in Web Editor NEWSocial auth made simple
Home Page: http://psa.matiasaguirre.net
License: BSD 3-Clause "New" or "Revised" License
Social auth made simple
Home Page: http://psa.matiasaguirre.net
License: BSD 3-Clause "New" or "Revised" License
I have the following pipeline settings
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.create_user',
'social.pipeline.social_auth.associate_user',
'social.pipeline.social_auth.associate_by_email',
'social.pipeline.social_auth.load_extra_data',
'social.pipeline.user.user_details'
)
I have the email address as [email protected] as registered and i have the google plus account as [email protected].
When i log out and try to signup with google plus account, it creates a new account with same email address even 'social.pipeline.social_auth.associate_by_email'
is added. Any ideas?
The fix to #76 isn't correct. It causes another error when you have an expired association:
python-social-auth/social/store.py
Lines 43 to 48 in 8b58942
for assoc_id, association in self.assoc.oids(server_url, handle):
expires = self.expiresIn(association)
if expires > 0:
associations.append(association)
elif expires == 0:
expired.append(association.id)
The last line here assumes association
is an Association
(Django model), but it's not. It's an OpenIdAssociation
, and therefore has no id
member.
expired.append(association.id)
should be:
expired.append(assoc_id)
Traceback:
File "/Users/kbussell/.virtualenvs/tcdc/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/kbussell/.virtualenvs/tcdc/lib/python2.7/site-packages/social/apps/django_app/utils.py" in wrapper
32. return func(request, backend, *args, **kwargs)
File "/Users/kbussell/.virtualenvs/tcdc/lib/python2.7/site-packages/social/apps/django_app/views.py" in auth
12. return do_auth(request.strategy, redirect_name=REDIRECT_FIELD_NAME)
File "/Users/kbussell/.virtualenvs/tcdc/lib/python2.7/site-packages/social/actions.py" in do_auth
25. return strategy.start()
File "/Users/kbussell/.virtualenvs/tcdc/lib/python2.7/site-packages/social/strategies/base.py" in start
56. if self.backend.uses_redirect():
File "/Users/kbussell/.virtualenvs/tcdc/lib/python2.7/site-packages/social/backends/open_id.py" in uses_redirect
215. return self.openid_request().shouldSendRedirect()
File "/Users/kbussell/.virtualenvs/tcdc/lib/python2.7/site-packages/social/backends/open_id.py" in openid_request
221. params))
File "/Users/kbussell/.virtualenvs/tcdc/lib/python2.7/site-packages/openid/consumer/consumer.py" in begin
353. return self.beginWithoutDiscovery(service, anonymous)
File "/Users/kbussell/.virtualenvs/tcdc/lib/python2.7/site-packages/openid/consumer/consumer.py" in beginWithoutDiscovery
376. auth_req = self.consumer.begin(service)
File "/Users/kbussell/.virtualenvs/tcdc/lib/python2.7/site-packages/openid/consumer/consumer.py" in begin
598. assoc = self._getAssociation(service_endpoint)
File "/Users/kbussell/.virtualenvs/tcdc/lib/python2.7/site-packages/openid/consumer/consumer.py" in _getAssociation
1158. assoc = self.store.getAssociation(endpoint.server_url)
File "/Users/kbussell/.virtualenvs/tcdc/lib/python2.7/site-packages/social/store.py" in getAssociation
48. expired.append(association.id)
Exception Type: AttributeError at /user/login/yahoo/
Exception Value: 'Association' object has no attribute 'id'
Doesn't work without ACCESS_TOKEN_METHOD = 'POST' in social.backends.odnoklassniki.OdnoklassnikiOAuth2 . This is mentioned in their docs as well (http://apiok.ru/wiki/pages/viewpage.action?pageId=12878032)
There's a lot of coupling in the classes, specially strategy and backend, this needs to be reduced.
Hi, I got the problem when using weibo backend in Django 1.4.5
I configured like this(Already created a web app in weibo developer site sae.sina.com.cn
)
in settings.py
WEIBO_CLIENT_KEY=""
WEIBO_CLIENT_SECRET=""
AUTHENTICATION_BACKENDS = (
'social.backends.weibo.WeiboOAuth2',
'django.contrib.auth.backends.ModelBackend',
)
and edit a template home.html
with this code:
{% load url from future %}
<a href="{% url 'social:begin' "weibo" %}">Weibo Login</a> <br />
views.py
def loginTest(request):
if request.user.is_authenticated():
return redirect('done')
return render_to_response('home.html', {
'client_id': getattr(settings, 'WEIBO_CLIENT_KEY', None),
'user': request.user,
},
RequestContext(request))
it generate a url http://127.0.0.1:8000/login/weibo/
click it , will redirect to
https://api.weibo.com/oauth2/authorize?state=msHi0CsZbiAYjJGIo8ALBXYAEZ5NjWQ9&redirect_uri=http://127.0.0.1:8000/complete/weibo/&response_type=code&client_id=None
the problem is the Parameter client_id=None , it surpose to be client_id={WEIBO_CLIENT_KEY}, but it just failed to pass to the GET request here.
When I try to setup the library with the mongoengine it fails with a ImportError: No module named auth
.
I have explained the problem in stackoverflow, here .
Is it a compatibility bug or have I missed something? Thanks
I have a web client (Javascript) that authenticates users with G+ and Facebook. The client then needs to authenticate with a REST API implemented with django-rest-framework. I have seen the previous discussions implementing this with dsa. But could not get this working with psa. Do you have any pointers?
I recently upgraded from django-social-auth to python-social-auth (version 0.1.12) and a bit of code that had worked before is no longer working. I've got a model that points to UserSocialAuth or one of my own custom models through a generic FK, and it throws an error when I try to access it.
Here is the traceback I get (and please let me know if there's any other information I could provide that would be helpful):
Traceback (most recent call last):
File "/var/venvs/project_name/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/var/venvs/project_name/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 25, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/var/venvs/project_name/local/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/var/venvs/project_name/local/lib/python2.7/site-packages/django/views/generic/base.py", line 86, in dispatch
return handler(request, *args, **kwargs)
File "/var/venvs/project_name/local/lib/python2.7/site-packages/django/views/generic/edit.py", line 218, in get
return super(BaseUpdateView, self).get(request, *args, **kwargs)
File "/var/venvs/project_name/local/lib/python2.7/site-packages/django/views/generic/edit.py", line 154, in get
form = self.get_form(form_class)
File "/var/sites/project_name/project_name/user_settings/views.py", line 102, in get_form
return form_class(self.request.user, **self.get_form_kwargs())
File "/var/sites/project_name/project_name/user_settings/forms.py", line 75, in __init__
if user.fb_account:
File "/var/venvs/project_name/local/lib/python2.7/site-packages/django/utils/functional.py", line 205, in inner
return func(self._wrapped, *args)
File "/var/venvs/project_name/local/lib/python2.7/site-packages/django/contrib/contenttypes/generic.py", line 124, in __get__
ct = self.get_content_type(id=ct_id, using=instance._state.db)
File "/var/venvs/project_name/local/lib/python2.7/site-packages/django/contrib/contenttypes/generic.py", line 60, in get_content_type
return ContentType.objects.db_manager(using).get_for_id(id)
File "/var/venvs/project_name/local/lib/python2.7/site-packages/django/contrib/contenttypes/models.py", line 107, in get_for_id
self._add_to_cache(self.db, ct)
File "/var/venvs/project_name/local/lib/python2.7/site-packages/django/contrib/contenttypes/models.py", line 122, in _add_to_cache
key = (model._meta.app_label, model._meta.object_name.lower())
AttributeError: 'NoneType' object has no attribute '_meta'
The documentation (http://psa.matiasaguirre.net/docs/html/backends/google.html) refers to a parameter, SOCIAL_AUTH_GOOGLE_OAUTH2_EXTRA_SCOPE, that can be set (for example to ['https://mail.google.com'] to extend the default authorisation scope.
SOCIAL_AUTH_GOOGLE_OAUTH2_EXTRA_SCOPE does not appear to be utilised by backend/google.py at all and setting it has no effect on the scope.
Setting SOCIAL_AUTH_GOOGLE_SCOPE = ['https://mail.google.com'] does extend the scope.
I had a question, How to store the facebook profile picture of a user while logging in through facebook.
I found this link which says how to do so using django-social-app, https://gist.github.com/kalamhavij/1662930.
How can I do the same using python-social-app ??
I'm building a django application where I want users to be able to log in with their google accounts, do stuff, and logout. I am not wanting to keep data or anything like that, so I overrode the default disconnect pipeline and just removed the 'social.pipeline.disconnect.allowed_to_disconnect' check so that they would be able to disconnect without having any other information in the db (like a password). I modified the example app you provide to test this functionality but ran into a snag. When I click disconnect, it does not actually disconnect the user and still says "You are logged in as [username]." Here is some data for you.
[27/Sep/2013 09:17:56] "GET /login/google-oauth2/ HTTP/1.1" 302 0
[27/Sep/2013 09:17:57] "GET /complete/google-oauth2/?state=2elSzt1mWspvP9MuUc6mFAuzSarns0j5&code=4/RvBkG11KwhtQr9X_qOGqeGW1iSOe.Qur7pBQX2wAWmmS0T3UFEsO6zJG_ggI HTTP/1.1" 302 0
[27/Sep/2013 09:17:57] "GET /done/ HTTP/1.1" 200 1208
[27/Sep/2013 09:18:06] "POST /disconnect/google-oauth2/1/ HTTP/1.1" 302 0
[27/Sep/2013 09:18:06] "GET /done/ HTTP/1.1" 200 1169
If you need any more info, or if I am just doing something wrong, please let me know! Thanks!
thinking maybe this needs to change from:
class UserSocialAuth(Document, DjangoUserMixin):
"""Social Auth association model"""
user = ReferenceField(USER_MODEL, dbref=True)
provider = StringField(max_length=32)
uid = StringField(max_length=255, unique_with='provider')
extra_data = DictField()
to:
class UserSocialAuth(Document, DjangoUserMixin):
"""Social Auth association model"""
user = ReferenceField(USER_MODEL)
provider = StringField(max_length=32)
uid = StringField(max_length=255, unique_with='provider')
extra_data = DictField()
How do I refresh token?
Writing old django-social-auth style
user = User.objects.get(...)
social = user.social_auth.filter(provider='google-oauth2')[0]
social.refresh_token()
but,
<type 'exceptions.TypeError'> refresh_token() takes at least 2 arguments (1 given)
at /social/storage/base/UserMixin.refresh_token()
How do I get strategy param?
Sorry, but I have really strong integration of this plugin with my project, and I've been struggling with this problem and i can't found the solution.
TypeError at /complete/facebook/
datetime.datetime(2013, 11, 19, 8, 1, 8, 318871, tzinfo=<UTC>) is not JSON serializable
Request Method: GET
Request URL: (url)/complete/facebook/?redirect_state=(long param)
Django Version: 1.5.4
Exception Type: TypeError
Exception Value:
datetime.datetime(2013, 11, 19, 8, 1, 8, 318871, tzinfo=<UTC>) is not JSON serializable
Exception Location: (path)/python/lib/python2.7/json/encoder.py in default, line 178
-----EDIT
I think it might be a problem with the redirect, in facebook app there is a other different a /complete/facebook/ maybe it ignores it for some reason
Thanks
w/ the following configuration, first, last, and email are showing up in the mongoengine user documents but not in the user_social_auth documents
SOCIAL_AUTH_LINKEDIN_OAUTH2_SCOPE = ['r_fullprofile', 'r_emailaddress', 'rw_nus']
SOCIAL_AUTH_LINKEDIN_OAUTH2_FIELD_SELECTORS = ['summary', 'positions', 'email-address', 'headline', 'industry', 'educations']
SOCIAL_AUTH_LINKEDIN_OAUTH2_EXTRA_DATA = [('id', 'id'),
('first-name', 'first_name'),
('last-name', 'last_name'),
('summary', 'summary'),
('email-address', 'email-address'),
('headline', 'headline'),
('positions', 'positions'),
('industry', 'industry'),
('educations', 'educations')]
All of the data is captured, I just would have expected the email, first, and last name to be captured in both places (user and user_social_auth).
rs0:PRIMARY> db.user_social_auth.find({user: ObjectId('5222bf9ec64c8c9629cce5cd')}).pretty()
{
"_id" : ObjectId("5222bf9ec64c8c9629cce5ce"),
"extra_data" : {
"email-address" : null,
"last_name" : null,
"industry" : "Internet",
"first_name" : null,
"headline" : "PaaS Evangelist",
"id" : "ZURjBbzFZH"
},
"provider" : "linkedin-oauth2",
"uid" : "ZURjBbzFZH",
"user" : ObjectId("5222bf9ec64c8c9629cce5cd")
}
The corresponding User:
{
"cls" : "User",
"id" : ObjectId("5222bf9ec64c8c9629cce5cd"),
"date_joined" : ISODate("2013-09-01T04:16:30.637Z"),
"email" : "dblad**oo.com",
"first_name" : "D__id",
"is_active" : true,
"is_staff" : false,
"is_superuser" : false,
"last_login" : ISODate("2013-09-20T16:09:29.834Z"),
"last_name" : "Bl__o",
"password" : *__,
"username" : "Da***ado"
}
I can't use with django, check the error when I try to use a fresh installation:
When I try to run ./manage.py:
https://dpaste.de/O6j0
Sorry because it could be a dumb question.
Anyway,
Thx!
Hi,
I have settings:
SOCIAL_AUTH_LINKEDIN_SCOPE = ['r_basicprofile', 'r_emailaddress',]
SOCIAL_AUTH_LINKEDIN_FIELD_SELECTORS = ['email-address', 'headline', 'industry', 'picture-url']
SOCIAL_AUTH_LINKEDIN_EXTRA_DATA = [('id', 'id'),
('first-name', 'first_name'),
('last-name', 'last_name'),
('email-address', 'email_address'),
('picture-url', 'picture_url'),
('headline', 'headline'),
('industry', 'industry'),]
The linkedIn login works fine and I see the correct permissions scope on the linkedIn login dialogue.
When I look in the database post logging in my extra_data contains:
{"first_name": null, "last_name": null, "access_token": {"oauth_token_secret": "xxxxxxxxxxx", "oauth_authorization_expires_in": "5183999", "oauth_token": "xxxxxxxxxxx", "oauth_expires_in": "5183999"}, "industry": "Computer Software", "picture_url": null, "headline": "Co-Founder at Bought By Many", "email_address": null, "id": "N_Nd_fVZMB"}
As you can see most fields are null except industry and headline.
Thanks, Guy.
In order to get my app to work with github I need to set the callback url to:
http:///complete/github/
Currently the docs only say:
Register a new application at GitHub Developers, set your site domain as the callback URL or it might cause some troubles when associating accounts,
I think it should read
Register a new application at GitHub Developers, setting the callback URL to "http:///complete/github/".
If this seems like the right idea I'll be happy to do the work.
I have a custom model where I use email as the unique identification. When I have created a user with the email address [email protected] and then register a new user with the facebook social backend I get a dupicate entry error.
As I recall using the older django-social-auth 7.28 the existing user got updated. Now this doesn't happen, and it doesn't matter if I use username or email as the identification. I get the error.
If you need some more info please ask me.
(1062, "Duplicate entry '[email protected]' for key 'email'")
Here is the traceback
[22/Oct/2013 11:41:39] "GET /login/facebook/ HTTP/1.1" 302 0
Internal Server Error: /complete/facebook/
Traceback (most recent call last):
File "/Users/marinopallvaldimarsson/.virtualenvs/gracipe/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/Users/marinopallvaldimarsson/.virtualenvs/gracipe/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 77, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/marinopallvaldimarsson/.virtualenvs/gracipe/lib/python2.7/site-packages/social/apps/django_app/utils.py", line 32, in wrapper
return func(request, backend, *args, **kwargs)
File "/Users/marinopallvaldimarsson/.virtualenvs/gracipe/lib/python2.7/site-packages/social/apps/django_app/views.py", line 25, in complete
redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs)
File "/Users/marinopallvaldimarsson/.virtualenvs/gracipe/lib/python2.7/site-packages/social/actions.py", line 54, in do_complete
*args, **kwargs)
File "/Users/marinopallvaldimarsson/.virtualenvs/gracipe/lib/python2.7/site-packages/social/strategies/base.py", line 69, in complete
return self.backend.auth_complete(*args, **kwargs)
File "/Users/marinopallvaldimarsson/.virtualenvs/gracipe/lib/python2.7/site-packages/social/backends/facebook.py", line 74, in auth_complete
return self.do_auth(access_token, response, *args, **kwargs)
File "/Users/marinopallvaldimarsson/.virtualenvs/gracipe/lib/python2.7/site-packages/social/backends/facebook.py", line 106, in do_auth
return self.strategy.authenticate(*args, **kwargs)
File "/Users/marinopallvaldimarsson/.virtualenvs/gracipe/lib/python2.7/site-packages/social/strategies/django_strategy.py", line 69, in authenticate
return authenticate(*args, **kwargs)
File "/Users/marinopallvaldimarsson/.virtualenvs/gracipe/lib/python2.7/site-packages/django/contrib/auth/__init__.py", line 60, in authenticate
user = backend.authenticate(**credentials)
File "/Users/marinopallvaldimarsson/.virtualenvs/gracipe/lib/python2.7/site-packages/social/backends/base.py", line 78, in authenticate
return self.pipeline(pipeline, *args, **kwargs)
File "/Users/marinopallvaldimarsson/.virtualenvs/gracipe/lib/python2.7/site-packages/social/backends/base.py", line 81, in pipeline
out = self.run_pipeline(pipeline, pipeline_index, *args, **kwargs)
File "/Users/marinopallvaldimarsson/.virtualenvs/gracipe/lib/python2.7/site-packages/social/backends/base.py", line 107, in run_pipeline
result = func(*args, **out) or {}
File "/Users/marinopallvaldimarsson/.virtualenvs/gracipe/lib/python2.7/site-packages/social/pipeline/user.py", line 91, in user_details
strategy.storage.user.changed(user)
File "/Users/marinopallvaldimarsson/.virtualenvs/gracipe/lib/python2.7/site-packages/social/storage/django_orm.py", line 13, in changed
user.save()
File "/Users/marinopallvaldimarsson/.virtualenvs/gracipe/lib/python2.7/site-packages/django/db/models/base.py", line 546, in save
force_update=force_update, update_fields=update_fields)
File "/Users/marinopallvaldimarsson/.virtualenvs/gracipe/lib/python2.7/site-packages/django/db/models/base.py", line 626, in save_base
rows = manager.using(using).filter(pk=pk_val)._update(values)
File "/Users/marinopallvaldimarsson/.virtualenvs/gracipe/lib/python2.7/site-packages/django/db/models/query.py", line 605, in _update
return query.get_compiler(self.db).execute_sql(None)
File "/Users/marinopallvaldimarsson/.virtualenvs/gracipe/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1014, in execute_sql
cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
File "/Users/marinopallvaldimarsson/.virtualenvs/gracipe/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 840, in execute_sql
cursor.execute(sql, params)
File "/Users/marinopallvaldimarsson/.virtualenvs/gracipe/lib/python2.7/site-packages/django/db/backends/util.py", line 41, in execute
return self.cursor.execute(sql, params)
File "/Users/marinopallvaldimarsson/.virtualenvs/gracipe/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 122, in execute
six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
File "/Users/marinopallvaldimarsson/.virtualenvs/gracipe/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 120, in execute
return self.cursor.execute(query, args)
File "/Users/marinopallvaldimarsson/.virtualenvs/gracipe/lib/python2.7/site-packages/MySQLdb/cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "/Users/marinopallvaldimarsson/.virtualenvs/gracipe/lib/python2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
IntegrityError: (1062, "Duplicate entry '[email protected]' for key 'email'")
This is my user model
class MyUserManager(BaseUserManager):
def create_user(self, email, username=None, password=None, date_of_birth=None, **extra_fields):
"""
Creates and saves a User with the given email, date of
birth and password.
"""
username=email
if not email:
raise ValueError('Users must have an email address')
# if not password:
# raise ValueError('Users must have an password')
user = self.model(
email=self.normalize_email(email),
date_of_birth=date_of_birth,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password, date_of_birth=None):
"""
Creates and saves a superuser with the given email, date of
birth and password.
"""
user = self.create_user(email,
password=password,
date_of_birth=date_of_birth
)
user.is_admin = True
user.save(using=self._db)
return user
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
db_index=True,
)
first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True)
date_of_birth = models.DateField(default=None,blank=True,null=True)
is_admin = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_staff = models.BooleanField(_('staff status'), default=False,
help_text=_('Designates whether the user can log into this admin '
'site.'))
is_active = models.BooleanField(_('active'), default=True,
help_text=_('Designates whether this user should be treated as '
'active. Unselect this instead of deleting accounts.'))
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
username = models.CharField(_('username'), max_length=30,
help_text=_('Required. 30 characters or fewer. Letters, numbers and '
'@/./+/-/_ characters'),
validators=[
validators.RegexValidator(re.compile('^[\w.@+-]+$'), _('Enter a valid username.'), 'invalid')
])
objects = MyUserManager()
USERNAME_FIELD = 'email'
def is_authenticated(self):
"""
Always return True. This is a way to tell if the user has been
authenticated in templates.
"""
return True
def get_full_name(self):
# The user is identified by their email address
return self.email
def get_short_name(self):
# The user is identified by their email address
return self.email
# On Python 3: def __str__(self):
def __unicode__(self):
return self.email
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
@property
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin
If in config set PROTECTED_USER_FIELDS = ['first_name', 'last_name']
then when user just registered through social network (facebook, linkedin etc) those fields will not be set and details for new users are empty.
In SOCIAL_AUTH_PIPELINE
'social.pipeline.user.user_details'
is below create_user pipeline
I am attempting to use Django oauth with Amazon.
I have setup an application with amazon and placed my key/secret in settings.py
SOCIAL_AUTH_AMAZON_OAUTH2_KEY = ''blahkey'
SOCIAL_AUTH_AMAZON_OAUTH2_SECRET = 'blahblahblabhsecret'
The request (which returns an Error from Amazon) is made to amazon with url like so:
https://www.amazon.com/ap/oa?ie=UTF8&response_type=code&scope=profile&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fcomplete%2Famazon%2F&state=oRNdyN6ewMMA6zqkkPc2k8ntR20JNtp2&client_id=None
Notice the client_id=None in the url. Could this be an issue?
I've followed both the tutorial and examples/flask_example but I keep getting error about missing social_auth_usersocialauth relation.
One thing I had to change in the sample was
Base.metadata.create_all(bind=Base)
(Base was missing Model) to
Base.metadata.create_all(bind=db.engine)
Traceback: https://gist.github.com/skakri/5282381
I haven't tried to set up relation manually (I'm not proficient in postgresql).
Currently I don't see support for linkedin oauth2. Is it supported?
Sorry, maybe it's a dumb question.
But after /done/, after everything ok, how can I get the user details, something like: {{ user.social_auth.gender }}. Thank you!
Not an issue, just an enhancement: It would be great if you could add a pyramid example.
cheers
How can I unit test authentication on my Django app using python-social-auth?
I attempted this:
self.c = Client()
self.u = User.objects.create(username="testuser", password="password", is_staff=True, is_active=True, is_superuser=True)
self.u.save()
self.auth = UserSocialAuth(user=self.u, provider="Facebook")
self.auth.save()
self.c.login(username=self.u.username, password=self.u.password)
but this call to login returns False and the user is not authenticated
I believe I have it set up correctly—it redirects me as expected to Github to sign in, and then github forwards my browser back to the app, where I land on a 500. There's no python error or backtrace shown either in the browser or command line—just this sequence:
10.25.0.217 - - [30/Aug/2013 15:48:46] "GET / HTTP/1.1" 200 -
10.25.0.217 - - [30/Aug/2013 15:48:52] "GET /login/github/ HTTP/1.1" 302 -
10.25.0.217 - - [30/Aug/2013 15:48:53] "GET /complete/github/?code=7900ff5b...ae1c&redirect_state=n6tqyniCa...s9tf8yXE0&state=n6tqyniCaD....tf8yXE0 HTTP/1.1" 500 -
As I've already added the app on Github at this point, it's an immediate turnaround, but I see the same error when I have to click through manually.
Note: I'm also seeing a problem where the initial pageload triggers a "'Session' object has no attribute '_model_changes'" from what looks to be some SQLAlchemy initialization stuff. Subsequent pageloads appear to work correctly, though, so I'm not certain that's a related issue.
When I try to install the databases in django 1.5.4 I get this:
PicklingError: Can't pickle <class 'django.db.models.fields.subclassing.JSONField'>: attribute lookup django.db.models.fields.subclassing.JSONField failed
--EDIT
This error appears when not use south
The documented way of setting the permissions scope for facebook is:
SOCIAL_AUTH_FACEBOOK_EXTENDED_PERMISSIONS = ['email']
This was not working and after looking at the source code I found that it is working with:
SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']
I guess we have a documentation bug here.
I can't being logged with any social backend with Django 1.6b4.
I have debugged and I realized that the request
var (strategy.request
) is not the same when accessing to final view ("example.app.views.done") as the strategy.request
, which is modified with the real logged user.
PS: The account association seems to work properly
Traceback:
File "/Users/mlowicki/Projects/buildout/eggs/Django-1.5.4-py2.7.egg/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/mlowicki/Projects/buildout/eggs/Django-1.5.4-py2.7.egg/django/views/decorators/csrf.py" in wrapped_view
77. return view_func(*args, **kwargs)
File "/Users/mlowicki/Projects/buildout/eggs/python_social_auth-0.1.13-py2.7.egg/social/apps/django_app/utils.py" in wrapper
32. return func(request, backend, *args, **kwargs)
File "/Users/mlowicki/Projects/buildout/eggs/python_social_auth-0.1.13-py2.7.egg/social/apps/django_app/views.py" in complete
25. redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs)
File "/Users/mlowicki/Projects/buildout/eggs/python_social_auth-0.1.13-py2.7.egg/social/actions.py" in do_complete
54. *args, **kwargs)
File "/Users/mlowicki/Projects/buildout/eggs/python_social_auth-0.1.13-py2.7.egg/social/strategies/base.py" in complete
71. return self.backend.auth_complete(*args, **kwargs)
File "/Users/mlowicki/Projects/buildout/eggs/python_social_auth-0.1.13-py2.7.egg/social/backends/facebook.py" in auth_complete
68. 'code': self.data['code']
File "/Users/mlowicki/Projects/buildout/eggs/Django-1.5.4-py2.7.egg/django/utils/datastructures.py" in __getitem__
23. raise KeyError
Exception Type: KeyError at /complete/facebook/
Exception Value:
self.data is set to:
{u'redirect_state': u'[snap]', u'state': u'[snap]', u'error_message': u'Potwierd\u017a adres e-mail: Podany przez Ciebie adres e-mail zosta\u0142 ju\u017c zarejestrowany, ale Twoje konto nie zosta\u0142o jeszcze potwierdzone. Wkr\xf3tce otrzymasz wiadomo\u015b\u0107 e-mail z informacjami na temat sposobu potwierdzania konta.', u'error_code': u'1348058'}
Hi, I got the problem when using douban backend.
I configured like this(Already created a web app in douban developer site)
SOCIAL_AUTH_DOUBAN_OAUTH2_KEY = ''
SOCIAL_AUTH_DOUBAN_OAUTH2_SECRET = ''
Add 'social.backends.douban.DoubanOAuth2' into SOCIAL_AUTH_AUTHENTICATION_BACKENDS.
but I got the exception when I tried to login with douban account.
AuthCanceled at /complete/douban-oauth2/
Authentication process canceled
I didn't get some ideas why authentication process canceled. Could you help my trouble shooting? Thanks.
v01.1.12
https://github.com/omab/python-social-auth/releases/tag/v01.1.12
and v0.1.13 and v0.1.14 are missing
I need some help creating a custom User model, in order to extend it.
My models.py is :
from mongoengine.django.auth import User
class User(User):
"""Extend Mongo Engine User model"""
foo = ListField(default=[])
So I have updated the settings.py with:
MONGOENGINE_USER_DOCUMENT = 'apps.models.User'
AUTH_USER_MODEL = 'mongo_auth.MongoUser'
SOCIAL_AUTH_USER_MODEL = 'apps.models.User'
However on login I get:
ValidationError: ValidationError (UserSocialAuth:526fab8ac36b440b4a8f080b) (A ReferenceField only accepts DBRef or documents: ['user'])
I checked I saw that the 526fab8ac36b440b4a8f080b
id is the user id in user_social_auth
collection.
I'm using Django 1.5.4 and Django Social Auth 0.7.28 without a problem but wanted to make a switch because of deprecation. During connecting procedure with facebook i can never complete the procedure. I've tried going throught python-social-auth code to see what was going on but couldn't figure it out beside the django authenticate() returning None.
Connecting procedure:
click on:
127.0.0.1 - - [26/Sep/2013 11:33:52] "GET /login/facebook/ HTTP/1.1" 302 -
127.0.0.1 - - [26/Sep/2013 11:33:53] "GET /complete/facebook/?redirect_state=n4Bm...SeNJw&code=AQASofC...MRa57z3o&state=n4Bm...SeNJw HTTP/1.1" 302 -
127.0.0.1 - - [26/Sep/2013 11:33:53] "GET /accounts/login-error/ HTTP/1.1" 404 - (i dont have login-error currently implemented)
This is roughly the state of the various functions that python-social-auth calls
do_complete
strategy.request_data()
data: {u'state': u'n4Bm...SeNJw', u'code': u'AQASofC...MRa57z3o', u'redirect_state': u'n4Bm...SeNJw'}
partial is None
- FacebookOAuth2 auth_complete
state: n4BmS...SeNJw
key: 211331415633513
url: https://graph.facebook.com/oauth/access_token
access_token: CAAD...yDE
- FacebookOAuth2 do_auth ---
- FacebookOAuth2 user_data ---
data: {u'username': u'ho...c', ..., u'id': u'100...92'}
- DjangoStrategy authenticate--
args: ()
kwargs contains complete request
kwargs response: {
u'username': u'ho...c', ..., # other profile data
'access_token': u'CAAD...yDE',
u'id': u'100004043024192'
}
kwargs user: None
kwargs backend: social.backends.facebook.FacebookOAuth2
DjangoStrategy backend: social.backends.facebook.FacebookOAuth2
django.contrib.auth.authenticate returns None
not authenticated, not user hence
url = login_error_url # /accounts/login-error/
I've also documented all the changes from django-social-auth (OLD) to python-social-auth (NEW):
Django==1.5.4
django-social-auth==0.7.28
python-social-auth==0.1.13
/accounts/middleware.py
OLD:
from social_auth.middleware import SocialAuthExceptionMiddleware
from social_auth.exceptions import AuthCanceled
NEW:
from social.apps.django_app.middleware import SocialAuthExceptionMiddleware
from social.exceptions import AuthCanceled
accounts/templates/accounts/index.html
OLD
{% if not social_auth.facebook %}
a href="{% url 'socialauth_associate_begin' 'facebook' %}"
NEW
{% if not social.facebook %}
a href="{% url 'social:begin' 'facebook' %}"
accounts/templates/accounts/login.html
OLD:
href="{% url 'socialauth_begin' 'facebook' %}"
NEW:
href="{% url 'social:begin' 'facebook' %}"
cstorm/settings/base.py
OLD INSTALLED_APPS
'social_auth',
NEW INSTALLED_APPS
'social.apps.django_app.default',
OLD:
AUTHENTICATION_BACKENDS = (
'social_auth.backends.facebook.FacebookBackend',
'accounts.auth_backends.EmailOrUsernameBackend',
)
NEW:
AUTHENTICATION_BACKENDS = (
'social.backends.facebook.FacebookOAuth2',
'accounts.auth_backends.EmailOrUsernameBackend',
# 'django.contrib.auth.backends.ModelBackend', #doesnt make a difference
)
OLD:
LOGIN_REDIRECT_URL = '/accounts/postlogin/'
LOGIN_ERROR_URL = '/accounts/login-error/'
NEW:
SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/accounts/postlogin/'
SOCIAL_AUTH_LOGIN_ERROR_URL = '/accounts/login-error/'
OLD:
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.tz',
'django.core.context_processors.request',
'django.contrib.messages.context_processors.messages',
'social_auth.context_processors.social_auth_by_name_backends',
)
NEW:
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.tz',
'django.core.context_processors.request',
'django.contrib.messages.context_processors.messages',
'social.apps.django_app.context_processors.backends',
)
OLD:
SOCIAL_AUTH_PIPELINE = (
'social_auth.backends.pipeline.social.social_auth_user',
'social_auth.backends.pipeline.associate.associate_by_email',
'social_auth.backends.pipeline.user.get_username',
'social_auth.backends.pipeline.user.create_user',
'social_auth.backends.pipeline.social.associate_user',
'social_auth.backends.pipeline.social.load_extra_data',
'social_auth.backends.pipeline.user.update_user_details',
'accounts.social_auth_pipeline.get_profile_data', # custom
'accounts.social_auth_pipeline.get_profile_avatar', # custom
)
NEW:
SOCIAL_AUTH_PIPELINE = (
'social.pipeline.social_auth.social_user',
'social.pipeline.social_auth.associate_by_email',
'social.pipeline.user.get_username',
'social.pipeline.user.create_user',
'social.pipeline.social_auth.associate_user',
'social.pipeline.social_auth.load_extra_data',
'social.pipeline.user.user_details',
'accounts.social_auth_pipeline.get_profile_data', # custom
'accounts.social_auth_pipeline.get_profile_avatar', # custom
)
OLD:
FACEBOOK_EXTENDED_PERMISSIONS = ['email', 'user_birthday']
NEW:
#FACEBOOK_EXTENDED_PERMISSIONS = ['email', 'user_birthday']
SOCIAL_AUTH_FACEBOOK_EXTENDED_PERMISSIONS = ['email', 'user_birthday']
SOCIAL_AUTH_FACEBOOK_SCOPE = ['email', 'user_birthday']
OLD:
FACEBOOK_APP_ID = '...'
FACEBOOK_API_SECRET = '...'
NEW:
SOCIAL_AUTH_FACEBOOK_KEY = '...'
SOCIAL_AUTH_FACEBOOK_SECRET = '...'
urls.py
OLD:
(r'^sso/', include('social_auth.urls')),
NEW:
(r'^sso/', include('social.apps.django_app.urls', namespace='social')),
I have a logged in user and want to connect a social auth to existing user. Is there a way to do that?
Traceback (most recent call last):
File "/home/markus/.venvs/bakery/lib/python3.3/site-packages/django/core/urlresolvers.py", line 340, in urlconf_module
return self._urlconf_module
AttributeError: 'RegexURLResolver' object has no attribute '_urlconf_module'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/markus/.venvs/bakery/lib/python3.3/site-packages/gunicorn/workers/sync.py", line 131, in handle_request
respiter = self.wsgi(environ, resp.start_response)
File "/home/markus/.venvs/bakery/lib/python3.3/site-packages/django/core/handlers/wsgi.py", line 255, in __call__
response = self.get_response(request)
File "/home/markus/.venvs/bakery/lib/python3.3/site-packages/django/core/handlers/base.py", line 178, in get_response
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
File "/home/markus/.venvs/bakery/lib/python3.3/site-packages/django/core/handlers/base.py", line 220, in handle_uncaught_exception
if resolver.urlconf_module is None:
File "/home/markus/.venvs/bakery/lib/python3.3/site-packages/django/core/urlresolvers.py", line 342, in urlconf_module
self._urlconf_module = import_module(self.urlconf_name)
File "/home/markus/.venvs/bakery/lib/python3.3/site-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/home/markus/Coding/bakery/bakery/urls.py", line 7, in <module>
admin.autodiscover()
File "/home/markus/.venvs/bakery/lib/python3.3/site-packages/django/contrib/admin/__init__.py", line 29, in autodiscover
import_module('%s.admin' % app)
File "/home/markus/.venvs/bakery/lib/python3.3/site-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/home/markus/Coding/python-social-auth/social/apps/django_app/default/admin.py", line 13, in <module>
all_names = _User._meta.get_all_field_names()
AttributeError: 'str' object has no attribute '_meta'
Pull request follows.
I'm about to add a new social backend and I'm not sure what's the difference between the get_user_details()
and user_data()
methods. In this particular backend, the response from the ACCESS_TOKEN_URL
has almost no user details other than the token itself; all details are fetched from a separate api call to the service. So I tried returning an empty dict from get_user_details()
but apparently the username is autogenerated in this case, which is not what I want. I can make the api call to the service to retrieve the user data in get_user_details()
but then what's the point of having user_data()
?
Thanks,
George
Stopped work authorization through steam
Django==1.6
python-social-auth==0.1.16
python-openid==2.2.5
I seem to be having an issue with social auth and logging in via Facebook OAuth2 from Django.
When logging in the browser appears to get stuck in an infinite loop from the app to Facebook and back again, but only when the view Facebook is returning to takes longer than a certain time to complete (normally a longer than a few seconds).
It is repeatable using the example Django app, it requires a next parameter is added initially:
<a href="{% url 'social:begin' "facebook" %}?next=/done/">Facebook</a>
This in itself will work, however if the view is delayed from completing (a simple time.sleep will do) it will begin to loop. Test view looks like this:
@login_required
def done(request):
"""Login complete view, displays user data"""
import time
time.sleep(5)
scope = ' '.join(GooglePlusAuth.DEFAULT_SCOPE)
return render_to_response('done.html', {
'user': request.user,
'plus_id': getattr(settings, 'SOCIAL_AUTH_GOOGLE_PLUS_KEY', None),
'plus_scope': scope
}, RequestContext(request))
It does need to be a time >4 seconds it seems but it can vary. The console doesn't give much indication other than the requests are going through. However on odd occasions it will throw a "error: [Errno 32] Broken pipe" but continue looping. It's almost as if two requests are running simultaneously and competing with each other.
It's not overly clear why this is occurring, any thoughts where this might be going wrong?
(Running latest version of social auth and Django 1.5.4 - also tried 1.4.8 & 1.4.5 and it is consistent)
SOCIAL_AUHT_FACEBOOK_KEY --> SOCIAL_AUTH_FACEBOOK_KEY
https://github.com/omab/python-social-auth/blob/master/social/backends/facebook.py#L5
noticed that when copy pasting + using the variable ;)
After authentication I have in table 'social_auth_usersocialauth' extra_data={"token_type": "Bearer", "access_token": "ya29.AHES6ZQtbhA1K-CmCn8bvnZy.................AgCfk8", "expires": 3599} without refresh_token. I think refresh_token is a required part of response.
Documentation states SOCIAL_AUTH_YAHOO_KEY, SOCIAL_AUTH_YAHOO_SECRET, but the library really wants SOCIAL_AUTH_YAHOO_OAUTH_KEY, SOCIAL_AUTH_YAHOO_OAUTH_SECRET.
at first sight it does not seem to serve a purpose
edit
https://github.com/omab/python-social-auth/blob/master/social/apps/flask_app/models.py#L88
Hi,
I received a comment today expressing python-social-auth's interest in using rauth provided rauth runs on Python 3. Unfortunately, today it is does not. However there have been efforts and it's on my radar, e.g. slated for the 0.6.0 release.
It would be fantastic if the Python community wanted to work on this. Certainly if there's a demand for rauth on Python 3 I want to see that demand met. However given I can't give a definitive timeline for this, it would be great if others wanted to take the lead on this a bit. I could probably contribute alongside these efforts as well, albeit I probably won't be able to devote huge chunks of my time to it.
It's probably feasible to revive the previous efforts. I'm not sure exactly how much work would be involved in making things work with Python 3. The good news is Requests should be good to go so the hardest part may be organizing it sanely and getting the tests to pass.
Anyway to be clear, this is not a python-social-auth issue, but an issue that lies upstream with rauth. But that said. I wanted to open up a dialogue and confirm interest.
Thanks!
{"code": 400, "error_type": "OAuthException", "error_message": "Redirect URI does not match registered redirect URI"}
on instargam side everything seems to be correct
It's saved as <_sre.SRE_Match object at 0x2b189cbe6990>
instead of actual ID.
As a side note, I just started using this repo after I found out you deleted requests
branch from django-social-auth
repo. Is this package going to replace django-social-auth
in the future?
It's only started happening since 0.1.15, and it's kind of frustrating.
Django==1.5.5
python-openid==2.2.5
requests==2.0.1
oauthlib==0.6.0
requests-oauthlib==0.4.0
six==1.4.1
I'm not sure if there was a small bug in my code that got exacerbated by any changes in the latest release, but figured I'd post this anyways in case someone is seeing something similar.
Here is the traceback:
TypeError at /auth/login/google/
TypeError: int() argument must be a string or a number, not 'Association' Stacktrace (most recent call last): File "django/core/handlers/base.py", line 115, in get_response response = callback(request, *callback_args, **callback_kwargs) File "social/apps/django_app/utils.py", line 32, in wrapper return func(request, backend, *args, **kwargs) File "social/apps/django_app/views.py", line 16, in auth return do_auth(request.strategy, redirect_name=REDIRECT_FIELD_NAME) File "social/actions.py", line 25, in do_auth return strategy.start() File "social/strategies/base.py", line 56, in start if self.backend.uses_redirect(): File "social/backends/open_id.py", line 215, in uses_redirect return self.openid_request().shouldSendRedirect() File "social/backends/open_id.py", line 221, in openid_request params)) File "openid/consumer/consumer.py", line 353, in begin return self.beginWithoutDiscovery(service, anonymous) File "openid/consumer/consumer.py", line 376, in beginWithoutDiscovery auth_req = self.consumer.begin(service) File "openid/consumer/consumer.py", line 598, in begin assoc = self._getAssociation(service_endpoint) File "openid/consumer/consumer.py", line 1158, in _getAssociation assoc = self.store.getAssociation(endpoint.server_url) File "social/store.py", line 51, in getAssociation self.assoc.remove(expired) File "social/storage/django_orm.py", line 127, in remove cls.objects.filter(pk__in=ids_to_delete).delete() File "django/db/models/manager.py", line 155, in filter return self.get_query_set().filter(*args, **kwargs) File "django/db/models/query.py", line 669, in filter return self._filter_or_exclude(False, *args, **kwargs) File "django/db/models/query.py", line 687, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "django/db/models/sql/query.py", line 1271, in add_q can_reuse=used_aliases, force_having=force_having) File "django/db/models/sql/query.py", line 1202, in add_filter connector) File "django/db/models/sql/where.py", line 71, in add value = obj.prepare(lookup_type, value) File "django/db/models/sql/where.py", line 339, in prepare return self.field.get_prep_lookup(lookup_type, value) File "django/db/models/fields/__init__.py", line 324, in get_prep_lookup return [self.get_prep_value(v) for v in value] File "django/db/models/fields/__init__.py", line 555, in get_prep_value return int(value)
I have a working django LinkedIn OAuth1 setup. I have tried to switch to OAuth2 by updating all my settings from SOCIAL_AUTH_LINKEDIN_* to SOCIAL_AUTH_LINKEDIN_OAUTH2_* and switching the backend to social.backends.linkedin.LinkedinOAuth2
I get an AuthCancelled Exception. Triggered I think by by HTTPError('400 Client Error: Bad Request',)
The inbound URL looks like:
Have I missed anything in my setup changes? Any other ideas? Thanks.
The Steam backend returns an invalid user id.
In steam.py#37, the whole MatchObject
is returned instead of the subgroup.
Adding .group(1)
fixes the problem.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.