def syncGoogleAccount(request): if request.method == 'POST': oldUserID = request.POST['oldUserID'] newUserID = request.POST['newUserID'] if User.objects.filter(id=oldUserID): resetThisUser = User.objects.get(id=oldUserID) else: return HttpResponse(json.dumps({'error':'Sorry, we are having an issue linking your google account.'})) if User.objects.filter(id=newUserID): deleteThisUser = User.objects.get(id=newUserID) else: return HttpResponse(json.dumps({'error':'Sorry, we are having an issue linking your google account.'})) #reset google account to oldUserID and delete newUserID if GoogleUserInfo.objects.filter(user=deleteThisUser): googleAccount = GoogleUserInfo.objects.get(user=deleteThisUser) #get the storage from deleteUser oldStorage = Storage(CredentialsModel, 'id', deleteThisUser, 'credential') credential = oldStorage.get() #create a new storage for resetUser newStorage = Storage(CredentialsModel, 'id', resetThisUser, 'credential') newStorage.put(credential) #delete old credential for deleteUser oldStorage.delete() #reset email from deleteUser to resetUser to make them the same resetThisUser.email = deleteThisUser.email resetThisUser.save() #log in resetUser resetThisUser.backend = 'django.contrib.auth.backends.ModelBackend' login(request, resetThisUser) #set new userID for session request.session['user_id'] = resetThisUser.id request.session.set_expiry(604800) #set to old account googleAccount.user = resetThisUser googleAccount.save() #delete deleteUser deleteThisUser.delete() data = {'success':'success'} else: return HttpResponse(json.dumps({'error':'Sorry, we are having an issue linking your google account.'})) else: data = {'error':'Did not post correctly'} return HttpResponse(json.dumps(data))
def getAllStudentsOrgUnit(user): #adminUser = User.objects.get(email='*****@*****.**') storage = Storage(CredentialsModel, 'id', user, 'credential') credential = storage.get() if credential is None or credential.invalid == True: #return HttpResponseRedirect("/login/") return False else: http = httplib2.Http() http = credential.authorize(http) directory_service = build("admin", "directory_v1", http=http) all_users = [] page_token = None params = {'domain': 'student.alvaradoisd.net', 'fields':'nextPageToken,users(name,id,orgUnitPath,primaryEmail)'} while True: try: if page_token: params['pageToken'] = page_token current_page = directory_service.users().list(**params).execute() all_users.extend(current_page['users']) page_token = current_page.get('nextPageToken') if not page_token: break except errors.HttpError as error: return 'An error occurred: %s' % error break return all_users
def driveUpload(user, FILENAME): storage = Storage(CredentialsModel, 'id', user, 'credential') credential = storage.get() if credential is None or credential.invalid == True: #return HttpResponseRedirect("/login/") return render_to_response('google-login-wait.html', {}) else: # Path to the file to upload #FILENAME = filePath fdir, fname = os.path.split(FILENAME) http = httplib2.Http() http = credential.authorize(http) drive_service = build("drive", "v2", http=http) # Insert a file media_body = MediaFileUpload(FILENAME, mimetype='application/sst', resumable=True) body = { 'title': fname, 'description': 'Simple Sheets Worksheet', 'mimeType': 'application/sst' } file = drive_service.files().insert(body=body, media_body=media_body).execute() return file['id']
def auth_return(request): if 'state' not in request.REQUEST or not xsrfutil.validate_token( settings.SECRET_KEY, str(request.REQUEST['state']), request.user): return HttpResponseBadRequest() credential = FLOW.step2_exchange(request.REQUEST) http = httplib2.Http() http = credential.authorize(http) (resp_headers, content) = http.request('https://www.googleapis.com/oauth2/v1/userinfo', 'GET') content = loads(content) try: profile = Profile.objects.get(google_plus_id=content['id']) request_profile = request.get_user().profile if request.user.is_authenticated(): request.log_action('google_plus.merge', {'id': content['id']}, profile) profile.merge_from_other(request_profile) user = profile.user request.set_user(user) except Profile.DoesNotExist: user = request.get_user() profile = user.profile storage = Storage(CredentialsModel, 'id', request.user, 'credential') storage.put(credential) profile.update_from_google_plus_data(credential, content) request.log_action('google_plus.connect', {'data': content}, profile) next_uri = '/' if 'google_plus_next' in request.session: next_uri = request.session['google_plus_next'] del request.session['google_plus_next'] request.session.modified = True return HttpResponseRedirect(next_uri)
def init_gclient(self): storage = Storage(CredentialsModel, 'id', self._user, 'credential') credential = storage.get() if credential is None or credential.invalid == True: raise InvalidCredentialException() else: self.client = get_gclient(credential)
def auth(request): # use the first REDIRECT_URI if you are developing your app locally, and the second in production #REDIRECT_URI = 'http://localhost:8000/gmail_setup/callback' REDIRECT_URI = "http://%s%s" % (BASE_URL, reverse("oauth2:return")) #REDIRECT_URI = 'https://' + BASE_URL + '/gmail_setup/callback' print "ACCESSING CLIENT SECRETS" with open(CLIENT_SECRETS) as json_data: d = json.load(json_data) print "DATA:", d FLOW = flow_from_clientsecrets( CLIENT_SECRETS, scope= 'https://www.googleapis.com/auth/contacts.readonly https://www.googleapis.com/auth/gmail.readonly https://www.googleapis.com/auth/gmail.settings.basic https://www.googleapis.com/auth/gmail.modify', redirect_uri=REDIRECT_URI) FLOW.params['access_type'] = 'offline' user = request.user storage = Storage(CredentialsModel, 'id', user, 'credential') credential = storage.get() if not credential or credential.invalid: if 'group' in request.GET: group_name = request.GET['group'] FLOW.params['state'] = xsrfutil.generate_token( settings.SECRET_KEY, user) + '___' + group_name authorize_url = FLOW.step1_get_authorize_url() f = FlowModel(id=user, flow=FLOW) f.save() return HttpResponseRedirect(authorize_url) else: return HttpResponseRedirect("/gmail_setup") else: return HttpResponseRedirect("/gmail_setup")
def oauth_callback(request): from oauth2client.client import OAuth2WebServerFlow from auth.models import CredentialsModel from oauth2client.django_orm import Storage #Get query code from auth request code = request.GET.get('code') #create flow object flow = OAuth2WebServerFlow( client_id= '940056909424-57b143selist3s7uj8rnpcmt7f2s0g7u.apps.googleusercontent.com', client_secret='mgHATY9kYzp3HEHg2xKrYzmh', scope=[ 'https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/drive' ], redirect_uri='http://localhost:8000/oauth2callback') #retrieve and store credentials credentials = flow.step2_exchange(code) storage = Storage(CredentialsModel, 'id', request.user, 'credential') storage.put(credentials) #mark user has having been validated user = request.user user_profile = user.get_profile() user_profile.google_validated = True user_profile.save() return HttpResponseRedirect('/index.html')
def index(request): storage = Storage(CredentialsModel, 'id', request.user, 'credential') credential = storage.get() if credential is None or credential.invalid == True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() return render(request, 'utube/index.html', {'login_url': authorize_url}) else: user = AuthUser.objects.get(pk=request.user.id) video_count = user.uservideo_set.count() print video_count if not video_count: http = httplib2.Http() http = credential.authorize(http) service = build('youtube', 'v3', http=http) update_user_infos(user, service) videos = Video.objects.raw( ''' SELECT DISTINCT v.* FROM utube_video v LEFT JOIN utube_uservideo uv ON uv.video_id = v.youtube_id WHERE uv.user_id = %s ''', [user.id]) return render(request, 'utube/index.html', {'videos': videos})
def get_credentials(self): """ gets credentials from Storage """ storage = Storage(Credentials, 'id', self.request.user, 'credential') credentials = storage.get() return credentials
def checkAuth(request): """Checks OAuth status of user, if not initiates exchange with google's OAuth server """ REDIRECT_URI = "http://%s%s" % (request.get_host(), reverse("oauth2return")) FLOW = flow_from_clientsecrets( CLIENT_SECRETS, scope='https://www.googleapis.com/auth/calendar.readonly', redirect_uri=REDIRECT_URI ) user = request.user storage = Storage(CredentialsModel, 'id', user, 'credential') credential = storage.get() if credential is None or credential.invalid is True or not user.userPointer.isOAuthed: FLOW.params['state'] = xsrfutil.generate_token( settings.SECRET_KEY, user) authorize_url = FLOW.step1_get_authorize_url() f = FlowModel(id=user, flow=FLOW) f.save() calUser = CalendarUser.objects.get(user=user) calUser.isOAuthed = True calUser.save() return HttpResponseRedirect(authorize_url) else: return HttpResponseRedirect(reverse('main'))
def _get_user_credentials(self, user): from orders_manager.models import CredentialsModel user = user if not hasattr(user, 'user') else user.user try: storage = Storage(CredentialsModel, 'id', user, 'credential') credential = storage.get() except: raise ValueError('Credentials for user \'%s\' was not found!' % user.profile.get_full_name()) if not credential: raise ValueError('User \'%s\' has no credentials' % user.profile.get_full_name()) if credential.invalid: raise ValueError('Credentials are invalid for user \'%s\'!' % user.profile.get_full_name()) try: if credential.access_token_expired: http = credential.authorize(httplib2.Http()) credential.refresh(http) except Exception as ex: raise ValueError('Bad user credentials! ' + ex.args[0]) return credential
def get_credentials(gmail_account): """ Get the credentials for the given EmailAccount, what should be a Gmail account. If there are no valid credentials for the account, is_authorized is set to False and there will be an InvalidCredentialsError raised. Arguments: gmail_account (instance): EmailAccount instance Returns: credentials for the EmailAccount Raises: InvalidCredentialsError, if there are no valid credentials for the account. """ storage = Storage(GmailCredentialsModel, 'id', gmail_account, 'credentials') credentials = storage.get() if credentials is not None and credentials.invalid is False: return credentials else: gmail_account.is_authorized = False gmail_account.save() logger.error('no credentials for account %s' % gmail_account) raise InvalidCredentialsError('no credentials for account %s' % gmail_account)
def index(request): storage = Storage(CredentialsModel, 'user', request.user, 'credential') credential = storage.get() if credential is None or credential.invalid == True: request.session["scope"] = "admin.directory.user" FLOW = get_flow("admin.directory.user") FLOW.params['state'] = xsrfutil.generate_token( settings.SECRET_KEY, request.user ) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build("admin", "directory_v1", http=http) results = service.users().list( customer='carthage.edu', maxResults=10, orderBy='email', viewType='domain_public' ).execute() return render( request, 'directory/index.html', {'users': users,} )
def get(self, *args, **kwargs): if not xsrfutil.validate_token( settings.SECRET_KEY, self.request.GET['state'], self.request.user): return HttpResponseBadRequest() credential = self.FLOW.step2_exchange(self.request.GET) storage = Storage(Credential, 'id', self.request.user, 'credential') storage.put(credential) return HttpResponseRedirect(reverse("adsense"))
def get_stored_credential(request): google_id = None credential = None if request.session.get('google_id', False): google_id = str(request.session.get('google_id')) storage = Storage(CredentialsModel, 'id', google_id, 'credential') credential = storage.get() return credential
def update_user_credentials(self, new_credential): from orders_manager.models import CredentialsModel, User user = User.objects.get( email=self.get_google_user_email(new_credential)) storage = Storage(CredentialsModel, 'id', user, 'credential') storage.put(new_credential) return storage.get()
def auth_return(request): if not xsrfutil.validate_token(settings.SECRET_KEY, request.REQUEST['state'], request.user): return HttpResponseBadRequest() credential = FLOW.step2_exchange(request.REQUEST) storage = Storage(CredentialsModel, 'id', request.user, 'credential') storage.put(credential) return HttpResponseRedirect("gtasks/")
def handle(self, *args, **options): config = { u'metrics': [ u'annotationClickThroughRate', u'annotationCloseRate', u'averageViewDuration', u'comments', u'dislikes', u'estimatedMinutesWatched', u'favoritesAdded', u'favoritesRemoved', u'likes', u'shares', u'subscribersGained', u'subscribersLost', u'views', ], u'dimensions': [ u'day', ], u'start_date': u'2014-03-01', u'end_date': u'2014-03-19', u'start_index': 1, u'max_results': 100, } if args: aycs = AnalyticsYoutubeChannel.objects.filter( youtube_channel__youtube_id__in=args, first_load=False, deleted=False) else: aycs = AnalyticsYoutubeChannel.objects.filter(first_load=False, deleted=False) for ayc in aycs: storage = Storage(AnalyticsYoutubeChannel, 'email', ayc.email, 'credential') credential = storage.get() if credential is None or credential.invalid == True: CommandError(u'YoutubeConnection is invalid') http = httplib2.Http() http = credential.authorize(http) service = build('youtubeAnalytics', 'v1', http=http) analytics_response = service.reports().query( ids="channel==%s" % ayc.youtube_channel.youtube_id, metrics=u','.join(config[u'metrics']), dimensions=u','.join(config[u'dimensions']), start_date=config[u'start_date'], end_date=config[u'end_date'], start_index=config[u'start_index'], max_results=config[u'max_results'], ).execute() for column_header in analytics_response.get("columnHeaders", []): print "%-20s" % column_header["name"], for row in analytics_response.get("rows", []): for value in row: print "%-20s" % value,
def table2sql(request, id=0): bucket_name = '' if id: storage = Storage(CredentialsModel, 'id', request.user, 'credential') credential = storage.get() http1 = httplib2.Http() http2 = credential.authorize(http1) service = build("drive", "v2", http=http2) # files = service.files().list().execute() # request = service.files().get_media(fileId=id) # local_fd = open('workfile', 'w'); # media_request = http.MediaIoBaseDownload(local_fd, request) # close f; # Retry transport and file IO errors. RETRYABLE_ERRORS = (httplib2.HttpLib2Error, IOError) # Number of times to retry failed downloads. NUM_RETRIES = 5 # Number of bytes to send/receive in each request. CHUNKSIZE = 2 * 1024 * 1024 # Mimetype to use if one can't be guessed from the file extension. DEFAULT_MIMETYPE = 'application/octet-stream' print 'Building download request...' filename = 'xxx' f = file(filename, 'w') request = service.files().get_media(fileId=id) media = http.MediaIoBaseDownload(f, request, chunksize=CHUNKSIZE) print 'Downloading bucket: %s object: %s to file: %s' % (bucket_name, id, filename) progressless_iters = 0 done = False while not done: error = None try: progress, done = media.next_chunk() if progress: print_with_carriage_return('Download %d%%.' % int(progress.progress() * 100)) except HttpError, err: error = err if err.resp.status < 500: raise except RETRYABLE_ERRORS, err: error = err if error: progressless_iters += 1 handle_progressless_iter(error, progressless_iters) else: progressless_iters = 0
def confirm_authentication(view, login_form_uri=None, login_post_uri=None, login_done_uri=None, continuation_url=None, scope=SCOPE_DEFAULT): """ Return None if required authentication is present, otherwise a login redirection response to the supplied URI view.credential is set to credential that can be used to access resource """ if view.request.user.is_authenticated(): storage = Storage(CredentialsModel, 'id', view.request.user, 'credential') view.credential = storage.get() # log.info("view.credential %r"%(view.credential,)) if view.credential is not None: if not view.credential.invalid: return None # Valid credential present: proceed... else: # Django login with local credential: check for user email address # # @@TODO: is this safe? # # NOTE: currently, view.credential is provided by the oauth2 and used # only for the .invalid test above. If it is ever used by other # application components, it may be necessary to construct a # credential for local logins. In the long run, if credentials will # be used to access third party services or resources, it may not be # possible to use non-Oauth2 credentials here. In the meanwhile, # allowing local Django user credentials provides an easier route for # getting a software instance installed for evaluation purposes. # if view.request.user.email: return None # Assume valid login: proceed... else: return error400values(view, "Local user has no email address") if not login_form_uri: return error400values(view, "No login form URI specified") if not login_done_uri: return error400values(view, "No login completion URI specified") if not login_post_uri: login_post_uri = login_form_uri if not continuation_url: continuation_url = view.request.path # Redirect to initiate login sequence view.request.session['login_form_uri'] = login_form_uri view.request.session['login_post_uri'] = login_post_uri view.request.session['login_done_uri'] = login_done_uri view.request.session['continuation_url'] = continuation_url view.request.session['oauth2_scope'] = scope query_params = ({ "continuation": continuation_url, "scope": scope, "message": "" }) return HttpResponseRedirectWithQuery(login_form_uri, query_params)
def update_gmail_filter(user, group_name, whitelist_emails, filter_hash): storage = Storage(CredentialsModel, 'id', user, 'credential') credential = storage.get() http = httplib2.Http() http = credential.authorize(http) service_mail = build('gmail', 'v1', http=http) forward_address = '%s@%s' % (group_name, BASE_URL) return True
def auth_return(request): ans = xsrfutil.validate_token(settings.SECRET_KEY, str(request.REQUEST['state']), request.user) if not ans: return HttpResponseBadRequest() credential = FLOW.step2_exchange(request.REQUEST) storage = Storage(CredentialsModel, 'id', request.user, 'credential') storage.put(credential) return HttpResponseRedirect(reverse('contactos:registrar_recordatorio'))
def logout(request): u = request.user f = FlowModel.objects.get(id=u.id) f.delete() c = CredentialsModel.objects.get(id=u.id) c.delete() storage = Storage(CredentialsModel, 'id', u, 'credential') storage.delete() return HttpResponseRedirect("http://accounts.google.com/logout")
def index(request): REDIRECT_URI = 'http://localhost:8000/oauth2/oauth2callback' # REDIRECT_URI = "https://%s%s" % ( # get_current_site(request).domain, reverse("oauth2:return")) FLOW = flow_from_clientsecrets( CLIENT_SECRETS, scope='https://www.googleapis.com/auth/youtube.readonly', redirect_uri=REDIRECT_URI ) user = request.user storage = Storage(CredentialsModel, 'id', user, 'credential') credential = storage.get() if credential is None or credential.invalid is True: FLOW.params['state'] = xsrfutil.generate_token( settings.SECRET_KEY, user) authorize_url = FLOW.step1_get_authorize_url() f = FlowModel(id=user, flow=FLOW) f.save() return HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, http=http) channels_response = youtube.channels().list( mine=True, part="contentDetails" ).execute() for channel in channels_response["items"]: wh_list_id = channel["contentDetails"]["relatedPlaylists"]["watchHistory"] playlistitems_list_response = youtube.playlistItems().list( playlistId=wh_list_id, part="snippet", maxResults=50, ).execute() video_id = [] for playlist_item in playlistitems_list_response["items"]: video_id.append(playlist_item["snippet"]["resourceId"]["videoId"]) video_ids = ','.join(video_id) video_response = youtube.videos().list( id=video_ids, part='snippet', ).execute() titles = [] video_id = [] for vr in video_response['items']: if vr['snippet']['categoryId'] == "10": titles.append(vr["snippet"]["title"]) video_id.append("https://www.youtube.com/watch?v=" + vr['id']) details = zip(titles, video_id) # pdb.set_trace() return details
def get_storage_flow_secret(scope): flow = flow_from_clientsecrets( scope_secret, scope=scope_urls[scope], redirect_uri=settings.YOUTUBE_REDIRECT_URL + scope, ) storage = Storage(CredentialsModel, 'id', scope_users[scope], 'credential') credential = storage.get() return flow, credential
def get_service(): user = User.objects.get(username='******') storage = Storage(CredentialsModel, 'id', user, 'credential') credential = storage.get() http = httplib2.Http() http = credential.authorize(http) service = build("analytics", "v3", http=http) return service
def callback(request): # if not xsrfutil.validate_token(settings.SECRET_KEY, request.GET['state'], # request.user): # return HttpResponseBadRequest() credential = FLOW.step2_exchange(request.GET) print credential storage = Storage(CredentialsModel, 'id', request.user, 'credential') storage.put(credential) return redirect('/utube')
def store(self): """ stores credentials in the Credentials Model """ flow = self.get_flow() credential = flow.flow.step2_exchange(self.request.REQUEST) storage = Storage(Credentials, 'id', self.request.user, 'credential') storage.put(credential) self.delete_flow(flow)
def google_auth(request): """ Handles Google oauth flow. For details, visit https://developers.google.com/api-client-library/python/guide/aaa_oauth#OAuth2WebServerFlow https://developers.google.com/api-client-library/python/guide/django """ flow = None default_flow = OAuth2WebServerFlow( client_id=settings.GOOGLE_CALENDAR_API_CLIENT_ID, client_secret=settings.GOOGLE_CALENDAR_API_CLIENT_SECRET, scope=['https://www.googleapis.com/auth/calendar', 'profile', 'email'], redirect_uri=settings.BASE_URL + '/auth/google') default_flow.params['access_type'] = 'offline' default_flow.params['include_granted_scopes'] = 'true' default_flow.params['prompt'] = 'consent' # Try to retrieve an existing flow, or create one if it doesn't exist gflow = GoogleFlow.objects.filter(id=request.user).last() if gflow and gflow.flow.params.get('prompt') != 'consent': # Delete any flows that don't have the prompt parameter set, since that will # prevent the credentials from getting a refresh token gflow.delete() gflow = None if not gflow: # print "Could not retrieve existing flow" gflow = GoogleFlow(id=request.user, flow=default_flow) gflow.save() flow = gflow.flow code = request.GET.get('code', None) error = request.GET.get('error', None) if error: # TODO eventually make this prettier, like redirect to some landing page return HttpResponseBadRequest( "Authentication failed. Reason: {}".format(error)) elif code: credential = flow.step2_exchange(code) # Save the credentials storage = Storage(GoogleCredentials, 'user', request.user, 'credential') storage.put(credential) profile, _ = Profile.get_or_create(user=request.user) profile.authed = True profile.save() # TODO improve the latency over here request.user.googlecredentials.import_calendars() return HttpResponseRedirect("/") else: auth_uri = flow.step1_get_authorize_url() return HttpResponseRedirect(auth_uri)
def auth_return(request): user = request.user if not xsrfutil.validate_token( settings.SECRET_KEY, str(request.GET['state']), user): return HttpResponseBadRequest() FLOW = FlowModel.objects.get(id=user).flow credential = FLOW.step2_exchange(request.GET) storage = Storage(CredentialsModel, 'id', user, 'credential') storage.put(credential) return HttpResponseRedirect("/oauth2")