示例#1
0
文件: views.py 项目: diegogn/TFG
def auth_return(request):
    if not xsrfutil.validate_token(settings.SECRET_KEY, str(request.GET.get('state')), request.user):
        return HttpResponseBadRequest()
    credential = FLOW.step2_exchange(request.GET.get('code'))
    storage = Storage(CredentialsModel, 'id', request.user, 'credential')
    storage.put(credential)
    return HttpResponseRedirect("/api/create")
示例#2
0
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)
    )
示例#3
0
def getAllStudentsOrgUnit(user):
    #adminUser = User.objects.get(email='*****@*****.**')
    
    
    storage = Storage(CredentialsModel, 'id', user, 'credential')
    credential = storage.get()
    
    if credential is None or credential.invalid == True:
                #return HttpResponseRedirect("/login/")
        return False
    else:
        http = httplib2.Http()
        http = credential.authorize(http)
	directory_service = build("admin", "directory_v1", http=http)
	    
	all_users = []
	page_token = None
	params = {'domain': 'student.alvaradoisd.net', 'fields':'nextPageToken,users(name,id,orgUnitPath,primaryEmail)'}
	
	while True:
	  try:
	    if page_token:
	      params['pageToken'] = page_token
	      
	    current_page = directory_service.users().list(**params).execute()
	
	    all_users.extend(current_page['users'])
	    page_token = current_page.get('nextPageToken')
	    if not page_token:
	      break
	  except errors.HttpError as error:
	    return 'An error occurred: %s' % error
	    break
	
	return all_users
示例#4
0
def auth_return(request):
    if 'state' not in request.REQUEST or not xsrfutil.validate_token(
            settings.SECRET_KEY, str(request.REQUEST['state']), request.user):
        return HttpResponseBadRequest()
    credential = FLOW.step2_exchange(request.REQUEST)
    http = httplib2.Http()
    http = credential.authorize(http)
    (resp_headers,
     content) = http.request('https://www.googleapis.com/oauth2/v1/userinfo',
                             'GET')
    content = loads(content)
    try:
        profile = Profile.objects.get(google_plus_id=content['id'])
        request_profile = request.get_user().profile
        if request.user.is_authenticated():
            request.log_action('google_plus.merge', {'id': content['id']},
                               profile)
            profile.merge_from_other(request_profile)
        user = profile.user
        request.set_user(user)
    except Profile.DoesNotExist:
        user = request.get_user()
        profile = user.profile
    storage = Storage(CredentialsModel, 'id', request.user, 'credential')
    storage.put(credential)
    profile.update_from_google_plus_data(credential, content)
    request.log_action('google_plus.connect', {'data': content}, profile)
    next_uri = '/'
    if 'google_plus_next' in request.session:
        next_uri = request.session['google_plus_next']
        del request.session['google_plus_next']
        request.session.modified = True

    return HttpResponseRedirect(next_uri)
示例#5
0
def oauth_callback(request):
    if not xsrfutil.validate_token(
            settings.SECRET_KEY, request.REQUEST['state'], request.user):
        return HttpResponseBadRequest()
    credential = FLOW.step2_exchange(request.REQUEST)
    http = httplib2.Http()
    http = credential.authorize(http)

    user_info_service = build(
        serviceName='oauth2', version='v2',
        http=http)

    user_info = user_info_service.userinfo().get().execute()
    try:
        user = User.objects.get(username=user_info['id'])
    except ObjectDoesNotExist:
        user = None

    if not user:
        user = User.objects.create_user(
            user_info['id'], user_info['email'], '')
        user.first_name = user_info['name']
        user.save()
        storage = Storage(CredentialsModel, 'id', user, 'credential')
        storage.put(credential)
    user.backend = 'django.contrib.auth.backends.ModelBackend'
    if user is not None:
        login(request, user)
        return redirect('/')

    else:
        # Return an 'invalid login' error message.
        return render_to_response('gmail/thread.html', {
                                  'threads': 'Try again later some problem',
                                  })
