def index(request): try: credentialsModel = CredentialsModel.objects.get(website = request.active_website) credential = credentialsModel.credential except CredentialsModel.DoesNotExist: credential = None print credential,request.active_website.id try: if credential is None or credential.invalid == True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.active_website) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build("analytics", "v3", http=http) accounts = service.management().accounts().list().execute() profiles = service.management().profiles().list(accountId = '~all',webPropertyId = '~all').execute() print profiles start_date = datetime.datetime.today().date()-datetime.timedelta(days = 30) end_date = datetime.datetime.today().date() data = service.data().ga().get(start_date = start_date.strftime("%Y-%m-%d"),end_date = end_date.strftime("%Y-%m-%d"), ids = 'ga:'+profiles['items'][0]['id'],metrics = 'ga:visits',dimensions = 'ga:browser,ga:city').execute() print data logging.info(accounts) context = RequestContext(request,{ 'accounts': accounts, }) return render_to_response('google_analytics/index.html', context) except AccessTokenRefreshError: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.active_website) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url)
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('calendar', 'v3', http=http) #See if general calendar stuff will work. If it doesn't than we need to reauth try: calendar = service.events().list(calendarId='primary').execute() except: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) #Now do the real calendar work activitylist = [] #Get a student from the user : student = Student.objects.filter( user=request.user ) [0] #build activities to export export_list = [] for course in student.course_set.all(): for activity in course.graded_activities_set.all(): export_list.append( activity ) #Make Sure that all activities have a due date for each in export_list: if each.grade_due_date: activitylist.append( ( each.activity_name, each.grade_due_date ) ) #build subactivities to export export_list = [] for course in student.course_set.all(): for activity in course.graded_activities_set.all(): for sub in activity.subgraded_activities_set.all(): export_list.append( sub ) #Make Sure that all activities have a due date for each in export_list: if each.subgrade_due_date: activitylist.append( ( each.subactivity_name, each.subgrade_due_date ) ) for each in activitylist: try: createEvent( service, each[1], each[0] ) except Exception as e: print e #activitylist = calendar[ 'summary' ] return render_to_response('plus/welcome.html', {"activitylist":activitylist, 'student':Student.objects.filter( user=request.user)[0] } )
def register_gmail(request, force=None): if force is True: FLOW.params['approval_prompt'] = 'force' FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) else: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url)
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 index(request): storage = Storage(GmailCredentials, '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) people = service.people() peoplelist = people.list(collection='visible', userId='me').execute() logging.info(peoplelist) return render_to_response('gmail/welcome.html', { 'peoplelist': peoplelist, }) """ imapobj = GMail_IMAP('imap.gmail.com') imapobj.login_oauth2(request.user.email, credential) messagelist = list(imapobj.gmsearch_messages('label:!projekt-vlab-test')) return render_to_response('gmail/welcome.html', { 'messagelist': messagelist, })
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 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.xsrfutil.hmac') as hmac: hmac.new = mock.MagicMock(name='new', return_value=digester) with mock.patch('oauth2client.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 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 index(request): storage = Storage(GcalCredentials, '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) people = service.people() peoplelist = people.list(collection='visible', userId='me').execute() logging.info(peoplelist) return render_to_response('gmail/welcome.html', { 'peoplelist': peoplelist, }) """ http = httplib2.Http() http = credential.authorize(http) service = build('calendar', 'v3', http=http) calendar_id, created = get_or_create_calendar(service, request.user) calendar_dict = service.calendarList().get(calendarId=calendar_id).execute() return render_to_response('googlecalendar/index.html', { 'calendar': calendar_dict, 'created': created, })
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 home(request, template='oauth/index.html'): # store and retrieve Credentials objects using a model # defined with a CredentialsField object credential = get_credential(request.user) if credential is None or credential.invalid == True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) print "NEW CREDENTIAL REQUESTED", FLOW.params['state'] authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) else: print template if template != 'oauth/index.html': return render_to_response(template, {}, context_instance=RequestContext(request)) http = httplib2.Http() http = credential.authorize(http) service = build("analytics", "v3", http=http) #service = build("drive", "v2", http=http) # Get a list of all Google Analytics accounts for this user accounts = service.management().accounts().list().execute() context = { 'items': accounts['items'], } print context return render_to_response(template, context, context_instance=RequestContext(request))
def auth_gmail(request): print ("Authenticaion Gmail request") storage = Storage(CredentialsModel, 'id', request.user.id, 'credential') credential = storage.get() print ("credential: %s" % credential) if credential is None or credential.invalid == True: print ("call authentication") FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) else: print ("in the else statement whenre authenticated") http = httplib2.Http() http = credential.authorize(http) service = build("gmail", "v1", http=http) threads = service.users().threads().list(userId='me').execute() messages = service.users().messages().list(userId='me', q='reservation confirmation').execute() #activities = service.activities() #activitylist = activities.list(collection='public', # userId='me').execute() #logging.info(threads) return render_to_response('app/welcome.html', { 'threads': messages['messages'], })
def post(self, request): # Retrieve request parameters userid = request.POST.get("userid", "") provider = request.POST.get("provider", "Google") login_done = request.POST.get("login_done", "/no_login_done_in_form_response/") continuation = request.POST.get("continuation", "/no_continuation_in_form_response/") scope = request.POST.get("scope", SCOPE_DEFAULT) # Access or create flow object for this session if request.POST.get("login", None) == "Login": collect_client_secrets() # Create and initialize flow object clientsecrets_filename = os.path.join(settings.CONFIG_BASE, "providers/", PROVIDER_LIST[provider]) flow = flow_from_clientsecrets( clientsecrets_filename, scope=scope, redirect_uri=request.build_absolute_uri(login_done)) flow.params['state'] = xsrfutil.generate_token( FLOW_SECRET_KEY, request.user) flow.params['provider'] = provider flow.params['userid'] = userid # flow.params['scope'] = scope flow.params['continuation'] = continuation # Save flow object in Django session request.session['oauth2flow'] = flow_to_dict(flow) # Initiate OAuth2 dance auth_uri = flow.step1_get_authorize_url() return HttpResponseRedirect(auth_uri) # Login cancelled: redirect to continuation # (which may just redisplay the login page) return HttpResponseRedirect(continuation)
def edit(request): """Edit GCal settings""" service_provider = request.user.service_provider service = get_gcal(service_provider) if not service: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) calendars = get_all_items(service.calendarList().list) initial = {'calendar': service_provider.gcal_id} if request.method == 'POST': form = GCalSettings(request.POST, calendars=calendars, initial=initial) if form.is_valid(): if service_provider.gcal_id and service_provider.gcal_id != form.cleaned_data['calendar']: # change in google calendar selection, need full resync service = get_gcal(service_provider) reset_sync(service_provider) service_provider.gcal_id = form.cleaned_data['calendar'] if service_provider.gcal_id == 'None': service_provider.gcal_id = None if service_provider.gcal_id == 'new': calendar = service.calendars().insert(body={'summary': 'E-Narocanje'}).execute() service_provider.gcal_id = calendar['id'] service_provider.save() sync(service_provider) return HttpResponseRedirect(reverse('myreservations_calendar')) else: form = GCalSettings(calendars=calendars, initial=initial) return render_to_response('reservations/gcal.html', locals(), context_instance=RequestContext(request))
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_to_response( 'directory/index.html', {'users': users,}, context_instance=RequestContext(request) )
def create(request): storage = Storage(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: http = httplib2.Http() http = credential.authorize(http) service = build(serviceName='calendar', version='v3', http=http) if request.method == 'POST': form = CreateForm(request.POST) if form.is_valid(): calendar = { 'summary': form.cleaned_data['nombre'], 'timeZone': form.cleaned_data['zona_horaria'], } created_calendar = service.calendars().insert(body=calendar).execute() return render(request, 'welcome2.html', {'created_calendar': created_calendar}) else: form = CreateForm() return render(request, 'create_calendar.html', {'form': form})
def index(request): storage = Storage(CredentialsModel, 'id', request.user, 'credential') credential = storage.get() # return render_to_response("accounts/welcome.html", {'activitylist': ['ddss','asdasd','3ed23d32d']}) 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("drive", "v2", http=http) files = service.files().list().execute() #print json.dumps(files) #simport pdb; pdb.set_trace() return render_to_response('accounts/welcome.html', { 'activitylist': files, })
def check_api_token(request, master): storage = Storage(CredentialsYoutubeModel, 'id', master, 'credential') credential = storage.get() # Si les autorisation n'ont pas été données où sont devenue invalides if credential is None or credential.invalid is True: get_flow().params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, master) authorize_url = get_flow().step1_get_authorize_url() # si l'utilisateur connecté est un admin, il doit mettre à jour les autorisations if request.user.is_superuser: context = { 'title': "On a besoin de vous !", 'message': "Bienvenue ! Comme tu peux le voir c'est la guerre ici, tout ne marche pas comme prévu ... " "Mais heureusement que tu es là ! " "Le président ne veut plus nous subventionner " "(c'est plutôt son compte youtube qui ne nous est plus accessible ...) ! " "Convaincs-le, et récupère nous ses autorisations ! Son nom est : SpamWeb. " "Tu as carte blanche " "(tu pourrais par exemple te connecter à son compte google avant de continuer ...) ! " "Allez juste un dernier conseil : " "tu devrais essayer [email protected] / spamnocturne. Bonne chance !", 'url_for_admin': authorize_url } return {'status': False, 'value': render_to_response('spamusic/message.html', context)} else: context = { 'title': "Oups ...", 'message': "Le compte youtube de SpamWeb a besoin de mettre ses autorisations à jour. " "Veuillez contacter un administrateur" } return {'status': False, 'value': render_to_response('spamusic/message.html', context)} return {'status': True, 'value': credential}
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 create_ssp_view(request): #Aqui cargo los datos del usuario form = UserNewProject() status = "" if request.method == "POST": if 'create_ssp' in request.POST: form = UserNewProject(request.POST) if form.is_valid(): storage = Storage(CredentialsModel, 'id_user', 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: name_ssp = form.cleaned_data['name_ssp'] description_ssp = form.cleaned_data['description_ssp'] user = User.objects.get(username__exact=request.user.get_username()) projectsUser = userSoftSystemProject.objects.filter(manager=user, name_ssp=name_ssp) if projectsUser: status = "0" form = UserNewProject() ctx = {'status' : status, 'form' : form} return render(request,'principal/user_new_ssp.html', ctx) try: storage = Storage(CredentialsModel, 'id_user', request.user, 'credential') credential = storage.get() http = httplib2.Http() http = credential.authorize(http) drive_service = build('drive', 'v2', http=http, developerKey="hbP6_4UJIKe-m74yLd8tQDfT") except: return redirect('vista_logout') newSSP = userSoftSystemProject.objects.create(manager = user, name_ssp = name_ssp, description_ssp = description_ssp) newStateOne = StateOne.objects.create(ssp_stateOne = newSSP) newStateTwo = StateTwo.objects.create(ssp_stateTwo = newSSP) newStateThree = StateThree.objects.create(ssp_stateThree = newSSP) newSSP.save() newStateOne.save() newStateTwo.save() newStateThree.save() body = { 'title': '%s'%(newSSP.name_ssp), 'mimeType': "application/vnd.google-apps.folder", 'parents' : [{'id' : user.get_profile().id_drive_folder}] } folder = drive_service.files().insert(body = body).execute() newSSP.id_folder_ssp = folder.get('id') newSSP.save() return redirect('vista_principal') ctx = {'form': form} return render(request,'principal/user_new_ssp.html', ctx)
def get_authorize_url(cls, user): cls.FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, user) # 아래 두 라인을 통해 refresh token 을 발급받는다. 사실 access token 하나만 줄창 받아도 상관없긴 하다. cls.FLOW.params['access_type'] = 'offline' cls.FLOW.params['approval_prompt'] = 'force' return cls.FLOW.step1_get_authorize_url()
def login_by_google(request): print 'login_by_google', request.user SK = request.POST['csrfmiddlewaretoken'] #FLOW.params['state'] = xsrfutil.generate_token(SECRET_KEY,request.user) FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY,request.user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url)
def google_refresh_token(request): ''' A one time view to get a refresh token from google ''' FLOW = Drive.create_flow() FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url)
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) return render(request, 'registration/index.html')
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 login_by_google(request): #Google login을 사용하기위한 API적용 print 'login_by_google', request.user SK = request.POST['csrfmiddlewaretoken'] #FLOW.params['state'] = xsrfutil.generate_token(SECRET_KEY,request.user) FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url)
def get_auth_action(request, credential): if credential is None or credential.invalid == True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, '') authorize_url = FLOW.step1_get_authorize_url() return redirect(authorize_url) else: # To authorize any http requests with credentials. We might not need this as we only need authentication! http = httplib2.Http() http = credential.authorize(http) return redirect('/new_program')
def evento(request,pk): # Refer to the Python quickstart on how to setup the environment: # https://developers.google.com/google-apps/calendar/quickstart/python # Change the scope to 'https://www.googleapis.com/auth/calendar' and delete any # stored credentials. FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) FLOW.params['pk'] = pk authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url)
def home(request): credential = Credential.objects.get_for_user(request.user) if credential is None or credential.invalid == True: settings.FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = settings.FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) else: #mail_box = MiliBox.objects.get(user=request.user) '''
def auth(request): credential = None if credential is None or credential.invalid == True: FLOW.params['access_type'] = 'offline' FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url)
def save_flow(self): """ saves the state of the flow """ flow = self.get_flow() user = self.request.user flow.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, user) flow = Flow(id=user, flow=flow) flow.save()
def index(request): isItOn() credential = None if credential is None or credential.invalid == True: FLOW.params['access_type'] = 'offline' FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url)
def index(request): try: credentialsModel = CredentialsModel.objects.get( website=request.active_website) credential = credentialsModel.credential except CredentialsModel.DoesNotExist: credential = None print credential, request.active_website.id try: if credential is None or credential.invalid == True: FLOW.params['state'] = xsrfutil.generate_token( settings.SECRET_KEY, request.active_website) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build("analytics", "v3", http=http) accounts = service.management().accounts().list().execute() profiles = service.management().profiles().list( accountId='~all', webPropertyId='~all').execute() print profiles start_date = datetime.datetime.today().date() - datetime.timedelta( days=30) end_date = datetime.datetime.today().date() data = service.data().ga().get( start_date=start_date.strftime("%Y-%m-%d"), end_date=end_date.strftime("%Y-%m-%d"), ids='ga:' + profiles['items'][0]['id'], metrics='ga:visits', dimensions='ga:browser,ga:city').execute() print data logging.info(accounts) context = RequestContext(request, { 'accounts': accounts, }) return render_to_response('google_analytics/index.html', context) except AccessTokenRefreshError: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.active_website) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url)
def noPopAuth(request): request.session['popup'] = False request.session.set_expiry(300) credential = None 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)
def get(self, *args, **kwargs): storage = Storage(Credential, 'id', self.request.user, 'credential') credential = storage.get() if credential is None or credential.invalid is True: self.FLOW.params['state'] = xsrfutil.generate_token( settings.SECRET_KEY, self.request.user) self.FLOW.params['approval_prompt'] = 'force' authorize_url = self.FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) else: return HttpResponseRedirect(reverse("summon_adsense_stat", kwargs={'days_before': 1}))
def index(request): storage = Storage(CredentialsModel, 'id', request.user, 'credential') credential = storage.get() if credential is None or credential.invalid: FLOW.params['state'] = xsrfutil.generate_token(SECRET_KEY, str(request.user)) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) return HttpResponseRedirect('/admin')
def google(request): storage = Storage(Credentials, 'id', request.user, 'google_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: redirect_url = request.session.pop('oauth_callback_redirect', 'google_calendar_sync_run') return redirect(redirect_url)
def youtube_api_get_credentials(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) return build("youtube", "v3", http=http)
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 save_flow(self): """ saves the state of the flow """ flow = self.get_flow() user = self.request.user flow.params['state'] = xsrfutil.generate_token( settings.SECRET_KEY, user ) flow = Flow(id=user, flow=flow) flow.save()
def get_tasks_service(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) tasks_service = build("tasks", "v1", http=http) return tasks_service
def auth(request, Boyett=0): credential = None if credential is None or credential.invalid == True: FLOW.params['access_type'] = 'offline' # in oder to force a persistant credential that will refresh itself user "/google/auth/1". However other users will not need to worry about it. if Boyett: FLOW.params['approval_prompt'] = 'force' FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url)
def google_login(request): storage = Storage(CredentialsModel, 'id', request.user.id, 'credential') credential = storage.get() next_uri = '/' if 'next' in request.GET: request.session['google_plus_next'] = request.GET['next'] next_uri = request.GET['next'] request.session.modified = True 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) return HttpResponseRedirect(next_uri)
def GenerateXsrfToken(self, current_user): """Generate a xsrf token. Args: current_user: Appengine user object of the current user. Returns: A string of the xsrf token. """ _LOG.info('Generating xsrf token for %s.', current_user.nickname()) xsrf_token = xsrfutil.generate_token(appengine.xsrf_secret_key(), current_user.user_id()) _LOG.debug('Successfully generated xsrf token for %s.', current_user.nickname()) return xsrf_token
def get_google_authentication(request, credential): user = dummy_user if credential is None or credential.invalid == True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, user) authorize_url = FLOW.step1_get_authorize_url() print authorize_url return http.HttpResponseRedirect(authorize_url) elif not request.user.is_authenticated(): # authenticate user in django user = authenticate(username=DUMMY_USERNAME, password=DUMMY_USERNAME) login(request, user) return http.HttpResponseRedirect(reverse('events'))
def GenerateXsrfToken(user_email, action_id): """Generate a xsrf token. Args: user_email: String email address of the form [email protected]. action_id: String identifier of the action for which authorization is requested. Returns: A string of the xsrf token. """ _LOG.info('Generating xsrf token for %s.', user_email) xsrf_token = xsrfutil.generate_token(key=appengine.xsrf_secret_key(), user_id=user_email, action_id=action_id) _LOG.debug('Successfully generated xsrf token for %s.', user_email) return xsrf_token
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): storage = Storage(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) 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 google_connect(): import pickle import base64 user = User.objects.get(id=1) storage = Storage(CredentialsModel, 'id', user, 'credential') cred = storage.get() if cred is not None: credential = pickle.loads(base64.b64decode(cred)) else: credential = None if credential is None or credential.invalid == True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, user) authorize_url = FLOW.step1_get_authorize_url() HttpResponseRedirect(authorize_url) else: http = credential.authorize(httplib2.Http()) service = build("calendar", "v3", http=http) return service
def auth_return(request): print "xxxxxxxxxxxxPSTATE ", request.REQUEST['state'] print "xxxxxxxxxxxxU ", request.user print "xxxxxxxxxxxxS ", settings.SECRET_KEY print "xxxxxxxxxxxxV ", xsrfutil.validate_token(settings.SECRET_KEY, request.REQUEST['state'], request.user) print "xxxxxxxxxxxxG ", xsrfutil.generate_token(settings.SECRET_KEY, request.user) if not xsrfutil.validate_token( settings.SECRET_KEY, str(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("/")