def disconnect(self, user, association_id=None): """Deletes current backend from user if associated. Override if extra operations are needed. """ if association_id: UserSocialAuth.get_social_auth_for_user(user)\ .get(id=association_id).delete() else: UserSocialAuth.get_social_auth_for_user(user)\ .filter(provider=self.AUTH_BACKEND.name).delete()
def getAssociation(self, server_url, handle=None): """Return stored assocition""" oid_associations = UserSocialAuth.get_oid_associations(server_url, handle) associations = [association for assoc_id, association in oid_associations if association.getExpiresIn() > 0] expired = [assoc_id for assoc_id, association in oid_associations if association.getExpiresIn() == 0] if expired: # clear expired associations UserSocialAuth.delete_associations(expired) if associations: # return most recet association return associations[0]
def modify(request): if request.user.is_authenticated(): if request.method == 'POST': sug = str(request.POST.get("suggestion").encode('utf-8')) article = get_object_or_404( ArticleDetails, id=request.POST.get("article")) feedbacks = Feedback.objects.filter(articledetails_id = request.POST.get("article"), email= request.POST.get("email"), name = request.POST.get("name")) for feedback in feedbacks: if feedback.suggestion.raw.encode('utf-8') == sug: return HttpResponse(simplejson.dumps({'duplicate':True,'name':request.POST.get("name")})) Feedback(user = request.POST.get("user_id"),articledetails_id = request.POST.get("article"),suggestion = request.POST.get("suggestion") , email = request.POST.get("email"), name = request.POST.get("name")).save() feedback = Feedback.objects.filter(articledetails_id = request.POST.get("article"),suggestion = request.POST.get("suggestion") , email= request.POST.get("email"), name = request.POST.get("name")) article.feedback_count = article.feedback_count + 1 article.save() if request.user.username != "admin": # post on twitter or facebook if UserSocialAuth.auth_provider(request.user.username) == 'facebook': extra_data = UserSocialAuth.get_extra_data(request.user.username) access_token = extra_data['access_token'] # GraphAPI is the main class from facebook_sdp.py art = get_object_or_404(ArticleDetails, id=request.POST.get("article")) art_name = art.header.name.encode('utf-8') art_body = art.summary.raw.encode('utf-8') graph = facebook_sdk.GraphAPI(access_token) attachment = {} attachment['name'] = art_name attachment['link'] = shorten_url(settings.domain+"sharek/"+request.POST.get("class_slug")+"/"+request.POST.get("article_slug")+"/comment/"+str(feedback[0].id)+"/") attachment['picture'] = settings.domain + settings.STATIC_URL + "images/facebook-thumb.jpg" attachment['description'] = art_body message = 'لقد شاركت في كتابة #دستور_مصر وقمت بالتعليق على '+art_name+" من الدستور" graph.put_wall_post(message, attachment) if UserSocialAuth.auth_provider(request.user.username) == 'twitter': extra_data = UserSocialAuth.get_extra_data(request.user.username) access_token = extra_data['access_token'] access_token_secret = access_token[access_token.find('=')+1 : access_token.find('&')] access_token_key = access_token[access_token.rfind('=')+1:] api = twitter.Api(consumer_key=settings.TWITTER_CONSUMER_KEY, consumer_secret=settings.TWITTER_CONSUMER_SECRET, access_token_key=access_token_key, access_token_secret=access_token_secret) link = shorten_url(settings.domain+"sharek/"+request.POST.get("class_slug")+"/"+request.POST.get("article_slug")+"/comment/"+str(feedback[0].id)+"/") message = 'لقد شاركت في كتابة #دستور_مصر بالتعليق على '+get_object_or_404(ArticleDetails, id=request.POST.get("article")).header.name.encode('utf-8')+" "+link api.PostUpdate(message) return HttpResponse(simplejson.dumps({'date':str(feedback[0].date),'id':feedback[0].id ,'suggestion':request.POST.get("suggestion")}))
def backends_data(user): """Return backends data for given user. Will return a dict with values: associated: UserSocialAuth model instances for currently associated accounts not_associated: Not associated (yet) backend names. backends: All backend names. If user is not authenticated, then first list is empty, and there's no difference between the second and third lists. """ available = get_backends().keys() values = { 'associated': [], 'not_associated': available, 'backends': available } # user comes from request.user usually, on /admin/ it will be an instance # of auth.User and this code will fail if a custom User model was defined if hasattr(user, 'is_authenticated') and user.is_authenticated(): associated = UserSocialAuth.get_social_auth_for_user(user) not_associated = list( set(available) - set(assoc.provider for assoc in associated)) values['associated'] = associated values['not_associated'] = not_associated return values
def get_username(details, user=None, user_exists=UserSocialAuth.simple_user_exists, *args, **kwargs): """Return an username for new user. Return current user username if user was given. """ if user: return {'username': user.username} if details.get(USERNAME): username = unicode(details[USERNAME]) else: username = uuid4().get_hex() uuid_length = 16 max_length = UserSocialAuth.username_max_length() short_username = username[:max_length - uuid_length] final_username = username[:max_length] # Generate a unique username for current user using username # as base but adding a unique hash at the end. Original # username is cut to avoid any field max_length. while user_exists(username=final_username): username = short_username + uuid4().get_hex()[:uuid_length] final_username = username[:max_length] return {'username': final_username}
def backends_data(user): """Return backends data for given user. Will return a dict with values: associated: UserSocialAuth model instances for currently associated accounts not_associated: Not associated (yet) backend names. backends: All backend names. If user is not authenticated, then first list is empty, and there's no difference between the second and third lists. """ available = get_backends().keys() values = {'associated': [], 'not_associated': available, 'backends': available} # user comes from request.user usually, on /admin/ it will be an instance # of auth.User and this code will fail if a custom User model was defined if hasattr(user, 'is_authenticated') and user.is_authenticated(): associated = UserSocialAuth.get_social_auth_for_user(user) not_associated = list(set(available) - set(assoc.provider for assoc in associated)) values['associated'] = associated values['not_associated'] = not_associated return values
def get_username(details, user=None, user_exists=UserSocialAuth.simple_user_exists, *args, **kwargs): """Return an username for new user. Return current user username if user was given. """ if user: return {'username': user.username} if details.get(USERNAME): username = unicode(details[USERNAME]) else: username = uuid4().get_hex() uuid_length = 16 max_length = UserSocialAuth.username_max_length() short_username = username[:max_length - uuid_length] final_username = username[:max_length] # Generate a unique username for current user using username # as base but adding a unique hash at the end. Original # username is cut to avoid any field max_length. while user_exists(username=final_username): username = short_username + uuid4().get_hex()[:uuid_length] final_username = username[:max_length] return {'username': final_username}
def context_value(): keys = get_backends().keys() accounts = dict(zip(keys, [None] * len(keys))) user = request.user if hasattr(user, 'is_authenticated') and user.is_authenticated(): accounts.update((assoc.provider.replace('-', '_'), assoc) for assoc in UserSocialAuth.get_social_auth_for_user(user)) return accounts
def context_value(): keys = get_backends().keys() accounts = dict(zip(keys, [None] * len(keys))) user = request.user if hasattr(user, 'is_authenticated') and user.is_authenticated(): accounts.update( (assoc.provider.replace('-', '_'), assoc) for assoc in UserSocialAuth.get_social_auth_for_user(user)) return accounts
def consumer_oauth_url_request(backend, url, user_or_id, redirect_uri="/", json=True): """Builds and retrieves an OAuth signed response.""" user = UserSocialAuth.resolve_user_or_id(user_or_id) oauth_info = user.social_auth.filter(provider=backend.AUTH_BACKEND.name)[0] token = Token.from_string(oauth_info.tokens["access_token"]) request = build_consumer_oauth_request(backend, token, url, redirect_uri) response = "\n".join(dsa_urlopen(request.to_url()).readlines()) if json: response = simplejson.loads(response) return response
def consumer_oauth_url_request(backend, url, user_or_id, redirect_uri='/', json=True): """Builds and retrieves an OAuth signed response.""" user = UserSocialAuth.resolve_user_or_id(user_or_id) oauth_info = user.social_auth.filter(provider=backend.AUTH_BACKEND.name)[0] token = Token.from_string(oauth_info.tokens['access_token']) request = build_consumer_oauth_request(backend, token, url, redirect_uri) response = '\n'.join(dsa_urlopen(request.to_url()).readlines()) if json: response = simplejson.loads(response) return response
def create_user(backend, details, response, uid, username, user=None, *args, **kwargs): """Create user. Depends on get_username pipeline.""" if user: return {'user': user} if not username: return None # NOTE: not return None because Django raises exception of strip email email = details.get('email') or '' return { 'user': UserSocialAuth.create_user(username=username, email=email), 'is_new': True }
def load_extra_data(backend, details, response, uid, user, social_user=None, *args, **kwargs): """Load extra data from provider and store it on current UserSocialAuth extra_data field. """ social_user = social_user or \ UserSocialAuth.get_social_auth(backend.name, uid) if social_user: extra_data = backend.extra_data(user, uid, response, details) if extra_data and social_user.extra_data != extra_data: if social_user.extra_data: social_user.extra_data.update(extra_data) else: social_user.extra_data = extra_data social_user.save() return {'social_user': social_user}
def social_auth_user(backend, uid, user=None, *args, **kwargs): """Return UserSocialAuth account for backend/uid pair or None if it doesn't exists. Raise AuthAlreadyAssociated if UserSocialAuth entry belongs to another user. """ social_user = UserSocialAuth.get_social_auth(backend.name, uid) if social_user: if user and social_user.user != user: msg = ugettext('This %(provider)s account is already in use.') raise AuthAlreadyAssociated(backend, msg % {'provider': backend.name}) elif not user: user = social_user.user return {'social_user': social_user, 'user': user}
def associate_by_email(details, user=None, *args, **kwargs): """Return user entry with same email address as one returned on details.""" if user: return None email = details.get('email') if email: # try to associate accounts registered with the same email address, # only if it's a single object. AuthException is raised if multiple # objects are returned try: return {'user': UserSocialAuth.get_user_by_email(email=email)} except MultipleObjectsReturned: raise AuthException(kwargs['backend'], 'Not unique email address.') except ObjectDoesNotExist: pass
def associate_user(backend, user, uid, social_user=None, *args, **kwargs): """Associate user social account with user instance.""" if social_user: return None try: social = UserSocialAuth.create_social_auth(user, uid, backend.name) except Exception as e: if not SOCIAL_AUTH_MODELS_MODULE.is_integrity_error(e): raise # Protect for possible race condition, those bastard with FTL # clicking capabilities, check issue #131: # https://github.com/omab/django-social-auth/issues/131 return social_auth_user(backend, uid, user, social_user=social_user, *args, **kwargs) else: return {'social_user': social, 'user': social.user}
def social_auth_user(backend, uid, user=None, *args, **kwargs): """Return UserSocialAuth account for backend/uid pair or None if it doesn't exists. Raise AuthAlreadyAssociated if UserSocialAuth entry belongs to another user. """ social_user = UserSocialAuth.get_social_auth(backend.name, uid) if social_user: if user and social_user.user != user: msg = ugettext('This %(provider)s account is already in use.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name }) elif not user: user = social_user.user return {'social_user': social_user, 'user': user}
def create_user(backend, details, response, uid, username, user=None, *args, **kwargs): """Create user. Depends on get_username pipeline.""" if user: return {'user': user} if not username: return None # NOTE: not return None because Django raises exception of strip email email = details.get('email') or '' return { 'user': UserSocialAuth.create_user(username=username, email=email), 'is_new': True }
def associate_user(backend, user, uid, social_user=None, *args, **kwargs): """Associate user social account with user instance.""" if social_user: return None try: social = UserSocialAuth.create_social_auth(user, uid, backend.name) except Exception as e: if not SOCIAL_AUTH_MODELS_MODULE.is_integrity_error(e): raise # Protect for possible race condition, those bastard with FTL # clicking capabilities, check issue #131: # https://github.com/omab/django-social-auth/issues/131 return social_auth_user(backend, uid, user, social_user=social_user, *args, **kwargs) else: return {'social_user': social, 'user': social.user}
def load_extra_data(backend, details, response, uid, user, social_user=None, *args, **kwargs): """Load extra data from provider and store it on current UserSocialAuth extra_data field. """ social_user = social_user or \ UserSocialAuth.get_social_auth(backend.name, uid) if social_user: extra_data = backend.extra_data(user, uid, response, details) if extra_data and social_user.extra_data != extra_data: if social_user.extra_data: social_user.extra_data.update(extra_data) else: social_user.extra_data = extra_data social_user.save() return {'social_user': social_user}
def get_user(self, user_id): """ Return user with given ID from the User model used by this backend """ return UserSocialAuth.get_user(user_id)
def modify(request): if request.user.is_authenticated(): if request.method == 'POST': sug = str(request.POST.get("suggestion").encode('utf-8')) article = get_object_or_404(ArticleDetails, id=request.POST.get("article")) feedbacks = Feedback.objects.filter( articledetails_id=request.POST.get("article"), email=request.POST.get("email"), name=request.POST.get("name")) for feedback in feedbacks: if feedback.suggestion.raw.encode('utf-8') == sug: return HttpResponse( simplejson.dumps({ 'duplicate': True, 'name': request.POST.get("name") })) Feedback(user=request.POST.get("user_id"), articledetails_id=request.POST.get("article"), suggestion=request.POST.get("suggestion"), email=request.POST.get("email"), name=request.POST.get("name")).save() feedback = Feedback.objects.filter( articledetails_id=request.POST.get("article"), suggestion=request.POST.get("suggestion"), email=request.POST.get("email"), name=request.POST.get("name")) article.feedback_count = article.feedback_count + 1 article.save() if request.user.username != "admin": # post on twitter or facebook if UserSocialAuth.auth_provider( request.user.username) == 'facebook': extra_data = UserSocialAuth.get_extra_data( request.user.username) access_token = extra_data['access_token'] # GraphAPI is the main class from facebook_sdp.py art = get_object_or_404(ArticleDetails, id=request.POST.get("article")) art_name = art.header.name.encode('utf-8') art_body = art.summary.raw.encode('utf-8') graph = facebook_sdk.GraphAPI(access_token) attachment = {} attachment['name'] = art_name attachment['link'] = shorten_url( settings.domain + "sharek/" + request.POST.get("class_slug") + "/" + request.POST.get("article_slug") + "/comment/" + str(feedback[0].id) + "/") attachment[ 'picture'] = settings.domain + settings.STATIC_URL + "images/facebook-thumb.jpg" attachment['description'] = art_body message = 'لقد شاركت في كتابة #دستور_مصر وقمت بالتعليق على ' + art_name + " من الدستور" graph.put_wall_post(message, attachment) if UserSocialAuth.auth_provider( request.user.username) == 'twitter': extra_data = UserSocialAuth.get_extra_data( request.user.username) access_token = extra_data['access_token'] access_token_secret = access_token[access_token.find('=') + 1:access_token.find('&' )] access_token_key = access_token[access_token.rfind('=') + 1:] api = twitter.Api( consumer_key=settings.TWITTER_CONSUMER_KEY, consumer_secret=settings.TWITTER_CONSUMER_SECRET, access_token_key=access_token_key, access_token_secret=access_token_secret) link = shorten_url(settings.domain + "sharek/" + request.POST.get("class_slug") + "/" + request.POST.get("article_slug") + "/comment/" + str(feedback[0].id) + "/") message = 'لقد شاركت في كتابة #دستور_مصر بالتعليق على ' + get_object_or_404( ArticleDetails, id=request.POST.get("article") ).header.name.encode('utf-8') + " " + link api.PostUpdate(message) return HttpResponse( simplejson.dumps({ 'date': str(feedback[0].date), 'id': feedback[0].id, 'suggestion': request.POST.get("suggestion") }))
def get_auth_provider(username): return UserSocialAuth.auth_provider(username)
def storeAssociation(self, server_url, association): """Store new assocition if doesn't exist""" UserSocialAuth.store_association(server_url, association)
def useNonce(self, server_url, timestamp, salt): """Generate one use number and return *if* it was created""" if abs(timestamp - time.time()) > SKEW: return False return UserSocialAuth.use_nonce(server_url, timestamp, salt)
def get_auth_provider(username): return UserSocialAuth.auth_provider(username)