示例#6
0
 def init_gclient(self):
     storage = Storage(CredentialsModel, 'id', self._user, 'credential')
     credential = storage.get()
     if credential is None or credential.invalid == True:
         raise InvalidCredentialException()
     else:
         self.client = get_gclient(credential)
    def _get_user_credentials(self, user):
        from orders_manager.models import CredentialsModel

        user = user if not hasattr(user, 'user') else user.user

        try:
            storage = Storage(CredentialsModel, 'id', user, 'credential')
            credential = storage.get()
        except:
            raise ValueError('Credentials for user \'%s\' was not found!' %
                             user.profile.get_full_name())

        if not credential:
            raise ValueError('User \'%s\' has no credentials' %
                             user.profile.get_full_name())

        if credential.invalid:
            raise ValueError('Credentials are invalid for user \'%s\'!' %
                             user.profile.get_full_name())

        try:
            if credential.access_token_expired:
                http = credential.authorize(httplib2.Http())
                credential.refresh(http)
        except Exception as ex:
            raise ValueError('Bad user credentials! ' + ex.args[0])

        return credential
示例#8
0
def auth_return(request):
    code=request.GET["code"]
    credential=flow.step2_exchange(code)
    storage=Storage(CredentialsModel, 'id', request.user, 'credential')
    storage.put(credential)
    
    
def authorize(request):
    # Fetch client info from settings.
    client_id = settings.GA_CLIENT_ID
    client_secret = settings.GA_CLIENT_SECRET
    redirect_uri = settings.GA_REDIRECT_URI
    scope = settings.GA_SCOPE

    # Load previously stored credentials if available.
    storage = Storage(Credentials, 'client_id', client_id, 'credentials')
    credentials = storage.get()

    # If credentials could not be found authorize.
    if credentials is None or credentials.invalid is True:
        FLOW = OAuth2WebServerFlow(
            client_id=client_id,
            client_secret=client_secret,
            scope=scope,
            redirect_uri=redirect_uri,
        )
        authorize_url = FLOW.step1_get_authorize_url()
        return HttpResponseRedirect(authorize_url)
    # Otherwise return to admin home with success message.
    else:
        messages.info(request, 'Previously authorized %s.' % client_id)
        return HttpResponseRedirect(reverse('admin:index'))
示例#10
0
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'],
            })
示例#11
0
def driveUpload(user, FILENAME):
    storage = Storage(CredentialsModel, "id", user, "credential")
    credential = storage.get()

    if credential is None or credential.invalid == True:
        # return HttpResponseRedirect("/login/")
        return render_to_response("google-login-wait.html", {})

    else:
        # Path to the file to upload
        # FILENAME = filePath

        fdir, fname = os.path.split(FILENAME)

        http = httplib2.Http()
        http = credential.authorize(http)
        drive_service = build("drive", "v2", http=http)

        # Insert a file
        media_body = MediaFileUpload(FILENAME, mimetype="application/sst", resumable=True)
        body = {"title": fname, "description": "Simple Sheets Worksheet", "mimeType": "application/sst"}

        file = drive_service.files().insert(body=body, media_body=media_body).execute()

        return file["id"]
示例#12
0
 def init_gclient(self):
     storage = Storage(CredentialsModel, 'id', self._user, 'credential')
     credential = storage.get()
     if credential is None or credential.invalid == True:
         raise InvalidCredentialException()
     else:
         self.client = get_gclient(credential)
示例#13
0
def purchase_item(request):
    action = request.POST['action']
    item = action[6:]
    size = item.split()[0]
    if size == "tiny":
        price = 1
    elif size == "small":
        price = 3
    elif size == "big":
        price = 10
    else:
        request.session['message'] = "Can't %s?!?" % action
        return HttpResponseRedirect(reverse('GloebitEx:index'))

    username = request.session.get('username', None)
    storage = Storage(CredentialModel, 'user', username, 'credential')
    credential = storage.get()

    try:
        balance = MERCHANT.purchase_item(credential, item, price)
        request.session['balance'] = balance
    except gloebit.AccessTokenError:
        request.session['message'] = "Stale token!  Logout and enter again"
    else:
        request.session['message'] = "You bought a %s." % item

    return HttpResponseRedirect(reverse('GloebitEx:index'))
