def test_bad_positional(self): # Need 2 positional arguments. with self.assertRaises(TypeError): xsrfutil.generate_token(None) # At most 2 positional arguments. with self.assertRaises(TypeError): xsrfutil.generate_token(None, None, None)
def test_it(self): digest = b'foobar' digester = mock.Mock() digester.digest = mock.Mock(name='digest', return_value=digest) with mock.patch('oauth2client.contrib.xsrfutil.hmac') as hmac: hmac.new = mock.Mock(name='new', return_value=digester) token = xsrfutil.generate_token(TEST_KEY, TEST_USER_ID_1, action_id=TEST_ACTION_ID_1, when=TEST_TIME) hmac.new.assert_called_once_with(TEST_KEY) digester.digest.assert_called_once_with() expected_digest_calls = [ mock.call.update(_helpers._to_bytes(str(TEST_USER_ID_1))), mock.call.update(xsrfutil.DELIMITER), mock.call.update(TEST_ACTION_ID_1), mock.call.update(xsrfutil.DELIMITER), mock.call.update(_helpers._to_bytes(str(TEST_TIME))), ] self.assertEqual(digester.method_calls, expected_digest_calls) expected_token_as_bytes = (digest + xsrfutil.DELIMITER + _helpers._to_bytes(str(TEST_TIME))) expected_token = base64.urlsafe_b64encode( expected_token_as_bytes) self.assertEqual(token, expected_token)
def test_with_system_time(self): digest = b'foobar' curr_time = 1440449755.74 digester = mock.MagicMock() digester.digest = mock.MagicMock(name='digest', return_value=digest) with mock.patch('oauth2client.contrib.xsrfutil.hmac') as hmac: hmac.new = mock.MagicMock(name='new', return_value=digester) with mock.patch('oauth2client.contrib.xsrfutil.time') as time: time.time = mock.MagicMock(name='time', return_value=curr_time) # when= is omitted token = xsrfutil.generate_token(TEST_KEY, TEST_USER_ID_1, action_id=TEST_ACTION_ID_1) hmac.new.assert_called_once_with(TEST_KEY) time.time.assert_called_once_with() digester.digest.assert_called_once_with() expected_digest_calls = [ mock.call.update(_to_bytes(str(TEST_USER_ID_1))), mock.call.update(xsrfutil.DELIMITER), mock.call.update(TEST_ACTION_ID_1), mock.call.update(xsrfutil.DELIMITER), mock.call.update(_to_bytes(str(int(curr_time)))), ] self.assertEqual(digester.method_calls, expected_digest_calls) expected_token_as_bytes = (digest + xsrfutil.DELIMITER + _to_bytes(str(int(curr_time)))) expected_token = base64.urlsafe_b64encode( expected_token_as_bytes) self.assertEqual(token, expected_token)
def index(request): """ Step 1 of Google OAuth 2.0 flow. """ # Create and store the per-user flow object FLOW = flow_from_clientsecrets( settings.GOOGLE_OAUTH2_CLIENT_SECRET_FILEPATH, scope=request.session.get('gauth_scope', ''), redirect_uri=request.build_absolute_uri(reverse('gauth_callback'))) FLOW.params['access_type'] = 'offline' FLOW.params['approval_prompt'] = 'force' # Properly gets refresh token FLOW.params['include_granted_scopes'] = 'true' # incremental authorization FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() flow_storage = DjangoORMStorage(FlowModel, 'id', request.user, 'flow') flow_storage.put(FLOW) # Don't worry if a next parameter is not set. `auth_return` will use the # homepage by default. Allows for `next_view` to be set from other places. try: request.session['next_view'] = request.GET['next'] except KeyError: pass return redirect(authorize_url)
def index(request): '''I Have created a static user as I dont have any logged in user in my app right now''' U = User( username = '******', firstname= 'Bla Bla', lastname= 'Bla Bla', email = '*****@*****.**' ) U.save() #This is a class created by google to save the credentials automatically in the database storage = Storage(CredentialsModel, 'id', U, 'credential') credential = storage.get() if credential is None or credential.invalid == True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, U) authorize_url = FLOW.step1_get_authorize_url() print(authorize_url) return HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build('drive', 'v3', http=http) #GOOGLE DRIVE FUNCTION CALLS id = getFolderID(service) #id1 = creatingFolderInsideAFolder(service, id) print("Successful") return id
def events_get(request): REDIRECT_URI = "https://%s%s" % ( request.get_host(), reverse("scheduler:events_return")) # FLOW = flow_from_clientsecrets( # CLIENT_SECRETS, # scope=SCOPES, # redirect_uri=REDIRECT_URI # ) FLOW = OAuth2WebServerFlow( client_id='323423619559-orlpuuiaalb7sp3ooblt4mjmp32ffq1t.apps.googleusercontent.com', client_secret=os.environ['CLIENT_SECRET'], scope=SCOPES, 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) service = build('calendar', 'v3', http=http) events = service.events().list(calendarId='primary').execute() return Response(events)
def list_spreadsheets(request): set_ids_list = request.GET.get('ids') if set_ids_list is None or len(set_ids_list) == 0: return HttpResponseBadRequest('No entry sets were specified') storage = Storage(CredentialsModel, 'id', request.user, 'credential') credential = storage.get() if credential is not None: print 'FOUND CREDENTIALS' print 'Access token: %s' % (credential.access_token,) print 'Refresh token: %s' % (credential.refresh_token,) else: print 'NO CREDENTIALS' if credential is None or credential.invalid == True: FLOW.params['state'] = xsrfutil.generate_token(SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) else: sheets = [] http = credential.authorize(httplib2.Http()) drive_service = build('drive', 'v3', http=http) page_token = None while True: response = drive_service.files().list(q="mimeType='application/vnd.google-apps.spreadsheet'", spaces='drive', fields='nextPageToken, files(id, name)', pageToken=page_token).execute() for file in response.get('files', []): sheets.append(file) page_token = response.get('nextPageToken', None) if page_token is None: break; return render(request, 'haslerentries/admin/export-spreadsheet.html', { 'sheets': sheets, 'set_ids': set_ids_list, })
def setup(request): state_token = xsrfutil.generate_token(settings.SECRET_KEY, request.user.username) if 'redir' in request.GET and request.GET['redir'] in ['ffsetup', 'subs', 'sponsors']: state_token = "%s|%s" % (state_token, request.GET['redir']) FLOW.params['state'] = state_token authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url)
def index(request): '''I Have created a static user as I dont have any logged in user in my app right now''' U = User( username = '******', firstname= 'Bla Bla', lastname= 'Bla Bla', email = '*****@*****.**' ) U.save() #This is a class created by google to save the credentials automatically in the database storage = Storage(CredentialsModel, 'id', U, 'credential') credential = storage.get() if credential is None or credential.invalid == True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, U) authorize_url = FLOW.step1_get_authorize_url() print(authorize_url) return HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build("gmail", "v1", http=http) '''results = service.users().labels().list(userId='me').execute() labels = results.get('labels', [])''' #GMAIL CHECK '''if not labels: print('No labels found.') else: print('Labels:') for label in labels: print(label['name']) ''''activities = service.activities()''' #GOOGLE PLUS CHECK '''activitylist = activities.list(collection='public', userId='me').execute() logging.info(activitylist)''' '''return render(request, 'plus/welcome.html', { 'activitylist': activitylist, })''' #print("1") #message_text = request.GET.get("message_text","i am default") message_text = request.GET['message_text'] sender = "" to = request.GET['to'] subject = request.GET['subject'] #print("2") #print(request.POST['message_text']+" "+request.POST.get['message_text']) message = CreateMessage(sender, to, subject, message_text,service) message = SendMessage(service,"me",message) print(message) print("Successful") return HttpResponse("Mail Sent Successfully <script type='text/javascript'> function Redirect() { window.location.href='http://localhost/OnCourse/student/communique/mailbox.html'; } document.write('You will be redirected to a new page in 5 seconds'); setTimeout('Redirect()', 5000); </script> ")
def index(request): '''I Have created a static user as I dont have any logged in user in my app right now''' U = User( username = '******', firstname= 'Bla Bla', lastname= 'Bla Bla', email = '*****@*****.**' ) U.save() #This is a class created by google to save the credentials automatically in the database storage = Storage(CredentialsModel, 'id', U, 'credential') credential = storage.get() if credential is None or credential.invalid == True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, U) authorize_url = FLOW.step1_get_authorize_url() print(authorize_url) return HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build('calendar', 'v3', http=http) listEvents(service) '''Just For Testing''' event = { 'summary': 'Google I/O 2015', 'location': '800 Howard St., San Francisco, CA 94103', 'description': 'A chance to hear more about Google\'s developer products.', 'start': { 'dateTime': '2016-04-07T09:00:00-07:00', 'timeZone': 'America/Los_Angeles', }, 'end': { 'dateTime': '2016-04-08T17:00:00-07:00', 'timeZone': 'America/Los_Angeles', }, 'recurrence': [ 'RRULE:FREQ=DAILY' ], 'attendees': [ {'email': '*****@*****.**'} ], 'reminders': { 'useDefault': False, 'overrides': [ {'method': 'email', 'minutes': 24 * 60}, {'method': 'popup', 'minutes': 10}, ], }, } link = addEvent(service,event) print("Successful") return HttpResponse(link)
def xsrf_encode(secret, uri, uid): # String -> String -> id -> Either Exception Bytes # Note: returns a Python2 string (bytes) # Does not work with unicode URIs try: tok = xsrfutil.generate_token(secret,uid,action_id=str(uri)) return Right(str(uri) + ':' + tok) except Exception as e: return Left(err.wrap(e))
def export_to_gdocs(request): qs = Match.objects.all() outfile_path = os.path.join(settings.DATA_DIR, 'exported_data.csv') model = qs.model writer = csv.writer(open(outfile_path, 'w')) headers = [] for field in model._meta.fields: headers.append(field.verbose_name) writer.writerow(headers) headers = [] for field in model._meta.fields: headers.append(field.name) for obj in qs: row = [] for field in headers: val = getattr(obj, field) if callable(val): val = val() if type(val) == str: val = val.encode("utf-8") row.append(val) writer.writerow(row) del writer storage = DjangoORMStorage( CredentialsModel, 'id', request.user, 'credential') credential = storage.get() if credential is None or credential.invalid is True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) else: outfile_path = os.path.join(settings.DATA_DIR, 'exported_data.csv') http = httplib2.Http() http = credential.authorize(http) print('printing file at ' + outfile_path) with open(outfile_path, 'r') as csvfile: spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in spamreader: print(', '.join(row)) service = build("drive", "v3", http=http) file_metadata = { 'mimeType': 'application/vnd.google-apps.spreadsheet' } media = MediaFileUpload(outfile_path, mimetype='text/csv', resumable=True) uploadfile = service.files().create(body=file_metadata, media_body=media, fields='webViewLink').execute() return render(request, 'scoutingapp/exporttogdocs.html', {'urlLink': uploadfile['webViewLink']}) return render(request, 'scoutingapp/exporttogdocs.html')
def get(self, request, *args, **kwargs): """ The view is protected with csrf because its cookie value is required for the AJAX POST request when user clicks on the sign-in button """ #For added security to make sure that the request's session is intact between #the GET (showing the sign-in button" to the POST (submitting the sign-in) self.request.session['state'] = xsrfutil.generate_token(settings.SECRET_KEY, None) return super(GoogleSingInView, self).get(request, *args, **kwargs)
def auth_view(request): """Start an oauth flow.""" FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) # If we lose a refresh token at some point, this will allow a re-auth to give us one. FLOW.params['approval_prompt'] = 'force' authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url)
def get(self, request, *args, **kwargs): """ Defines view that requests authorization for Patient Innovation Center to access a given navigator's Google calendar :param request: django request instance object :rtype: HttpResponse """ response_raw_data, rqst_errors = init_v2_response_data() search_params = validate_get_request_parameters( request.GET, ["nav_id"], rqst_errors) if 'nav_id' in search_params: nav_id = search_params["nav_id"] try: picstaff_object = Navigators.objects.get(id=nav_id) storage = DjangoORMStorage(CredentialsModel, 'id', nav_id, 'credential') credential = storage.get() if credential is None or credential.invalid == True: google_token = xsrfutil.generate_token( settings.SECRET_KEY, picstaff_object.id) params_dict = { "nav_id": nav_id, "token": google_token.decode('ascii') } params_json = json.dumps(params_dict).encode('ascii') params_base64_encoded = base64.urlsafe_b64encode( params_json) authorize_url = FLOW.step1_get_authorize_url( state=params_base64_encoded) return HttpResponseRedirect(authorize_url) else: response_raw_data["Data"] = "Authorized!" check_or_create_navigator_google_cal( credential, rqst_errors) except Navigators.DoesNotExist: rqst_errors.append( 'Navigator database entry does not exist for the id: {!s}'. format(str(nav_id))) else: rqst_errors.append("No valid parameters") response_raw_data["Host"] = settings.HOSTURL parse_and_log_errors(response_raw_data, rqst_errors) response = HttpResponse(json.dumps(response_raw_data), content_type="application/json") return response
def import_gsheet(request, id): gsheet_endpoint = None silo = None read_url = request.GET.get('link', None) file_id = request.GET.get('resource_id', None) file_name = request.GET.get("name", "Google Sheet Import") if read_url == None or file_id == None: messages.error(request, "A Google Spreadsheet is not selected to import data from.") return HttpResponseRedirect(reverse('index')) storage = Storage(GoogleCredentialsModel, '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() #FLOW.params.update({'redirect_uri_after_step2': "/export_gsheet/%s/?link=%s&resource_id=%s" % (id, read_url, file_id)}) request.session['redirect_uri_after_step2'] = "/import_gsheet/%s/?link=%s&resource_id=%s" % (id, read_url, file_id) return HttpResponseRedirect(authorize_url) credential_json = json.loads(credential.to_json()) user = User.objects.get(username__exact=request.user) gsheet_endpoint = None read_type = ReadType.objects.get(read_type="GSheet Import") try: silo = Silo.objects.get(id=id) if silo.unique_fields.exists() == False: messages.error(request, "A unique column must be specfied when importing to an existing table. <a href='%s'>Specify Unique Column</a>" % reverse_lazy('siloDetail', kwargs={"id": silo.id})) return HttpResponseRedirect(request.META['HTTP_REFERER']) except Silo.DoesNotExist: silo = Silo(name=file_name, owner=request.user, public=False, description="Google Sheet Import") silo.save() try: gsheet_endpoint = Read.objects.get(silos__id=id, type=read_type, silos__owner=user.id, resource_id=file_id, read_name='GSheet Import') except Read.MultipleObjectsReturned: messages.error(request, "There should not be multiple records for the same gsheet, silo, and owner") except Read.DoesNotExist: gsheet_endpoint = Read(read_name="GSheet Import", type=read_type, resource_id=file_id, owner=user) gsheet_endpoint.read_url = read_url gsheet_endpoint.save() silo.reads.add(gsheet_endpoint) silo.save() except Exception as e: messages.error(request, "An error occured: %" % e.message) #print("about to export to gsheet: %s" % gsheet_endpoint.resource_id) if import_from_google_spreadsheet(credential_json, silo, gsheet_endpoint.resource_id) == True: link = "Your imported data is available at here. <a href='%s'>See the table</a>" % reverse_lazy('siloDetail', kwargs={"id": silo.id}) messages.success(request, link) else: messages.error(request, 'Something went wrong.') #messages.success(request, "Now, it should import data from GSheet") return HttpResponseRedirect(reverse('index'))
def get(self, request): storage = DjangoORMStorage( Credentials, 'email', settings.PRIMARY_YOUTUBE_ACCOUNT, 'credential') credential = storage.get() if credential is None or credential.invalid: flow = get_flow(request) flow.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = flow.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) else: return HttpResponse("credentials are currently valid")
def get_mail_service(user): storage = DjangoORMStorage(models.CredentialsModel, 'id', user, 'credential') credential = storage.get() if credential is None or credential.invalid: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) service = build('gmail', 'v1', credentials=credential, cache_discovery=False) return service
def get_service(request): storage = DjangoORMStorage(CredentialsModel, "id", request.user, "credential") credential = storage.get() if credential is None or credential.invalid: FLOW.params["state"] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url), False else: http = httplib2.Http() http = credential.authorize(http) service = build("calendar", "v3", http=http) return service, True
def check_google_authenticated(request): storage = Storage(CredentialsModel, 'id', request.user, 'credential') credentials = storage.get() if credentials is None or credentials.invalid is True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) FLOW.params['access_type'] = 'offline' authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) else: return HttpResponseRedirect('/main')
def get_credential_object(user, prompt=None): storage = Storage(GoogleCredentialsModel, 'id', user, 'credential') credential_obj = storage.get() if credential_obj is None or credential_obj.invalid == True or prompt: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, user) FLOW.params['access_type'] = 'offline' FLOW.params['approval_prompt'] = 'force' authorize_url = FLOW.step1_get_authorize_url() return {"level": messages.ERROR, "msg": "Requires Google Authorization Setup", "redirect": authorize_url, "redirect_uri_after_step2": True} #print(json.loads(credential_obj.to_json())) return credential_obj
def sign_out(self, redirect_url=None): """Returns a signed URL to disassociate the ouath2 user from the session.""" config = config_lib.get_config() key = self.handler.app.config['webapp2_extras.sessions']['secret_key'] if redirect_url is None: redirect_url = self.handler.request.url user_id = self.handler.me.user_id() token = xsrfutil.generate_token(key, user_id, action_id=redirect_url) return '{}/signout?{}'.format( config['airlock_path'], urllib.urlencode({ 'redirect': redirect_url, 'token': token, }))
def export_gsheet(request, id): gsheet_endpoint = None read_url = request.GET.get('link', None) file_id = request.GET.get('resource_id', None) if read_url == None or file_id == None: messages.error(request, "A Google Spreadsheet is not selected to import data to it.") return HttpResponseRedirect(reverse('listSilos')) storage = Storage(GoogleCredentialsModel, '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() #FLOW.params.update({'redirect_uri_after_step2': "/export_gsheet/%s/?link=%s&resource_id=%s" % (id, read_url, file_id)}) request.session['redirect_uri_after_step2'] = "/export_gsheet/%s/?link=%s&resource_id=%s" % (id, read_url, file_id) return HttpResponseRedirect(authorize_url) credential_json = json.loads(credential.to_json()) user = User.objects.get(username__exact=request.user) gsheet_endpoint = None read_type = ReadType.objects.get(read_type="Google Spreadsheet") try: gsheet_endpoint = Read.objects.get(silos__id=id, type=read_type, silos__owner=user.id, read_name='Google') except Read.MultipleObjectsReturned: gsheet_endpoints = Read.objects.get(silos__id=id, type=read_type, silos__owner=user.id, read_name='Google') for endpoint in gsheet_endpoints: if endpoint.resource_id: gsheet_endpoint = endpoint except Read.DoesNotExist: gsheet_endpoint = Read(read_name="Google", type=read_type, owner=user) gsheet_endpoint.save() silo = Silo.objects.get(id=id) silo.reads.add(gsheet_endpoint) silo.save() except Exception as e: messages.error(request, "An error occured: %" % e.message) if gsheet_endpoint.resource_id == "None" or gsheet_endpoint.resource_id == None: gsheet_endpoint.resource_id = file_id gsheet_endpoint.read_url = read_url gsheet_endpoint.save() #print("about to export to gsheet: %s" % gsheet_endpoint.resource_id) if export_to_google_spreadsheet(credential_json, id, gsheet_endpoint.resource_id) == True: link = "Your exported data is available at <a href=" + gsheet_endpoint.read_url + " target='_blank'>Google Spreadsheet</a>" messages.success(request, link) else: messages.error(request, 'Something went wrong.') return HttpResponseRedirect(reverse('listSilos'))
def sync_gcalendar(request): gcalservice = GoogleService() if request.GET.get("appointment_id"): if request.GET.get("refferrer"): request.session["refferrer"] = request.GET.get("refferrer") customer_factory = CustomerServicesFactory() dealer_factory = DealerShipServicesFactory() dealer_service = dealer_factory.get_instance("dealership") # dealer = dealer_service.get_dealer_by(dealer_code) uservice = customer_factory.get_instance("user") #CUserService() appt_service = dealer_factory.get_instance( "appointment") #AppointmentService() appointment = appt_service.get_appointment( request.GET.get("appointment_id")) #,dealer) # REDIRECT_URI = 'http://127.0.0.1:8000/customer/oauth2callback/'#?appointment_id='+request.GET.get("appointment_id") request.session["oauth_appointment"] = request.GET.get( "appointment_id") #REDIRECT_URI = "https://%s%s" % ( # get_current_site(request).domain, reverse("customer:return")) REDIRECT_URI = settings.SITE_MAIN_URL + reverse("customer:return") CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), gcalservice.CLIENT_SECRET_FILE) FLOW = flow_from_clientsecrets(CLIENT_SECRETS, scope=gcalservice.SCOPES, redirect_uri=REDIRECT_URI) storage = Storage(CredentialsModel, 'id', appointment, 'credential') credential = storage.get() if credential is None or credential.invalid is True: FLOW.params['state'] = xsrfutil.generate_token( settings.SECRET_KEY, appointment) authorize_url = FLOW.step1_get_authorize_url() f = FlowModel(id=appointment, flow=FLOW) f.save() return HttpResponseRedirect(authorize_url) else: resp = gcalservice.create_event(appointment, credential) messages.success( request, "Your appointment has been added to Google Calendars") if request.session.get("refferrer"): refferrer = request.session["refferrer"] del request.session["refferrer"] return HttpResponseRedirect(refferrer) else: return JsonResponse({"success": resp}, safe=False)
def index(request): '''I Have created a static user as I dont have any logged in user in my app right now''' U = User( username = '******', firstname= 'Bla Bla', lastname= 'Bla Bla', email = '*****@*****.**' ) U.save() #This is a class created by google to save the credentials automatically in the database storage = Storage(CredentialsModel, 'id', U, 'credential') credential = storage.get() if credential is None or credential.invalid == True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, U) authorize_url = FLOW.step1_get_authorize_url() print(authorize_url) return HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build("gmail", "v1", http=http) '''results = service.users().labels().list(userId='me').execute() labels = results.get('labels', [])''' #GMAIL CHECK '''if not labels: print('No labels found.') else: print('Labels:') for label in labels: print(label['name']) ''''activities = service.activities()''' #FUNCTION CALL TO FIRST CREATE MESSAGE AND THEN SEND IT '''message_text = "Hello How are? Khana Khake Jana Hah!!" sender = "" to = "*****@*****.**" subject = "Invitation" message = CreateMessage(sender, to, subject, message_text,service) message = SendMessage(service,"me",message) print(message) print("Successful") return HttpResponse("Successful")''' message = ListMessagesMatchingQuery(service, 'me')
def export_gsheet(request, id): gsheet_endpoint = None read_url = request.GET.get('link', None) file_id = request.GET.get('resource_id', None) if read_url == None or file_id == None: messages.error(request, "A Google Spreadsheet is not selected to import data to it.") return HttpResponseRedirect(reverse('list_silos')) storage = Storage(GoogleCredentialsModel, '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() #FLOW.params.update({'redirect_uri_after_step2': "/export_gsheet/%s/?link=%s&resource_id=%s" % (id, read_url, file_id)}) request.session['redirect_uri_after_step2'] = "/export_gsheet/%s/?link=%s&resource_id=%s" % (id, read_url, file_id) return HttpResponseRedirect(authorize_url) credential_json = json.loads(credential.to_json()) user = User.objects.get(username__exact=request.user) gsheet_endpoint = None read_type = ReadType.objects.get(read_type="Google Spreadsheet") try: gsheet_endpoint = Read.objects.get(silos__id=id, type=read_type, silos__owner=user.id, read_name='Google') except Read.MultipleObjectsReturned: gsheet_endpoints = Read.objects.get(silos__id=id, type=read_type, silos__owner=user.id, read_name='Google') for endpoint in gsheet_endpoints: if endpoint.resource_id: gsheet_endpoint = endpoint except Read.DoesNotExist: gsheet_endpoint = Read(read_name="Google", type=read_type, owner=user) gsheet_endpoint.save() silo = Silo.objects.get(id=id) silo.reads.add(gsheet_endpoint) silo.save() except Exception as e: messages.error(request, "An error occured: %" % e.message) if gsheet_endpoint.resource_id == "None" or gsheet_endpoint.resource_id == None: gsheet_endpoint.resource_id = file_id gsheet_endpoint.read_url = read_url gsheet_endpoint.save() #print("about to export to gsheet: %s" % gsheet_endpoint.resource_id) if export_to_google_spreadsheet(credential_json, id, gsheet_endpoint.resource_id) == True: link = "Your exported data is available at <a href=" + gsheet_endpoint.read_url + " target='_blank'>Google Spreadsheet</a>" messages.success(request, link) else: messages.error(request, 'Something went wrong.') return HttpResponseRedirect(reverse('list_silos'))
def gmail_authenticate(request): # storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential') credential = None if credential is None or credential.invalid: 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('gmail', 'v1', http=http) print('access_token = ', credential.access_token) status = True return render(request, 'index.html', {'status': status})
def index(request): storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential') credential = storage.get() if credential is None or credential.invalid: 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("calendar", "v3", http=http, cache_discovery=False) now = datetime.datetime.utcnow().isoformat() + 'Z' events = service.events().list(calendarId='primary', timeMin=now, maxResults=10, singleEvents=True, orderBy='startTime').execute() logging.info(events) return render(request, 'core/welcome.html', {'events': events, })
def get(self, request, *args, **kwargs): storage = DjangoORMStorage(CredentialsModel, 'id', request.user.id, '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 redirect(authorize_url) referer = request.META.get('HTTP_REFERER') if not referer: return redirect("/") else: return redirect(referer)
def gmail_authenticate(request): if not request.user.is_authenticated: FLOW.params['state'] = xsrfutil.generate_token(settings.SOCIAL_AUTH_GOOGLE_SECRET, request.user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) else: storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential') credential = storage.get() if credential is None or credential.invalid: FLOW.params['state'] = xsrfutil.generate_token(settings.SOCIAL_AUTH_GOOGLE_SECRET, request.user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build('gmail', 'v1', http=http) print('access_token = ', credential.access_token) status = True template = 'home/home.html' return render(request, template, {'status': status})
def GenerateToken(action_id=_UPVOTE_DEFAULT_ACTION_ID, user_id=None): """Generates a string XSRF token. Args: action_id: A string identifying the action being performed. user_id: A string identifying the user, defaults to the current logged-in user. Returns: A string XSRF token. """ if not user_id: user_id = _GetCurrentUserId() return xsrfutil.generate_token( singleton.SiteXsrfSecret.GetSecret(), user_id, action_id=action_id)
def home(request): context = {} if request.user.is_authenticated(): logedin = True else: logedin = False context['logedin'] = logedin activities = Activity.objects.filter( user=request.user).order_by('event_date') context['activities'] = activities context['form'] = ActivityForm() markers = Activity.objects.all().order_by('-time') context['markers'] = markers storage = DjangoORMStorage(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 HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build("calendar", "v3", http=http) page_token = None calendar_list = service.calendarList().list( pageToken=page_token).execute() account = calendar_list['items'][0]['summary'] account = account.split('@') context['account1'] = account[0] context['account2'] = account[1] context['user'] = request.user if not ActivityTag.objects.filter(tag="Study"): tag1 = ActivityTag(tag="Study") tag1.save() if not ActivityTag.objects.filter(tag="Music"): tag2 = ActivityTag(tag="Music") tag2.save() if not ActivityTag.objects.filter(tag="Sports"): tag3 = ActivityTag(tag="Sports") tag3.save() return render(request, 'hypermap/mainpage.html', context)
def _build_state_value(request_handler, user): """Composes the value for the 'state' parameter. Packs the current request URI and an XSRF token into an opaque string that can be passed to the authentication server via the 'state' parameter. Args: request_handler: webapp.RequestHandler, The request. user: google.appengine.api.users.User, The current user. Returns: The state value as a string. """ uri = request_handler.request.url token = xsrfutil.generate_token(xsrf_secret_key(), user.user_id(), action_id=str(uri)) return uri + ":" + token
def get(self, request, *args, **kwargs): storage = DjangoORMStorage(CredentialsModel, 'id', request.user.id, 'credential') credential = storage.get() flow = OAuth2WebServerFlow( client_id=settings.GOOGLE_OAUTH2_CLIENT_ID, client_secret=settings.GOOGLE_OAUTH2_CLIENT_SECRET, scope='https://www.googleapis.com/auth/youtube', redirect_uri='http://localhost:8000/oauth2callback/') 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 redirect(authorize_url) return redirect('/')
def check_google_authenticated(request): storage = Storage(CredentialsModel, 'id', request.user, 'credential') credentials = storage.get() if credentials is None or credentials.invalid is True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) FLOW.params['access_type'] = 'offline' authorize_url = FLOW.step1_get_authorize_url() logger.debug(authorize_url) return HttpResponseRedirect(authorize_url) else: return HttpResponseRedirect('/main')
def drivePermission(request): if not request.user.profile.api_allowed: messages.error( request, "You do not have sufficient permissions to add your Google Drive" ) try: if request.user.profile.googlecreds.getCreds(): messages.success(request, "Google creds already in system") return redirect('home') except Exception: pass FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(url)
def get_credential_object(user, prompt=None): storage = Storage(GoogleCredentialsModel, 'id', user, 'credential') credential_obj = storage.get() if credential_obj is None or credential_obj.invalid == True or prompt: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, user) FLOW.params['access_type'] = 'offline' FLOW.params['approval_prompt'] = 'force' authorize_url = FLOW.step1_get_authorize_url() return { "level": messages.ERROR, "msg": "Requires Google Authorization Setup", "redirect": authorize_url, "redirect_uri_after_step2": True } #print(json.loads(credential_obj.to_json())) return credential_obj
def get(self, request): flow = self.get_flow(scope=analytics_settings.FLOW_SCOPE) logger.debug('Generating state token...') flow.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) key = analytics_settings.FLOW_CACHE_KEY_PLACEHOLDER % request.user.pk logger.debug('Setting OAuth2 Web server Flow to cache with key: %s', key) cache.set(key, pickle.dumps(flow)) ctx = {'auth_url': flow.step1_get_authorize_url()} logger.debug('Response context: %s', ctx) return Response(ctx, status=status.HTTP_200_OK)
def _generate_token(time=None): """Generate XSRF token. Args: time: The time in microseconds since the epoch at which the user was authorized for this action. Of not set, the current time is used. Returns: Generated XSRF token string, or an empty string if no user is logged in. """ current_user = user.get_user_email() if not current_user: return '' return xsrfutil.generate_token(key=_get_xsrf_secret(), user_id=current_user, action_id=constants.XSRF_ACTION_ID, when=time)
def _build_state_value(request_handler, user): """Composes the value for the 'state' parameter. Packs the current request URI and an XSRF token into an opaque string that can be passed to the authentication server via the 'state' parameter. Args: request_handler: webapp.RequestHandler, The request. user: google.appengine.api.users.User, The current user. Returns: The state value as a string. """ uri = request_handler.request.url token = xsrfutil.generate_token(xsrf_secret_key(), user.user_id(), action_id=str(uri)) return uri + ':' + token
def join_activity(request, activity_id): try: this_act = Activity.objects.get(id=activity_id) except ObjectDoesNotExist: raise Http404 this_act.joinedBy.add(request.user) this_act.save() storage = DjangoORMStorage(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 HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build("calendar", "v3", http=http) this_act.calendar_event_id = str(random.randint(1, 9999999999)) this_act.save() event = { 'id': this_act.calendar_event_id, 'summary': this_act.title, 'location': this_act.address, 'description': this_act.content, 'start': { 'dateTime': this_act.event_date.isoformat() + "T" + this_act.event_time.isoformat(), 'timeZone': 'America/New_York', }, 'end': { 'dateTime': this_act.event_end_date.isoformat() + "T" + this_act.event_end_time.isoformat(), 'timeZone': 'America/New_York', }, } event = service.events().insert(calendarId='primary', body=event).execute() return render(request, 'dump.json', content_type='application/json')
def export_new_gsheet(request, id): storage = Storage(GoogleCredentialsModel, '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() #FLOW.params.update({'redirect_uri_after_step2': "/export_new_gsheet/%s/" % id}) request.session[ 'redirect_uri_after_step2'] = "/export_new_gsheet/%s/" % id return HttpResponseRedirect(authorize_url) credential_json = json.loads(credential.to_json()) silo_id = id silo_name = Silo.objects.get(pk=silo_id).name http = httplib2.Http() # Authorize the http object to be used with "Drive API" service object http = credential.authorize(http) # Build the Google Drive API service object service = build("drive", "v2", http=http) # The body of "insert" API call for creating a blank Google Spreadsheet body = { 'title': silo_name, 'description': "Exported Data from Mercy Corps TolaData", 'mimeType': "application/vnd.google-apps.spreadsheet" } # Create a new blank Google Spreadsheet file in user's Google Drive google_spreadsheet = service.files().insert(body=body).execute() # Get the spreadsheet_key of the newly created Spreadsheet spreadsheet_key = google_spreadsheet['id'] #print(spreadsheet_key) if export_to_google_spreadsheet(credential_json, silo_id, spreadsheet_key) == True: link = "Your exported data is available at <a href=" + google_spreadsheet[ 'alternateLink'] + " target='_blank'>Google Spreadsheet</a>" messages.success(request, link) else: messages.error(request, 'Something went wrong; try again.') return HttpResponseRedirect(reverse('list_silos'))
def get(self, request): user = None if not request.user.is_anonymous(): user = request.user storage = DjangoORMStorage(CredentialsModel, 'id', user, 'credential') credentials = storage.get() if credentials is None or credentials.invalid == True: FLOW.params['state'] = xsrfutil.generate_token(settings.GOOGLE_OAUTH2_CLIENT_SECRET, request.user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) return HttpResponseRedirect('/')
def authorize_google(step, request): if step == 1: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) if step == 2: if not xsrfutil.validate_token(settings.SECRET_KEY, str(request.GET.__getitem__('state')), request.user): return False if request.GET.__contains__('error'): return False credential = FLOW.step2_exchange(request.GET) storage.DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential').put(credential) return True return False
def index(request): storage = DjangoORMStorage(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 HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build("plus", "v1", http=http) activities = service.activities() activitylist = activities.list(collection='public', userId='me').execute() logging.info(activitylist) return render(request, 'plus/welcome.html', { 'activitylist': activitylist, })
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 HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build("plus", "v1", http=http) activities = service.activities() activitylist = activities.list(collection='public', userId='me').execute() logging.info(activitylist) return render(request, 'plus/welcome.html', { 'activitylist': activitylist, })
def export_new_gsheet(request, id): storage = Storage(GoogleCredentialsModel, '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() #FLOW.params.update({'redirect_uri_after_step2': "/export_new_gsheet/%s/" % id}) request.session['redirect_uri_after_step2'] = "/export_new_gsheet/%s/" % id return HttpResponseRedirect(authorize_url) credential_json = json.loads(credential.to_json()) silo_id = id silo_name = Silo.objects.get(pk=silo_id).name http = httplib2.Http() # Authorize the http object to be used with "Drive API" service object http = credential.authorize(http) # Build the Google Drive API service object service = build("drive", "v2", http=http) # The body of "insert" API call for creating a blank Google Spreadsheet body = { 'title': silo_name, 'description': "Exported Data from Mercy Corps TolaData", 'mimeType': "application/vnd.google-apps.spreadsheet" } # Create a new blank Google Spreadsheet file in user's Google Drive google_spreadsheet = service.files().insert(body=body).execute() # Get the spreadsheet_key of the newly created Spreadsheet spreadsheet_key = google_spreadsheet['id'] #print(spreadsheet_key) if export_to_google_spreadsheet(credential_json, silo_id, spreadsheet_key) == True: link = "Your exported data is available at <a href=" + google_spreadsheet['alternateLink'] + " target='_blank'>Google Spreadsheet</a>" messages.success(request, link) else: messages.error(request, 'Something went wrong; try again.') return HttpResponseRedirect(reverse('listSilos'))
def sync_sheet(request): # possible error: oauth credentials can expire (?) but this will still try to use the old creds # TODO: loading spinner on the frontend while processing # TODO: ensure game id is provided; if no URL provided, fall back to last URL used if request.user.is_authenticated and request.method == 'POST': game_id = request.POST.get("game-id") game = get_object_or_404(Game, id=game_id) sheet_url = request.POST.get("sheet-url") or game.sheet_url result = None storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential') credentials = storage.get() if credentials is None or credentials.invalid == True: flow.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) flow.redirect_uri = '%s%s' % (request.META['HTTP_REFERER'],'oauth2callback') auth_uri = flow.step1_get_authorize_url() return HttpResponseRedirect(auth_uri) else: # google sheets API http = httplib2.Http() http = credentials.authorize(http) discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?' 'version=v4') service = discovery.build('sheets', 'v4', http=http, discoveryServiceUrl=discoveryUrl) spreadsheetId = None #TODO: cleaner error handling/fallback if sheet_url: spreadsheetId = parse_sheet_url(sheet_url) else: return HttpResponseBadRequest() # return a spreadsheet collection result = service.spreadsheets().get(spreadsheetId=spreadsheetId, includeGridData=True).execute() data = process_sheet_data(result) game.scrambler_endpoints = json.dumps(data.pop('endpoints', None)) game.scrambler_data = json.dumps(data) game.sheet_url = sheet_url game.save() return HttpResponseRedirect("/") else: return HttpResponseBadRequest()
def index(request): print "DATA_SET", DATA_SET 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 HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build("fitness", "v1", http=http) result = service.users().dataSources().datasets().get( userId='me', dataSourceId=DATA_SOURCE, datasetId=DATA_SET).execute() #print json.loads(result) json_string = json.dumps(result, encoding='utf-8') print json_string, "?" #logging.info(activitylist) return render(request, 'plus/welcome.html', {'fitpoint': update_total_fitPoint})
def auth_view(request): REDIRECT_URI = 'http://localhost:8000/oauth2/oauth2callback' FLOW = flow_from_clientsecrets( CLIENT_SECRETS, scope = 'https://www.googleapis.com/auth/calendar', 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) service = build('calendar', 'v3', http=http) now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time print('Get the last 150 events') eventsResult = service.events().list( calendarId='primary', timeMax=now, maxResults=150, singleEvents=False).execute() events = eventsResult.get('items', []) pprintpp.pprint(events) return render(request, 'oauth/index.html', {'events': events})
def get_context_data(self, **kwargs): """ This method is used to provide additional context to be passed to the template. """ self.request.session['state'] = xsrfutil.generate_token(settings.SECRET_KEY, None) # Call the base implementation first to get a context context = super(BlogPostDetail, self).get_context_data(**kwargs) # Add in the attachments linked to this blogpost context['attachments'] = Attachment.objects.filter(blogpost=self.object.pk) comments = Comment.objects.filter(blogpost__pk=self.object.pk).order_by('created') context['comments'] = comments #print(self.request.session.get('cid', 0)) try: context['commentform'] = CommentForm(initial={'blogpost': self.kwargs['pk']}) except Exception as e: print(e) pass return context
def events_list(request): home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'calendar-python-quickstart.json') store = file.Storage(credential_path) credentials = store.get() logger.error(credentials) if not credentials or credentials.invalid is True: flow = get_flow(request) flow.params['state'] = xsrfutil.generate_token(config('SECRET_KEY'), request.user) request.session['flow'] = pickle.dumps(flow).decode('iso-8859-1') authorize_url = flow.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) service = build("calendar", "v3", credentials=credentials) # now = datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time events = service.events() event_list = events.list( calendarId='primary', # timeMin=now, singleEvents=True, orderBy='startTime', ).execute() if 'delete' in request.GET: delete_from_API(request, request.GET.get('uidd')) return redirect('events_list') return render(request, 'paginaInicial/home.html', {'events': event_list})
def get(self, request): credential = None if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: credential = pickle.load(token) if credential is None or credential.invalid is True: chave = settings.SECRET_KEY user = request.user token = xsrfutil.generate_token( settings.GOOGLE_OAUTH2_CLIENT_SECRET, settings.GOOGLE_OAUTH2_CLIENT_ID) FLOW.params['state'] = token authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) http = httplib2.Http() http = credential.authorize(http) service = build('calendar', 'v3', http=http) events = service.events() event_list = events.list(calendarId='primary').execute() logging.info(event_list) return render(request, 'core/events.html', {'events': event_list})
def get(self, request, *args, **kwargs): print('inside setting up credentials') print('user id = ') print(request.user.id) storage = DjangoORMStorage(CredentialModel, 'id', request.user.id, 'credential') credential = storage.get() print('credentials = ') print(credential) if credential is None or credential.invalid == True: print('credential found to be invalid or None') flow.params['state'] = xsrfutil.generate_token( settings.SECRET_KEY, request.user) print('state = ') print(flow.params['state']) authorize_url = flow.step1_get_authorize_url() print('authorize_url = ') print(authorize_url) return redirect(authorize_url) else: print('credential does exist and it is valid too!') return redirect('/')
def index(request): # use the first REDIRECT_URI if you are developing your app # locally, and the second in production # 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/drive.file https://www.googleapis.com/auth/books', 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) FLOW.params['next'] = request.GET.get('next') authorize_url = FLOW.step1_get_authorize_url() f = FlowModel(id=user, flow=FLOW) f.save() return HttpResponseRedirect(authorize_url) else: return HttpResponse('<html><head><title>Close</title></head><body onload="window.close();">Thank you for authorizing the app. Please close this window</body></html>')
def add_to_spreadsheet(request): return_url = '/admin/haslerentries/entryset/' # TODO remember filter set_ids = request.POST.get('ids').split(',') sheet_id = request.POST.get('sheet') if set_ids is None or len(set_ids) == 0: messages.add_message(request, messages.ERROR, 'No entry sets were specified') return HttpResponseRedirect(request.path) if sheet_id is None or len(sheet_id) == 0: messages.add_message(request, messages.ERROR, 'No sheet ID was specified') return HttpResponseRedirect(request.path) summary = EntrySetSummary() storage = Storage(CredentialsModel, 'id', request.user, 'credential') credential = storage.get() if credential is not None: print 'FOUND CREDENTIALS' print 'Access token: %s' % (credential.access_token,) print 'Refresh token: %s' % (credential.refresh_token,) else: print 'NO CREDENTIALS' if credential is None or credential.invalid == True: FLOW.params['state'] = xsrfutil.generate_token(SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) else: http = credential.authorize(httplib2.Http()) service = build('script', 'v1', http=http) request_body = { 'function': 'addEntrySets', 'parameters': [ sheet_id, get_enty_sets_data(set_ids) ], 'devMode': ENTRIES_SCRIPT_DEV_MODE, } errorMessage = None try: response = service.scripts().run(body=request_body, scriptId=ENTRIES_SCRIPT_ID).execute() if 'error' in response: # The API executed, but the script returned an error. error = response['error']['details'][0] errorMessage = error['errorMessage'] else: print response['response'].get('result') # Here, the function returns an array of strings. # sheetNames = response['response'].get('result') # print('Sheet names in spreadsheet:') # for name in sheetNames: # print("\t{0}".format(name)) #logging.info(response) except HttpError, e: print e.content raise e if errorMessage is not None: print('Script error! Message: {0}'.format(errorMessage)) #return_url = request.path messages.add_message(request, messages.ERROR, errorMessage) else: messages.add_message(request, messages.INFO, 'Exported %s entry sets to spreadsheet' % (len(set_ids),)) return HttpResponseRedirect(return_url)
def event_post(request): REDIRECT_URI = "https://%s%s" % ( request.get_host(), reverse("scheduler:post_event_return")) # FLOW = flow_from_clientsecrets( # CLIENT_SECRETS, # scope=SCOPES, # redirect_uri=REDIRECT_URI # ) FLOW = OAuth2WebServerFlow( client_id='323423619559-orlpuuiaalb7sp3ooblt4mjmp32ffq1t.apps.googleusercontent.com', client_secret=os.environ['CLIENT_SECRET'], scope=SCOPES, redirect_uri=REDIRECT_URI ) user = request.user storage = Storage(CredentialsModel, 'id', user, 'credential') # credential = request. 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) service = build('calendar', 'v3', http=http) data = request.data event = { 'location': '5127 Sheridan Blvd, Broomfield, CO 80020', 'start': { 'timeZone': 'America/Denver', }, 'end' : { 'timeZone': 'America/Denver', }, } if 'event_id' in data: event['summary']= 'Event' + data['event_id'] else: event['summary']= 'Event w/o ID' if 'description' in data: event['description']= data['description'] else: event['summary']= 'Test for event w/o ID' #MANDATORY ARGUMENT if 'start_datetime' in data: event['start']['dateTime']= data['start_datetime'] else: event['start']['dateTime']='2016-05-28T20:00:00-07:00' #MANDATORY ARGUMENT if 'end_datetime' in data: event['end']['dateTime']= data['end_datetime'] else: event['end']['dateTime']= '2016-05-28T21:00:00-07:00'#str(datetime.datetime.now() + datetime.timedelta(hours=1))#str(timezone.now() +timezone.timedelta(hours=1))#'2016-05-28T14:00:00-07:00' if 'recurrence' in data: event['recurrence'] = data['recurrence'] else: event['recurrence'] ='RRULE:FREQ=DAILY;COUNT=2' if 'reminders' in data: event['reminders']= data['reminders'] else: event['reminders']= { 'useDefault': False, 'overrides': [ {'method': 'email', 'minutes': 24 * 60}, {'method': 'popup', 'minutes': 10}, ], } e = service.events().insert(calendarId='primary', body=event).execute()
def setup(request): FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user.username) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url)
def testGenerateAndValidateToken(self): """Test generating and validating a token.""" token = xsrfutil.generate_token(TEST_KEY, TEST_USER_ID_1, action_id=TEST_ACTION_ID_1, when=TEST_TIME) # Check that the token is considered valid when it should be. self.assertTrue(xsrfutil.validate_token(TEST_KEY, token, TEST_USER_ID_1, action_id=TEST_ACTION_ID_1, current_time=TEST_TIME)) # Should still be valid 15 minutes later. later15mins = TEST_TIME + 15 * 60 self.assertTrue(xsrfutil.validate_token(TEST_KEY, token, TEST_USER_ID_1, action_id=TEST_ACTION_ID_1, current_time=later15mins)) # But not if beyond the timeout. later2hours = TEST_TIME + 2 * 60 * 60 self.assertFalse(xsrfutil.validate_token(TEST_KEY, token, TEST_USER_ID_1, action_id=TEST_ACTION_ID_1, current_time=later2hours)) # Or if the key is different. self.assertFalse(xsrfutil.validate_token('another key', token, TEST_USER_ID_1, action_id=TEST_ACTION_ID_1, current_time=later15mins)) # Or the user ID.... self.assertFalse(xsrfutil.validate_token(TEST_KEY, token, TEST_USER_ID_2, action_id=TEST_ACTION_ID_1, current_time=later15mins)) # Or the action ID... self.assertFalse(xsrfutil.validate_token(TEST_KEY, token, TEST_USER_ID_1, action_id=TEST_ACTION_ID_2, current_time=later15mins)) # Invalid when truncated self.assertFalse(xsrfutil.validate_token(TEST_KEY, token[:-1], TEST_USER_ID_1, action_id=TEST_ACTION_ID_1, current_time=later15mins)) # Invalid with extra garbage self.assertFalse(xsrfutil.validate_token(TEST_KEY, token + b'x', TEST_USER_ID_1, action_id=TEST_ACTION_ID_1, current_time=later15mins)) # Invalid with token of None self.assertFalse(xsrfutil.validate_token(TEST_KEY, None, TEST_USER_ID_1, action_id=TEST_ACTION_ID_1))