def settings(request, settings_form=UserProfileForm): """ Presents the user a form with their settings, basically the register form minus username minus password. Also presents additional app-specific forms listed in the KSP_LOGIN_PROFILE_FORMS setting to the user. """ form_classes = [settings_form] + get_profile_forms() if request.method == "POST": forms = [ form(request.POST, user=request.user) for form in form_classes ] if all(form.is_valid() for form in forms): for form in forms: form.save() return redirect('account_settings') else: forms = [form(user=request.user) for form in form_classes] return render( request, 'ksp_login/settings.html', { 'account_associations': UserSocialAuth.get_social_auth_for_user(request.user), 'forms': forms, })
def download_sheet_with_user(user, filename='membership.csv'): """ Download the membership with a user's credentials :type user: users.models.User :param user: :return: boolean of successful download """ try: social = UserSocialAuth.get_social_auth_for_user(user).get() except UserSocialAuth.DoesNotExist: return False extra = social.extra_data expiry = datetime.utcnow() + timedelta(seconds=int(extra['expires'])) credentials = OAuth2Credentials(extra['access_token'], settings.SOCIAL_AUTH_GOOGLE_OAUTH2_KEY, settings.SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET, extra['refresh_token'], expiry, GOOGLE_TOKEN_URI, None, revoke_uri=GOOGLE_REVOKE_URI) service = build_service_from_credentials(credentials) try: file = service.files().get( fileId=settings.GOOGLE_MEMBERSHIP_FILE_ID).execute() except googleapiclient.errors.HttpError: return False url = file['exportLinks']['text/csv'] resp, content = service._http.request(url) open(filename, 'wb').write(content) return True
def download_sheet_with_user(user, filename="membership.csv"): """ Download the membership with a user's credentials :type user: users.models.User :param user: :return: boolean of successful download """ try: social = UserSocialAuth.get_social_auth_for_user(user).get() except UserSocialAuth.DoesNotExist: return False extra = social.extra_data expiry = datetime.utcnow() + timedelta(seconds=int(extra["expires"])) credentials = OAuth2Credentials( extra["access_token"], settings.SOCIAL_AUTH_GOOGLE_OAUTH2_KEY, settings.SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET, extra["refresh_token"], expiry, GOOGLE_TOKEN_URI, None, revoke_uri=GOOGLE_REVOKE_URI, ) service = build_service_from_credentials(credentials) try: file = service.files().get(fileId=settings.GOOGLE_MEMBERSHIP_FILE_ID).execute() except googleapiclient.errors.HttpError: return False url = file["exportLinks"]["text/csv"] resp, content = service._http.request(url) open(filename, "wb").write(content) return True
def box_detail(request, slug): if request.user.is_staff: box = get_object_or_404(Box.objects.select_related( 'units', 'instructor', 'links'), slug=slug) else: box = get_object_or_404(Box.published_boxes.select_related( 'units', 'instructor', 'links'), slug=slug) box.register_user(request.user) extra_context = {} extra_context['box'] = box extra_context['box_tags'] = box.get_tags() extra_context['search_form'] = LiveSearchForm() files = [] if box.drive_folder_url: config = SiteConfiguration.objects.get() access_token = UserSocialAuth.get_social_auth_for_user( request.user, provider='google-oauth2').get().tokens credentials = OAuth2Credentials(access_token, config.google_oauth2_key, config.google_oauth2_secret, None, None, None, None) # Create an httplib2.Http object and authorize it with our credentials http = httplib2.Http() http = credentials.authorize(http) drive_service = build('drive', 'v2', http=http) folder_id = box.drive_folder_url.split("/")[-1] page_token = None while True: try: param = {} if page_token: param['pageToken'] = page_token folder_files = drive_service.files().list( q='\'%s\' in parents' % folder_id, **param).execute() files.extend(folder_files['items']) page_token = folder_files.get('nextPageToken') if not page_token: break except: break extra_context['files'] = files return render_to_response('main/box_detail.html', extra_context, context_instance=RequestContext(request))
def get(self, request): socAuth = next( iter(UserSocialAuth.get_social_auth_for_user(request.user)), None) if not socAuth: return Response(status=HTTP_404_NOT_FOUND) else: return Response({"social_provider": socAuth.provider}, status=HTTP_200_OK)
def __init__(self, user, request=None, provider='google-oauth2'): self.user = user self.request = request self.provider = provider self.strategy = load_strategy(request) self.user_social = UserSocialAuth.get_social_auth_for_user(user=self.user, provider=self.provider)[0] self.backend = self.user_social.get_backend_instance(strategy=self.strategy)
def profile_image_for_user(user): try: auth = UserSocialAuth.get_social_auth_for_user(user)[0] backend = auth.get_backend().name if backend == "google-oauth2": return HttpResponseRedirect(auth.extra_data["image"]["url"]) elif backend == "facebook": return HttpResponseRedirect(fb_profile_image(auth.uid,50,50)) except Exception, e: pass
def __init__(self, user, request=None, provider='google-oauth2'): self.user = user self.request = request self.provider = provider self.strategy = load_strategy(request) self.user_social = UserSocialAuth.get_social_auth_for_user( user=self.user, provider=self.provider)[0] self.backend = self.user_social.get_backend_instance( strategy=self.strategy)
def get_large_user_image(user): try: auth = UserSocialAuth.get_social_auth_for_user(user)[0] backend = auth.get_backend().name if backend == "google-oauth2": url = auth.extra_data["image"]["url"] return HttpResponseRedirect("%s%i" % (url[:-2],200)) elif backend == "facebook": return HttpResponseRedirect(fb_profile_image(auth.uid,200,200)) except Exception, e: pass
def delete(self, request): # If this is a Google social account, revoke its Google tokens socAuth = next( iter(UserSocialAuth.get_social_auth_for_user(request.user)), None) if socAuth and socAuth.provider == 'google-oauth2': refresh_token = socAuth.extra_data.get( 'refresh_token', socAuth.extra_data['access_token']) makerequest.post( 'https://accounts.google.com/o/oauth2/revoke?token=' + refresh_token) request.user.delete() return Response(status=HTTP_200_OK)
def disconnect(request, backend, association_id): """ If the user has at least one other social account association or a valid password, disconnects the given social account, otherwise asks the user to set up a password before proceeding. """ associations = UserSocialAuth.get_social_auth_for_user(request.user) has_assoc = associations.exclude(id=association_id).count() has_pass = request.user.has_usable_password() if has_assoc or has_pass: return social_disconnect(request=request, backend=backend, association_id=association_id) return render(request, 'ksp_login/invalid_disconnect.html')
def disconnect(request, backend, association_id): """ If the user has at least one other social account association or a valid password, disconnects the given social account, otherwise asks the user to set up a password before proceeding. """ associations = UserSocialAuth.get_social_auth_for_user(request.user) has_assoc = associations.exclude(id=association_id).count() has_pass = request.user.has_usable_password() if has_assoc or has_pass: return social_disconnect(request=request, backend=backend, association_id=association_id) return render(request, 'ksp_login/invalid_disconnect.html')
def password(request): """ Sets, changes or removes the currently logged in user's passwords, depending on whether they have any social account associations. """ has_assoc = UserSocialAuth.get_social_auth_for_user(request.user).count() if request.user.has_usable_password(): def form(*args, **kwargs): return PasswordChangeForm(not has_assoc, *args, **kwargs) else: form = SetPasswordForm return password_change(request, post_change_redirect=reverse('account_settings'), password_change_form=form, template_name='ksp_login/password.html')
def password(request): """ Sets, changes or removes the currently logged in user's passwords, depending on whether they have any social account associations. """ has_assoc = UserSocialAuth.get_social_auth_for_user(request.user).count() if request.user.has_usable_password(): def form(*args, **kwargs): return PasswordChangeForm(not has_assoc, *args, **kwargs) else: form = SetPasswordForm return password_change(request, post_change_redirect=reverse('account_settings'), password_change_form=form, template_name='ksp_login/password.html')
def settings(request, settings_form=UserProfileForm): """ Presents the user a form with their settings, basically the register form minus username minus password. Also presents additional app-specific forms listed in the KSP_LOGIN_PROFILE_FORMS setting to the user. """ form_classes = [settings_form] + get_profile_forms() if request.method == "POST": forms = [form(request.POST, user=request.user) for form in form_classes] if all(form.is_valid() for form in forms): for form in forms: form.save() return redirect('account_settings') else: forms = [form(user=request.user) for form in form_classes] return render(request, 'ksp_login/settings.html', { 'account_associations': UserSocialAuth.get_social_auth_for_user(request.user), 'forms': forms, })