示例#14
0
        def wrapper(request, *args, **kwargs):

            def oauth2_step1():
                state = {
                    # token to check on redirect
                    'token': xsrfutil.generate_token(settings.SECRET_KEY, request.user)
                }
                # extra params that need to be kept over the auth process
                if 'oauth2_state' in kwargs:
                    state['oauth2_state'] = kwargs['oauth2_state']
                # encode the whole stuff
                base64_state = base64.urlsafe_b64encode(str(json.dumps(state)))
                # set the oauth2 state param
                self.flow.params['state'] = base64_state
                authorize_url = self.flow.step1_get_authorize_url()
                return HttpResponseRedirect(authorize_url)

            storage = Storage(CredentialsModel, 'id', request.user, 'credential')
            credential = storage.get()
            if credential is None or credential.invalid is True:
                return oauth2_step1()
            else:
                # refresh credential if needed
                if credential.access_token_expired:
                    try:
                        credential.refresh(httplib2.Http())
                    except AccessTokenRefreshError:
                        return oauth2_step1()
                # remove existing oauth2_state params
                if 'oauth2_state' in kwargs:
                    del kwargs['oauth2_state']
                return view_function(request, *args, **kwargs)
示例#15
0
def oauth_callback(request):
    from oauth2client.client import OAuth2WebServerFlow
    from auth.models import CredentialsModel
    from oauth2client.django_orm import Storage
    #Get query code from auth request
    code = request.GET.get('code')
    #create flow object
    flow = OAuth2WebServerFlow(
        client_id=
        '940056909424-57b143selist3s7uj8rnpcmt7f2s0g7u.apps.googleusercontent.com',
        client_secret='mgHATY9kYzp3HEHg2xKrYzmh',
        scope=[
            'https://www.googleapis.com/auth/calendar',
            'https://www.googleapis.com/auth/drive'
        ],
        redirect_uri='http://localhost:8000/oauth2callback')
    #retrieve and store credentials
    credentials = flow.step2_exchange(code)
    storage = Storage(CredentialsModel, 'id', request.user, 'credential')
    storage.put(credentials)
    #mark user has having been validated
    user = request.user
    user_profile = user.get_profile()
    user_profile.google_validated = True
    user_profile.save()
    return HttpResponseRedirect('/index.html')
示例#16
0
def logout(request):
    username = request.session.get('username', None)
    if username is not None:
        storage = Storage(CredentialModel, 'user', username, 'credential')
        storage.delete()
        request.session['username'] = None
    return HttpResponseRedirect('/')
示例#17
0
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")
示例#18
0
文件: views.py 项目: haystack/murmur
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")
示例#19
0
def test_gdata_token(request):
    """Tests to make sure credentials are still valid"""
    storage = Storage(CredentialsModel, "id", request.user, "credential")
    credential = storage.get()
    if credential is None or credential.invalid == True:
        return JsonResponse({"status": "failed"})
    return JsonResponse({"status": "success"})
示例#20
0
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})
示例#21
0
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'))
示例#22
0
def delete_credential(profile):
    """Delete credential for current user profile"""
    storage = Storage(EdmodoCredential, 'profile', profile, 'credential')
    credential = storage.get()    
    if credential is None:
        raise Exception('Edmodo credential not found')
    storage.delete()
示例#23
0
文件: views.py 项目: discobeta/docsql
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,
                })
示例#24
0
def driveUpload(user, FILENAME):
    storage = Storage(CredentialsModel, 'id', user, 'credential')
    credential = storage.get()

    if credential is None or credential.invalid == True:
        #return HttpResponseRedirect("/login/")
        return render_to_response('google-login-wait.html', {})

    else:
        # Path to the file to upload
        #FILENAME = filePath

        fdir, fname = os.path.split(FILENAME)

        http = httplib2.Http()
        http = credential.authorize(http)
        drive_service = build("drive", "v2", http=http)

        # Insert a file
        media_body = MediaFileUpload(FILENAME,
                                     mimetype='application/sst',
                                     resumable=True)
        body = {
            'title': fname,
            'description': 'Simple Sheets Worksheet',
            'mimeType': 'application/sst'
        }

        file = drive_service.files().insert(body=body,
                                            media_body=media_body).execute()

        return file['id']
