Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django-social-auth create new user programmatically by facebook_id

Is there any way to create User and UserSocialAuth objects without actually loggin in but only having FACEBOOK_ID of a user you want to create an account for?

I'm creating a simple app where user can select a friend from FB and create some model object for him. Since I have reference to User entity I need to have it whether that friend has been registered or not. And if not I need to create the whole object graph programmatically. It is possible to do using standard functionality of django-social-auth or should I create records in 'auth_user' and 'social_auth_usersocialauth' by hand?

like image 428
zjor Avatar asked Dec 12 '25 20:12

zjor


1 Answers

Use this custom backend that sets the username to the person's FACEBOOK_ID.

from social_auth.backends.facebook import FacebookBackend
class IDFacebookBackend(FacebookBackend):
    """Facebook OAuth2 authentication backend"""
    def get_user_details(self, response):
        """Return user details from Facebook account"""
        return {'username': response.get('id'),
                'email': response.get('email', ''),
                'fullname': response.get('name', ''),
                'first_name': response.get('first_name', ''),
                'last_name': response.get('last_name', '')}

Use this version of get_username in your auth pipleline instead of social_auth.backends.pipeline.user.get_username

def get_username(details, user=None, *args, **kwargs):
    " Make Username from User Id "
    if user:
        return {'username': UserSocialAuth.user_username(user)}
    else:
        return details['username']

Your pipeline should look like this:

SOCIAL_AUTH_PIPELINE = (
    'social_auth.backends.pipeline.social.social_auth_user',
    'our_custom_auth.get_username', # <= This should be the previous function
    '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'
)

Then all you need to do is call User.objects.create(username=friends_facebook_id) and you have a User that cannot login with username/pass, but can be referenced easily through ForeignKey fields.

Also, when that "Friend" comes and joins up with your site at a later date (Using SocialAuth), they will automatically be given this User object and your internal graph will stay accurate.

like image 73
Thomas Avatar answered Dec 14 '25 11:12

Thomas