def authenticate(self, token=None, request=None): """ Reads in a Facebook code and asks Facebook if it's valid and what user it points to. """ args = { 'client_id': settings.FACEBOOK_APP_ID, 'client_secret': settings.FACEBOOK_APP_SECRET, 'redirect_uri': request.build_absolute_uri( reverse('facebook_callback')), 'code': token, } # Get a legit access token target = urllib.urlopen( 'https://graph.facebook.com/oauth/access_token?' + urllib.urlencode(args)).read() response = cgi.parse_qs(target) access_token = response['access_token'][-1] # Read the user's profile information fb_profile = urllib.urlopen( 'https://graph.facebook.com/me?access_token=%s' % access_token) fb_profile = json.load(fb_profile) try: # Try and find existing user fb_user = UserProfile.objects.get(facebook_id=fb_profile['id']) user = fb_user.user # Update access_token fb_user.access_token = access_token fb_user.save() except UserProfile.DoesNotExist: # No existing user if getattr(settings, 'FACEBOOK_FORCE_SIGNUP', False): # No existing user, use anonymous user = AnonymousUser() user.username = username user.first_name = fb_profile['first_name'] user.last_name = fb_profile['last_name'] fb_user = UserProfile( facebook_id=fb_profile['id'], access_token=access_token ) user.facebookprofile = fb_user else: # No existing user, create one user = User.objects.create_user(fb_profile['id'], fb_profile['email']) user.first_name = fb_profile['first_name'] user.last_name = fb_profile['last_name'] # with django-primate User has one field called 'name' instead # of first_name and last_name user.name = u'%s %s' % (user.first_name, user.last_name) user.save() # Create the UserProfile fb_user = UserProfile(user=user, facebook_id=fb_profile['id'], access_token=access_token) fb_user.save() return user
def authenticate_credentials(self, key): sys_name = self.VALID_TOKEN_USER_MAP.get(key) if not sys_name: raise AuthenticationFailed(_('Invalid token.')) user = AnonymousUser() user.username = sys_name return user, key
def authenticate(self, token=None, request=None): """ Reads in a Facebook code and asks Facebook if it's valid and what user it points to. """ args = { "client_id": settings.FACEBOOK_APP_ID, "client_secret": settings.FACEBOOK_APP_SECRET, "redirect_uri": request.build_absolute_uri("/facebook/authentication_callback"), "code": token, } # Get a legit access token target = urllib.urlopen("https://graph.facebook.com/oauth/access_token?" + urllib.urlencode(args)).read() response = cgi.parse_qs(target) access_token = response["access_token"][-1] # Read the user's profile information fb_profile = urllib.urlopen("https://graph.facebook.com/me?access_token=%s" % access_token) fb_profile = json.load(fb_profile) try: # Try and find existing user fb_user = FacebookProfile.objects.get(facebook_id=fb_profile["id"]) user = fb_user.user # Update access_token fb_user.access_token = access_token fb_user.save() except FacebookProfile.DoesNotExist: # No existing user # Not all users have usernames username = fb_profile.get("username", fb_profile["id"]) if getattr(settings, "FACEBOOK_FORCE_SIGNUP", False): # No existing user, use anonymous user = AnonymousUser() user.username = username user.first_name = fb_profile["first_name"] user.last_name = fb_profile["last_name"] fb_user = FacebookProfile(facebook_id=fb_profile["id"], access_token=access_token) user.facebookprofile = fb_user else: # No existing user, create one try: user = User.objects.create_user(username, fb_profile["email"]) except IntegrityError: # Username already exists, make it unique user = User.objects.create_user(username + fb_profile["id"], fb_profile["email"]) user.first_name = fb_profile["first_name"] user.last_name = fb_profile["last_name"] user.save() # Create the FacebookProfile fb_user = FacebookProfile(user=user, facebook_id=fb_profile["id"], access_token=access_token) fb_user.save() return user
def get_user(user_id): try: user = user_map[user_id] except KeyError: # When you've removed the user, the session may still # exist. user = AnonymousUser() user.username = '******' return user
def __call__(self, request): is_anon = request.META.get('HTTP_X_ANONYMOUS_CONSUMER', False) == 'true' user = AnonymousUser() if not is_anon: user_id = request.META.get('HTTP_X_AUTHENTICATED_USERID', False) user = User() user.id = user_id user.username = user_id request.user = user response = self.get_response(request) return response
def __call__(self, request): not_anonomous_user = request.META.get('HTTP_X_ANONYMOUS_CONSUMER', True) == 'false' user = AnonymousUser() if not_anonomous_user: user_id = request.META.get('HTTP_X_AUTHENTICATED_USERID', False) user = get_user_model()() user.id = user_id user.username = user_id user.first_name = user_id user.last_name = user_id request.user = user response = self.get_response(request) return response
def request_factory(method, user=None): """ 构造简单的request,用于操作日志 """ method = method.upper() assert method in ['GET', 'POST', 'PUT', 'DELETE'] if user is None: user = AnonymousUser() user.username = '******' user.role_name = '平台' class Meta: REMOTE_ADDR = '127.0.0.1' return type('Request', (object, ), { 'method': method, 'user': user, 'Meta': Meta })()
def create_request(is_post, url, data=None, is_anonymous=None, **kwargs): user = AnonymousUser() if not is_anonymous: user = mixer.blend('users.User') user.username = "******" user.set_password('123') for key, value in kwargs: setattr(user, key, value) user.save() factory = RequestFactory() request = factory.post(url, data) if is_post else factory.get(url) setattr(request, 'session', 'session') messages = FallbackStorage(request) setattr(request, '_messages', messages) request.user = user request = add_middleware_to_request(request, SessionMiddleware) request.session.save() return request
def get_user(request): """ Return the user model instance associated with the given request session. If no user is retrieved, return an instance of `AnonymousUser`. """ user = AnonymousUser() token = request.META.get('HTTP_AUTHORIZATION') if not token: return (user, 'token不存在', 400, ResCode.Token_Missing) start = time.time() try: result = requests.get(settings.SSO_VERIFY, verify=False, headers={'Authorization': token}) status_code = result.status_code result = result.json() except Exception as ex: logger.error('SSO登录授权验证失败:' + str(ex)) return (user, '服务器异常,登录授权验证失败', 500, ResCode.Token_Missing) end = time.time() logger.debug('sso verify time:{} ms'.format((end - start) * 1000)) rescode = result.get('rescode') if rescode == res_code['success']: user_data = result.get('data') user = User() user.id = user_data.get('id') user.username = user_data.get('username') user.mobile = user_data.get('mobile') user.email = user_data.get('email') user.user_type = user_data.get('user_type') user.is_subuser = user_data.get('is_subuser') user.main_user_id = user_data.get('main_user_id') user.permissions = user_data.get('permissions') return (user, result.get('msg'), status_code, rescode)
def authenticate(self, token=None, request=None): """ Reads in a Facebook code and asks Facebook if it's valid and what user it points to. """ #rebuild redirect_uri for user id or next url redirect_uri = request.build_absolute_uri('/facebook/authentication_callback') redirect_args = {} if request.GET.get('next'): redirect_args['next'] = request.GET.get('next') if request.GET.get('user'): redirect_args['user'] = str(request.user.id) if len(redirect_args) != 0: redirect_uri = redirect_uri + '?' + urllib.urlencode(redirect_args) args = { 'client_id': settings.FACEBOOK_APP_ID, 'client_secret': settings.FACEBOOK_APP_SECRET, 'redirect_uri': redirect_uri, 'code': token, } # Get a legit access token target = urllib.urlopen('https://graph.facebook.com/oauth/access_token?' + urllib.urlencode(args)).read() response = cgi.parse_qs(target) access_token = response['access_token'][-1] # Read the user's profile information fb_profile = urllib.urlopen('https://graph.facebook.com/me?access_token=%s' % access_token) fb_profile = json.load(fb_profile) #if user is just trying to connect facebook not full login if request.GET.get('user'): user = request.user try: # Try and find existing user fb_user = FacebookProfile.objects.get(facebook_id=fb_profile['id']) user = fb_user.user if request.user.id != user.id: return None except FacebookProfile.DoesNotExist: fb_user = FacebookProfile( user=user, facebook_id=fb_profile['id'], access_token=access_token ) fb_user.save() return user #full login try: # Try and find existing user fb_user = FacebookProfile.objects.get(facebook_id=fb_profile['id']) user = fb_user.user # Update access_token fb_user.access_token = access_token fb_user.save() except FacebookProfile.DoesNotExist: # Not all users have usernames username = fb_profile.get('username', fb_profile['email'].split('@')[0]) if getattr(settings, 'FACEBOOK_FORCE_SIGNUP', False): user = AnonymousUser() user.signup_required = True user.username = username user.first_name = fb_profile['first_name'] user.last_name = fb_profile['last_name'] fb_user = FacebookProfile( facebook_id=fb_profile['id'], access_token=access_token ) user.facebookprofile = fb_user else: if getattr(settings, 'FACEBOOK_FORCE_VERIFICATION', False) and \ User.objects.filter(email__iexact=fb_profile['email']).exists(): user = AnonymousUser() user.verification_required = True user.email = fb_profile['email'] user.facebookprofile = FacebookProfile( facebook_id=fb_profile['id'], access_token=access_token ) else: try: user = User.objects.create_user(username, fb_profile['email']) except IntegrityError: # Username already exists, make it unique user = User.objects.create_user(username + fb_profile['id'], fb_profile['email']) user.first_name = fb_profile['first_name'] user.last_name = fb_profile['last_name'] user.save() # Create the FacebookProfile fb_user = FacebookProfile(user=user, facebook_id=fb_profile['id'], access_token=access_token) fb_user.save() return user
def authenticate(self, token=None, request=None): """ Reads in a Facebook code and asks Facebook if it's valid and what user it points to. """ args = { 'client_id': settings.FACEBOOK_APP_ID, 'client_secret': settings.FACEBOOK_APP_SECRET, 'redirect_uri': request.build_absolute_uri(reverse('facebook-callback')), 'code': token, } # Get a legit access token target = urllib.urlopen( 'https://graph.facebook.com/oauth/access_token?' + urllib.urlencode(args)).read() response = cgi.parse_qs(target) access_token = response['access_token'][-1] # Read the user's profile information fb_profile = urllib.urlopen( 'https://graph.facebook.com/me?access_token=%s' % access_token) fb_profile = json.load(fb_profile) try: # Try and find existing user fb_user = FacebookProfile.objects.get(facebook_id=fb_profile['id']) user = fb_user.user # Update access_token fb_user.access_token = access_token fb_user.save() except FacebookProfile.DoesNotExist: # No existing user if getattr(settings, 'FACEBOOK_FORCE_SIGNUP', False): # No existing user, use anonymous user = AnonymousUser() user.username = username user.first_name = fb_profile['first_name'] user.last_name = fb_profile['last_name'] fb_user = FacebookProfile(facebook_id=fb_profile['id'], access_token=access_token) user.facebookprofile = fb_user else: # No existing user, create one user = User.objects.create_user(fb_profile['id'], fb_profile['email']) user.first_name = fb_profile['first_name'] user.last_name = fb_profile['last_name'] # Facebook allows for longer name. This fixes the inconsistencies between # Django and Postgres if len(user.first_name) > 30: user.first_name = user.first_name[:30] if len(user.last_name) > 30: user.last_name = user.last_name[:30] # with django-primate User has one field called 'name' instead # of first_name and last_name user.name = u'%s %s' % (user.first_name, user.last_name) user.save() # Create the FacebookProfile fb_user = FacebookProfile(user=user, facebook_id=fb_profile['id'], access_token=access_token) fb_user.save() return user
def authenticate(self, token=None, request=None): """ Reads in a Facebook code and asks Facebook if it's valid and what user it points to. """ args = { 'client_id': settings.FACEBOOK_APP_ID, 'client_secret': settings.FACEBOOK_APP_SECRET, 'redirect_uri': request.build_absolute_uri('/facebook/authentication_callback'), 'code': token, } # Get a legit access token target = urllib.urlopen( 'https://graph.facebook.com/oauth/access_token?' + urllib.urlencode(args)).read() response = cgi.parse_qs(target) access_token = response['access_token'][-1] # Read the user's profile information fb_profile = urllib.urlopen( 'https://graph.facebook.com/me?access_token=%s' % access_token) fb_profile = json.load(fb_profile) try: # Try and find existing user fb_user = FacebookProfile.objects.get(facebook_id=fb_profile['id']) user = fb_user.user # Update access_token fb_user.access_token = access_token fb_user.save() except FacebookProfile.DoesNotExist: # No existing user # Not all users have usernames username = fb_profile.get('username', fb_profile['email'].split('@')[0]) if getattr(settings, 'FACEBOOK_FORCE_SIGNUP', False): # No existing user, use anonymous user = AnonymousUser() user.username = username user.first_name = fb_profile['first_name'] user.last_name = fb_profile['last_name'] fb_user = FacebookProfile(facebook_id=fb_profile['id'], access_token=access_token) user.facebookprofile = fb_user else: # No existing user, create one try: user = User.objects.create_user(username, fb_profile['email']) except IntegrityError: # Username already exists, make it unique user = User.objects.create_user( username + fb_profile['id'], fb_profile['email']) user.first_name = fb_profile['first_name'] user.last_name = fb_profile['last_name'] user.save() # Create the FacebookProfile fb_user = FacebookProfile(user=user, facebook_id=fb_profile['id'], access_token=access_token) fb_user.save() return user
def getAnonUser(self, username): """ Returns an anonymous user """ user = AnonymousUser() user.username = username return
def get_anonymous(self): """ Renvoyer l'utilisateur anonyme """ user = AnonymousUser() user.username = settings.ANONYMOUS_USER_NAME return user
def authenticate(self, token=None, request=None): """ Reads in a Facebook code and asks Facebook if it's valid and what user it points to. """ args = { 'client_id': settings.FACEBOOK_APP_ID, 'client_secret': settings.FACEBOOK_APP_SECRET, 'redirect_uri': request.build_absolute_uri('/facebook/authentication_callback'), 'code': token, } # Get a legit access token target = urllib.urlopen('https://graph.facebook.com/oauth/access_token?' + urllib.urlencode(args)).read() response = cgi.parse_qs(target) access_token = response['access_token'][-1] # Read the user's profile information fb_profile = urllib.urlopen('https://graph.facebook.com/me?access_token=%s' % access_token) fb_profile = json.load(fb_profile) fb_friends = urllib.urlopen('https://graph.facebook.com/me/friends?access_token=%s' % access_token) fb_friends = json.load(fb_friends) try: # Try and find existing user fb_user = FacebookProfile.objects.get(facebook_id=fb_profile['id']) user = fb_user.user # Update access_token fb_user.access_token = access_token fb_user.save() FacebookFriends.objects.filter(user=user).delete() for friend in fb_friends['data']: FacebookFriends.objects.create(user=user,facebook_id=friend['id'],name=friend['name']) except FacebookProfile.DoesNotExist: # No existing user # Not all users have usernames username = fb_profile.get('username', fb_profile['email'].split('@')[0]) if getattr(settings, 'FACEBOOK_FORCE_SIGNUP', False): # No existing user, use anonymous user = AnonymousUser() user.username = username user.first_name = fb_profile['first_name'] user.last_name = fb_profile['last_name'] fb_user = FacebookProfile( facebook_id=fb_profile['id'], access_token=access_token ) user.facebookprofile = fb_user else: # No existing user, create one try: user = User.objects.create_user(username, fb_profile['email']) except IntegrityError: # Username already exists, make it unique user = User.objects.create_user(username + fb_profile['id'], fb_profile['email']) user.first_name = fb_profile['first_name'] user.last_name = fb_profile['last_name'] user.save() # Create the FacebookProfile fb_user = FacebookProfile(user=user, facebook_id=fb_profile['id'], access_token=access_token) fb_user.save() return user
def authenticate(self, token=None, request=None): """ Reads in a Facebook code and asks Facebook if it's valid and what user it points to. """ args = { 'client_id': settings.FACEBOOK_APP_ID, 'client_secret': settings.FACEBOOK_APP_SECRET, 'redirect_uri': request.build_absolute_uri('/facebook/authentication_callback'), 'code': token, } # Get a legit access token target = urllib.urlopen('https://graph.facebook.com/oauth/access_token?' + urllib.urlencode(args)).read() response = cgi.parse_qs(target) access_token = response['access_token'][-1] # Read the user's profile information fb_profile = urllib.urlopen('https://graph.facebook.com/me?access_token=%s' % access_token) fb_profile = json.load(fb_profile) try: # Try and find existing user fb_user = FacebookProfile.objects.get(facebook_id=fb_profile['id']) user = fb_user.user # Update access_token fb_user.access_token = access_token fb_user.save() except FacebookProfile.DoesNotExist: # No existing user # Not all users have usernames username = (fb_profile['first_name']+fb_profile['last_name']).lower() if getattr(settings, 'FACEBOOK_FORCE_SIGNUP', False): # No existing user, use anonymous user = AnonymousUser() user.username = username user.first_name = fb_profile['first_name'] user.last_name = fb_profile['last_name'] fb_user = FacebookProfile( facebook_id=fb_profile['id'], access_token=access_token ) user.facebookprofile = fb_user else: # No existing user, create one try: user = User.objects.create_user(username, fb_profile['email']) except IntegrityError: # Username already exists, make it unique user = User.objects.create_user(username + fb_profile['id'], fb_profile['email']) user.first_name = fb_profile['first_name'] user.last_name = fb_profile['last_name'] user.save() image_url = 'https://graph.facebook.com/'+fb_profile['id']+'/picture?access_token='+access_token+'&type=large' savepath = 'media/members/'+fb_profile['id']+'.jpg' urllib.urlretrieve(image_url, savepath) #enregistrer l'image dans media/members profile = get_object_or_404(Profile, user=user) profile.email = fb_profile['email'] #profile.city = fb_profile['location']['name'] profile.avatar = 'members/'+fb_profile['id']+'.jpg' profile.save() # Create the FacebookProfile fb_user = FacebookProfile(user=user, facebook_id=fb_profile['id'], access_token=access_token) fb_user.save() return user
def authenticate(self, token=None, request=None,redirect_uri='/'): """ Reads in a Facebook code and asks Facebook if it's valid and what user it points to. """ args = { 'client_id': settings.FACEBOOK_APP_ID, 'client_secret': settings.FACEBOOK_APP_SECRET, 'redirect_uri': request.build_absolute_uri( redirect_uri ), 'code': token, } # Get Model to use appmodel = settings.AUTH_PROFILE_MODULE.split(".") FacebookProfile = get_model(appmodel[0],appmodel[1]) # Get a legit access token target = urllib.urlopen('https://graph.facebook.com/oauth/access_token?' + urllib.urlencode(args)).read() response = cgi.parse_qs(target) try: access_token = response['access_token'][-1] except KeyError: mail_admins("ERR",response) return None # Read the user's profile information fb_profile = urllib.urlopen('https://graph.facebook.com/me?fields=id,first_name,last_name,email,name&access_token=%s' % access_token) fb_profile = json.load(fb_profile) try: # Try and find existing user fb_user = FacebookProfile.objects.get(facebook_id=fb_profile['id']) user = fb_user.user # Update access_token fb_user.access_token = access_token fb_user.save() except FacebookProfile.DoesNotExist: # No existing user # Not all users have usernames username = fb_profile.get('username', fb_profile['email'].split('@')[0]) if getattr(settings, 'FACEBOOK_FORCE_SIGNUP', False): # No existing user, use anonymous user = AnonymousUser() user.username = username user.first_name = fb_profile['first_name'] user.last_name = fb_profile['last_name'] fb_user = FacebookProfile( facebook_id=fb_profile['id'], access_token=access_token ) user.facebookprofile = fb_user else: # No existing user, create one try: user = User.objects.create_user(username, fb_profile['email']) except IntegrityError: # Username already exists, make it unique user = User.objects.create_user(username + fb_profile['id'], fb_profile['email']) user.first_name = fb_profile['first_name'] user.last_name = fb_profile['last_name'] user.save() # Create the FacebookProfile fb_user = FacebookProfile(user=user, facebook_id=fb_profile['id'], access_token=access_token) fb_user.save() return user