示例#25
0
def get_credentials(gmail_account):
    """
    Get the credentials for the given EmailAccount, what should be a Gmail account.

    If there are no valid credentials for the account, is_authorized is set to
    False and there will be an InvalidCredentialsError raised.

    Arguments:
        gmail_account (instance): EmailAccount instance

    Returns:
        credentials for the EmailAccount

    Raises:
        InvalidCredentialsError, if there are no valid credentials for the account.

    """
    storage = Storage(GmailCredentialsModel, 'id', gmail_account,
                      'credentials')
    credentials = storage.get()
    if credentials is not None and credentials.invalid is False:
        return credentials
    else:
        gmail_account.is_authorized = False
        gmail_account.save()
        logger.error('no credentials for account %s' % gmail_account)
        raise InvalidCredentialsError('no credentials for account %s' %
                                      gmail_account)
示例#26
0
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,
                })
示例#27
0
文件: views.py 项目: discobeta/docsql
def table2sql(request,id=0):
    bucket_name = '';
    if id:

        storage = Storage(CredentialsModel, 'id', request.user, 'credential')
        credential = storage.get()
        http1 = httplib2.Http()

        http2 = credential.authorize(http1)
        service = build("drive", "v2", http=http2)
#        files = service.files().list().execute()
#        request = service.files().get_media(fileId=id)
#        local_fd  = open('workfile', 'w');
#        media_request = http.MediaIoBaseDownload(local_fd, request)
#        close f;


        # Retry transport and file IO errors.
        RETRYABLE_ERRORS = (httplib2.HttpLib2Error, IOError)

        # Number of times to retry failed downloads.
        NUM_RETRIES = 5

        # Number of bytes to send/receive in each request.
        CHUNKSIZE = 2 * 1024 * 1024

        # Mimetype to use if one can't be guessed from the file extension.
        DEFAULT_MIMETYPE = 'application/octet-stream'

        print 'Building download request...'
        filename = 'xxx'
        f = file(filename, 'w')
        request = service.files().get_media(fileId=id)
        media = http.MediaIoBaseDownload(f, request, chunksize=CHUNKSIZE)

        print 'Downloading bucket: %s object: %s to file: %s' % (bucket_name,
                                                           id,
                                                           filename)

        progressless_iters = 0
        done = False
        while not done:
            error = None
            try:
              progress, done = media.next_chunk()
              if progress:
                print_with_carriage_return(
                    'Download %d%%.' % int(progress.progress() * 100))
            except HttpError, err:
              error = err
              if err.resp.status < 500:
                raise
            except RETRYABLE_ERRORS, err:
              error = err

            if error:
              progressless_iters += 1
              handle_progressless_iter(error, progressless_iters)
            else:
              progressless_iters = 0
示例#28
0
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,
                })
示例#29
0
def get_credential(profile, required=False):
    """Get stored credential for current user profile"""
    storage = Storage(EdmodoCredential, 'profile', profile, 'credential')
    credential = storage.get()
    if credential is None and required:
        raise Exception('Edmodo credential not found')
    return credential
示例#30
0
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,}
    )
示例#31
0
文件: views.py 项目: qwtel/freamon
def index(request):
  storage = Storage(CredentialsModel, 'id', request.user, 'credential')
  credential = storage.get()
  if credential is None or credential.invalid == True:
    flow = OAuth2WebServerFlow(
        client_id='837647042410.apps.googleusercontent.com',
        client_secret='+SWwMCL9d8gWtzPRa1lXw5R8',
        scope='https://www.googleapis.com/auth/buzz',
        user_agent='buzz-django-sample/1.0',
        )

    authorize_url = flow.step1_get_authorize_url(STEP2_URI)
    f = FlowModel(id=request.user, flow=flow)
    f.save()
    return HttpResponseRedirect(authorize_url)
  else:
    http = httplib2.Http()
    http = credential.authorize(http)
    service = build("buzz", "v1", http=http)
    activities = service.activities()
    activitylist = activities.list(scope='@consumption',
                                   userId='@me').execute()
    logging.info(activitylist)

    return render_to_response('buzz/welcome.html', {
                'activitylist': activitylist,
                })
示例#32
0
 def get_credential(self):
   storage = Storage(authentication_models.CredentialsModel,
                     'id', self.user, 'credential')
   credential = storage.get()
   if credential is None or credential.invalid:
       raise CredentialsError('Credentials not found or invalid.')
   return credential
示例#33
0
def driveUpload(user, FILENAME):
    storage = Storage(CredentialsModel, 'id', user, 'credential')
    credential = storage.get()
    
    if credential is None or credential.invalid == True:
        return HttpResponseRedirect("/login/")
    
    else:
        # Path to the file to upload
        #FILENAME = filePath
        
        fdir, fname = os.path.split(FILENAME)
    
        http = httplib2.Http()
        http = credential.authorize(http)
        drive_service = build("drive", "v2", http=http)
    
        # Insert a file
        media_body = MediaFileUpload(FILENAME, mimetype='application/sst', resumable=True)
        body = {
          'title': fname,
          'mimeType': 'application/sst'
        }
        
        file = drive_service.files().insert(body=body, media_body=media_body).execute()
          
        return True
示例#34
0
    def _get_user_credentials(self, user):
        from orders_manager.models import CredentialsModel

        user = user if not hasattr(user, 'user') else user.user

        try:
            storage = Storage(CredentialsModel, 'id', user, 'credential')
            credential = storage.get()
        except:
            raise ValueError('Credentials for user \'%s\' was not found!' %
                             user.profile.get_full_name())

        if not credential:
            raise ValueError('User \'%s\' has no credentials' %
                             user.profile.get_full_name())

        if credential.invalid:
            raise ValueError('Credentials are invalid for user \'%s\'!' %
                             user.profile.get_full_name())

        try:
            if credential.access_token_expired:
                http = credential.authorize(httplib2.Http())
                credential.refresh(http)
        except Exception as ex:
            raise ValueError('Bad user credentials! ' + ex.args[0])

        return credential
示例#35
0
文件: views.py 项目: Blurjp/HuangDaxi
def index(request):
  storage = Storage(CredentialsModel, 'id', request.user, 'credential')
  credential = storage.get()
  if credential is None or credential.invalid == True:
    flow = OAuth2WebServerFlow(
        client_id='[[Insert Client ID here.]]',
        client_secret='[[Insert Client Secret here.]]',
        scope='https://www.googleapis.com/auth/plus.me',
        user_agent='plus-django-sample/1.0',
        )

    authorize_url = flow.step1_get_authorize_url(STEP2_URI)
    f = FlowModel(id=request.user, flow=flow)
    f.save()
    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_to_response('plus/welcome.html', {
                'activitylist': activitylist,
                })
示例#36
0
def _authorize_client(user, gclient):
    storage = Storage(CredentialsModel, 'id', user, 'credential')
    credential = storage.get()
    if credential is None or credential.invalid == True:
        raise Exception("Invalid credentials")
    gclient = credential.authorize_gclient(gclient)
    return gclient
示例#37
0
 def get_credentials(self):
     """
         gets credentials from Storage
     """
     storage = Storage(Credentials, 'id', self.request.user, 'credential')
     credentials = storage.get()
     return credentials
示例#38
0
def require_google_login(request):
    storage = Storage(CredentialsModel, 'id', request.session.session_key, 'credential')
    credential = storage.get()
    if credential is None or credential.invalid == True:
        flow = OAuth2WebServerFlow(client_id=settings.GOOGLE_OAUTH_KEY,
                                   client_secret=settings.GOOGLE_OAUTH_SECRET,
                                   scope='https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email',
                                   user_agent='plus-django-sample/1.0',
                                   state=request.GET['next'])

        authorize_url = flow.step1_get_authorize_url(settings.GOOGLE_RETURN_URL)

        f = FlowModel(id=request.session.session_key, flow=flow)
        f.save()

        return redirect(authorize_url)

    http = httplib2.Http()
    plus = build('plus', 'v1', http=http)
    credential.authorize(http)
    name_data = plus.people().get(userId='me').execute()

    name = name_data["name"]["givenName"]
    last_name = name_data["name"]["familyName"]

    plus = build('oauth2', 'v2', http=http)
    credential.authorize(http)
    email_data = plus.userinfo().get().execute()
    email = email_data["email"]

    return _login_user(request, email, name, last_name, email)
示例#39
0
文件: views.py 项目: suyadi/skripsi
def auth_return(request):
    if not xsrfutil.validate_token(settings.SECRET_KEY, request.REQUEST['state'], request.user):
        return  HttpResponseBadRequest()
    credential = FLOW.step2_exchange(request.REQUEST)
    storage = Storage(CredentialsModel, 'id', request.user, 'credential')
    storage.put(credential)
    return HttpResponseRedirect("/")
示例#40
0
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}
示例#41
0
文件: views.py 项目: Adnn/GTD_Tasks
def auth_return(request):
    if not xsrfutil.validate_token(settings.SECRET_KEY,
                                   request.REQUEST['state'], request.user):
        return HttpResponseBadRequest()
    credential = FLOW.step2_exchange(request.REQUEST)
    storage = Storage(CredentialsModel, 'id', request.user, 'credential')
    storage.put(credential)
    return HttpResponseRedirect("gtasks/")
示例#42
0
def get_stored_credential(request):
    google_id = None
    credential = None
    if request.session.get('google_id', False):
        google_id = str(request.session.get('google_id'))
        storage = Storage(CredentialsModel, 'id', google_id, 'credential')
        credential = storage.get()
    return credential
示例#43
0
 def get(self, *args, **kwargs):
     if not xsrfutil.validate_token(
             settings.SECRET_KEY, self.request.GET['state'], self.request.user):
         return HttpResponseBadRequest()
     credential = self.FLOW.step2_exchange(self.request.GET)
     storage = Storage(Credential, 'id', self.request.user, 'credential')
     storage.put(credential)
     return HttpResponseRedirect(reverse("adsense"))
    def update_user_credentials(self, new_credential):
        from orders_manager.models import CredentialsModel, User

        user = User.objects.get(
            email=self.get_google_user_email(new_credential))
        storage = Storage(CredentialsModel, 'id', user, 'credential')
        storage.put(new_credential)
        return storage.get()
示例#45
0
def table2sql(request, id=0):
    bucket_name = ''
    if id:

        storage = Storage(CredentialsModel, 'id', request.user, 'credential')
        credential = storage.get()
        http1 = httplib2.Http()

        http2 = credential.authorize(http1)
        service = build("drive", "v2", http=http2)
        #        files = service.files().list().execute()
        #        request = service.files().get_media(fileId=id)
        #        local_fd  = open('workfile', 'w');
        #        media_request = http.MediaIoBaseDownload(local_fd, request)
        #        close f;

        # Retry transport and file IO errors.
        RETRYABLE_ERRORS = (httplib2.HttpLib2Error, IOError)

        # Number of times to retry failed downloads.
        NUM_RETRIES = 5

        # Number of bytes to send/receive in each request.
        CHUNKSIZE = 2 * 1024 * 1024

        # Mimetype to use if one can't be guessed from the file extension.
        DEFAULT_MIMETYPE = 'application/octet-stream'

        print 'Building download request...'
        filename = 'xxx'
        f = file(filename, 'w')
        request = service.files().get_media(fileId=id)
        media = http.MediaIoBaseDownload(f, request, chunksize=CHUNKSIZE)

        print 'Downloading bucket: %s object: %s to file: %s' % (bucket_name,
                                                                 id, filename)

        progressless_iters = 0
        done = False
        while not done:
            error = None
            try:
                progress, done = media.next_chunk()
                if progress:
                    print_with_carriage_return('Download %d%%.' %
                                               int(progress.progress() * 100))
            except HttpError, err:
                error = err
                if err.resp.status < 500:
                    raise
            except RETRYABLE_ERRORS, err:
                error = err

            if error:
                progressless_iters += 1
                handle_progressless_iter(error, progressless_iters)
            else:
                progressless_iters = 0
示例#46
0
def confirm_authentication(view,
                           login_form_uri=None,
                           login_post_uri=None,
                           login_done_uri=None,
                           continuation_url=None,
                           scope=SCOPE_DEFAULT):
    """
    Return None if required authentication is present, otherwise
    a login redirection response to the supplied URI

    view.credential is set to credential that can be used to access resource
    """
    if view.request.user.is_authenticated():
        storage = Storage(CredentialsModel, 'id', view.request.user,
                          'credential')
        view.credential = storage.get()
        # log.info("view.credential %r"%(view.credential,))
        if view.credential is not None:
            if not view.credential.invalid:
                return None  # Valid credential present: proceed...
        else:
            # Django login with local credential: check for user email address
            #
            # @@TODO: is this safe?
            #
            # NOTE: currently, view.credential is provided by the oauth2 and used
            # only for the .invalid test above.  If it is ever used by other
            # application components, it may be necessary to construct a
            # credential for local logins.  In the long run, if credentials will
            # be used to access third party services or resources, it may not be
            # possible to use non-Oauth2 credentials here.  In the meanwhile,
            # allowing local Django user credentials provides an easier route for
            # getting a software instance installed for evaluation purposes.
            #
            if view.request.user.email:
                return None  # Assume valid login: proceed...
            else:
                return error400values(view, "Local user has no email address")
    if not login_form_uri:
        return error400values(view, "No login form URI specified")
    if not login_done_uri:
        return error400values(view, "No login completion URI specified")
    if not login_post_uri:
        login_post_uri = login_form_uri
    if not continuation_url:
        continuation_url = view.request.path
    # Redirect to initiate login sequence
    view.request.session['login_form_uri'] = login_form_uri
    view.request.session['login_post_uri'] = login_post_uri
    view.request.session['login_done_uri'] = login_done_uri
    view.request.session['continuation_url'] = continuation_url
    view.request.session['oauth2_scope'] = scope
    query_params = ({
        "continuation": continuation_url,
        "scope": scope,
        "message": ""
    })
    return HttpResponseRedirectWithQuery(login_form_uri, query_params)
    def handle(self, *args, **options):
        config = {
            u'metrics': [
                u'annotationClickThroughRate',
                u'annotationCloseRate',
                u'averageViewDuration',
                u'comments',
                u'dislikes',
                u'estimatedMinutesWatched',
                u'favoritesAdded',
                u'favoritesRemoved',
                u'likes',
                u'shares',
                u'subscribersGained',
                u'subscribersLost',
                u'views',
                ],
            u'dimensions': [
                u'day',
                ],
            u'start_date': u'2014-03-01',
            u'end_date': u'2014-03-19',
            u'start_index': 1,
            u'max_results': 100,
            }

        if args:
            aycs = AnalyticsYoutubeChannel.objects.filter(
                youtube_channel__youtube_id__in=args, first_load=False, deleted=False)
        else:
            aycs = AnalyticsYoutubeChannel.objects.filter(first_load=False, deleted=False)

        for ayc in aycs:
            storage = Storage(AnalyticsYoutubeChannel, 'email', ayc.email, 'credential')
            credential = storage.get()
            if credential is None or credential.invalid == True:
                CommandError(u'YoutubeConnection is invalid')

            http = httplib2.Http()
            http = credential.authorize(http)
            service = build('youtubeAnalytics', 'v1', http=http)

            analytics_response = service.reports().query(
                ids="channel==%s" % ayc.youtube_channel.youtube_id,
                metrics=u','.join(config[u'metrics']),
                dimensions=u','.join(config[u'dimensions']),
                start_date=config[u'start_date'],
                end_date=config[u'end_date'],
                start_index=config[u'start_index'],
                max_results=config[u'max_results'],
            ).execute()

            for column_header in analytics_response.get("columnHeaders", []):
                print "%-20s" % column_header["name"],

            for row in analytics_response.get("rows", []):
                for value in row:
                    print "%-20s" % value,
示例#48
0
def update_gmail_filter(user, group_name, whitelist_emails, filter_hash):

    storage = Storage(CredentialsModel, 'id', user, 'credential')
    credential = storage.get()
    http = httplib2.Http()
    http = credential.authorize(http)
    service_mail = build('gmail', 'v1', http=http)
    forward_address = '%s@%s' % (group_name, BASE_URL)
    return True
示例#49
0
def callback(request):
    # if not xsrfutil.validate_token(settings.SECRET_KEY, request.GET['state'],
    # request.user):
    # return  HttpResponseBadRequest()
    credential = FLOW.step2_exchange(request.GET)
    print credential
    storage = Storage(CredentialsModel, 'id', request.user, 'credential')
    storage.put(credential)
    return redirect('/utube')
示例#50
0
def logout(request):
    u = request.user
    f = FlowModel.objects.get(id=u.id)
    f.delete()
    c = CredentialsModel.objects.get(id=u.id)
    c.delete()
    storage = Storage(CredentialsModel, 'id', u, 'credential')
    storage.delete()
    return HttpResponseRedirect("http://accounts.google.com/logout")
示例#51
0
def auth_return(request):
    ans = xsrfutil.validate_token(settings.SECRET_KEY,
                                  str(request.REQUEST['state']), request.user)
    if not ans:
        return HttpResponseBadRequest()
    credential = FLOW.step2_exchange(request.REQUEST)
    storage = Storage(CredentialsModel, 'id', request.user, 'credential')
    storage.put(credential)
    return HttpResponseRedirect(reverse('contactos:registrar_recordatorio'))
示例#52
0
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
示例#53
0
 def store(self):
     """
         stores credentials in the Credentials Model
     """
     flow = self.get_flow()
     credential = flow.flow.step2_exchange(self.request.REQUEST)
     storage = Storage(Credentials, 'id', self.request.user, 'credential')
     storage.put(credential)
     self.delete_flow(flow)
示例#54
0
def get_service():
    user = User.objects.get(username='******')
    storage = Storage(CredentialsModel, 'id', user, 'credential')
    credential = storage.get()
    http = httplib2.Http()
    http = credential.authorize(http)
    service = build("analytics", "v3", http=http)

    return service
示例#55
0
def get_storage_flow_secret(scope):
    flow = flow_from_clientsecrets(
        scope_secret,
        scope=scope_urls[scope],
        redirect_uri=settings.YOUTUBE_REDIRECT_URL + scope,
    )
    storage = Storage(CredentialsModel, 'id', scope_users[scope], 'credential')
    credential = storage.get()
    return flow, credential
示例#56
0
文件: views.py 项目: tiffanyqi/cal2
def google_auth(request):
    """
    Handles Google oauth flow. For details, visit
    https://developers.google.com/api-client-library/python/guide/aaa_oauth#OAuth2WebServerFlow
    https://developers.google.com/api-client-library/python/guide/django
    """

    flow = None
    default_flow = OAuth2WebServerFlow(
        client_id=settings.GOOGLE_CALENDAR_API_CLIENT_ID,
        client_secret=settings.GOOGLE_CALENDAR_API_CLIENT_SECRET,
        scope=['https://www.googleapis.com/auth/calendar', 'profile', 'email'],
        redirect_uri=settings.BASE_URL + '/auth/google')
    default_flow.params['access_type'] = 'offline'
    default_flow.params['include_granted_scopes'] = 'true'
    default_flow.params['prompt'] = 'consent'

    # Try to retrieve an existing flow, or create one if it doesn't exist
    gflow = GoogleFlow.objects.filter(id=request.user).last()

    if gflow and gflow.flow.params.get('prompt') != 'consent':
        # Delete any flows that don't have the prompt parameter set, since that will
        # prevent the credentials from getting a refresh token
        gflow.delete()
        gflow = None

    if not gflow:
        # print "Could not retrieve existing flow"
        gflow = GoogleFlow(id=request.user, flow=default_flow)
        gflow.save()
    flow = gflow.flow

    code = request.GET.get('code', None)
    error = request.GET.get('error', None)

    if error:
        # TODO eventually make this prettier, like redirect to some landing page
        return HttpResponseBadRequest(
            "Authentication failed. Reason: {}".format(error))
    elif code:
        credential = flow.step2_exchange(code)
        # Save the credentials
        storage = Storage(GoogleCredentials, 'user', request.user,
                          'credential')
        storage.put(credential)
        profile, _ = Profile.get_or_create(user=request.user)
        profile.authed = True
        profile.save()

        # TODO improve the latency over here
        request.user.googlecredentials.import_calendars()

        return HttpResponseRedirect("/")
    else:
        auth_uri = flow.step1_get_authorize_url()
        return HttpResponseRedirect(auth_uri)
示例#57
0
def auth_return(request):
    try:
        f = FlowModel.objects.get(id=request.user)
        credential = f.flow.step2_exchange(request.REQUEST)
        storage = Storage(CredentialsModel, 'id', request.user, 'credential')
        storage.put(credential)
        f.delete()
        return HttpResponseRedirect(request.GET.get('state', '/'))
    except FlowModel.DoesNotExist:
        pass
示例#58
0
def auth_return(request):
    user = request.user
    if not xsrfutil.validate_token(
            settings.SECRET_KEY, str(request.GET['state']), user):
        return HttpResponseBadRequest()
    FLOW = FlowModel.objects.get(id=user).flow
    credential = FLOW.step2_exchange(request.GET)
    storage = Storage(CredentialsModel, 'id', user, 'credential')
    storage.put(credential)
    return HttpResponseRedirect("/oauth2")