示例#1
0
class AccessTokenCredentialsTests(unittest.TestCase):

  def setUp(self):
    access_token = "foo"
    user_agent = "refresh_checker/1.0"
    self.credentials = AccessTokenCredentials(access_token, user_agent)

  def test_token_refresh_success(self):
    http = HttpMockSequence([
      ({'status': '401'}, ''),
      ])
    http = self.credentials.authorize(http)
    try:
      resp, content = http.request("http://example.com")
      self.fail("should throw exception if token expires")
    except AccessTokenCredentialsError:
      pass
    except Exception:
      self.fail("should only throw AccessTokenCredentialsError")

  def test_non_401_error_response(self):
    http = HttpMockSequence([
      ({'status': '400'}, ''),
      ])
    http = self.credentials.authorize(http)
    resp, content = http.request('http://example.com')
    self.assertEqual(400, resp.status)

  def test_auth_header_sent(self):
    http = HttpMockSequence([
      ({'status': '200'}, 'echo_request_headers'),
      ])
    http = self.credentials.authorize(http)
    resp, content = http.request('http://example.com')
    self.assertEqual('Bearer foo', content['Authorization'])
class AccessTokenCredentialsTests(unittest.TestCase):
    def setUp(self):
        access_token = "foo"
        user_agent = "refresh_checker/1.0"
        self.credentials = AccessTokenCredentials(access_token, user_agent, revoke_uri=GOOGLE_REVOKE_URI)

    def test_token_refresh_success(self):
        for status_code in REFRESH_STATUS_CODES:
            http = HttpMockSequence([({"status": status_code}, b"")])
            http = self.credentials.authorize(http)
            try:
                resp, content = http.request("http://example.com")
                self.fail("should throw exception if token expires")
            except AccessTokenCredentialsError:
                pass
            except Exception:
                self.fail("should only throw AccessTokenCredentialsError")

    def test_token_revoke_success(self):
        _token_revoke_test_helper(self, "200", revoke_raise=False, valid_bool_value=True, token_attr="access_token")

    def test_token_revoke_failure(self):
        _token_revoke_test_helper(self, "400", revoke_raise=True, valid_bool_value=False, token_attr="access_token")

    def test_non_401_error_response(self):
        http = HttpMockSequence([({"status": "400"}, b"")])
        http = self.credentials.authorize(http)
        resp, content = http.request("http://example.com")
        self.assertEqual(400, resp.status)

    def test_auth_header_sent(self):
        http = HttpMockSequence([({"status": "200"}, "echo_request_headers")])
        http = self.credentials.authorize(http)
        resp, content = http.request("http://example.com")
        self.assertEqual(b"Bearer foo", content[b"Authorization"])
    def get_gdoc_resource(klass, gdocs_resource_id, gdocs_access_token=None):
        http = httplib2.Http()
        if gdocs_access_token is not None:
            credentials = AccessTokenCredentials(gdocs_access_token, 'remix-client')
            credentials.authorize(http)
        drive = build('drive', 'v2', http=http)

        # Get the html version of the file
        md = drive.files().get(fileId=gdocs_resource_id).execute()
        uri = md['exportLinks']['text/html']

        resp, content = drive._http.request(uri)
        return resp, content, md['title']
示例#4
0
    def __init__(self, request):
        self.service = None
        self.oauth2token = None
        try:
            if request.user:
                provider = request.session.get('social_auth_last_login_backend')
                social = request.user.social_auth.filter(
                    Q(user_id=request.user.id), 
                    Q(uid=request.user.email), 
                    Q(provider=provider)
                )
                credential = AccessTokenCredentials(
                    social[0].tokens['access_token'], 
                    'HTTP/1.1'
                )
                http = httplib2.Http()
                http = credential.authorize(http)
                self.service = build("calendar", "v3", http=http)

                self.oauth2token = OAuth2Token(
                    client_id = settings.GOOGLE_OAUTH2_CLIENT_ID,
                    client_secret=settings.GOOGLE_OAUTH2_CLIENT_SECRET,
                    scope = 'https://apps-apis.google.com/a/feeds/calendar/resource/',
                    access_token = social[0].tokens['access_token'],
                    user_agent='HTTP/1.1'
                )
        except: pass
示例#5
0
def post_event(request):
    if request.method == 'POST':
        event_id = json.loads(request.body)
        event = Event.objects.get(pk=event_id)

        # Parameters for event being saved to google calendar
        event_info = {
            "end": {
                "dateTime": event.end_time
            },

            "start": {
                'dateTime': event.start_time
            },

            "summary": event.name,
            "location": event.venue,

        }

        # Builds google calendar service with appropriate credentials
        user_social_auth = request.user.social_auth.filter(provider='google-oauth2').first()
        access_token = user_social_auth.extra_data['access_token']
        calID=user_social_auth.uid
        credentials = AccessTokenCredentials(access_token, 'my-user-agent/1.0')
        http= httplib2.Http()
        http = credentials.authorize(http)
        service = build(serviceName='calendar', version='v3', http=http, developerKey='HFs_k7g6ml38NKohwrzfi_ii')
        created_event = service.events().insert(calendarId='primary', body=event_info).execute()

        return HttpResponse(json.dumps(event_id), content_type='application/json')
示例#6
0
文件: views.py 项目: GoogleJump/ninja
def getUser():
    user_agent = request.headers.get('User-Agent')
    credentials = AccessTokenCredentials(session.get('credentials'), user_agent)
    if credentials is None:
        response = make_response(json.dumps('Current user not connected.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    try:
        # authorize an instance of Http with a set of credentials
        http = httplib2.Http()
        http = credentials.authorize(http)
        people_resource = SERVICE.people()
        people_document = people_resource.get(userId='me').execute(http=http)
        return jsonify(people_document)

    except AccessTokenRefreshError:
        response = make_response(json.dumps('Failed to refresh access token.'), 500)
        response.headers['Content-Type'] = 'application/json'
        return response

    except AccessTokenCredentialsError:
        response = make_response(json.dumps('Access token is invalid or expired and cannot be refreshed.'), 500)
        response.headers['Content-Type'] = 'application/json'
        return response
示例#7
0
def check():
    result = lambda ok, text: jsonify({'ok': ok, 'text': text})
    if not g.user.phone_info.get('valid'):
        return result(False, 'invalid phone number')

    token = g.user.social_auth.one().tokens
    credentials = AccessTokenCredentials(token, app.config['USER_AGENT'])
    service = discovery.build('gmail', 'v1', http=credentials.authorize(Http()))
    inbox = service.users().messages().list(userId='me', q='in:inbox is:unread').execute()
    data = inbox.get('messages', [])
    if not data:
        return result(False, 'no unread messages')

    msg = service.users().messages().get(userId='me', id=data[0]['id']).execute()
    subj = [x['value'] for x in msg['payload']['headers'] if x['name'] == 'Subject']
    text = msg['snippet'][:160]
    try:
        fmt_number = lambda x: '+%s%s' % (x.country_code, x.national_number)
        client = TwilioRestClient(app.config['TWILIO_ACCOUNT_SID'],
                                  app.config['TWILIO_AUTH_TOKEN'])
        client.messages.create(body=text, to=fmt_number(g.user.phone_info['number']),
                               from_=app.config['TWILIO_NUMBER'])
        data = (True, subj[0] if subj else None)
    except Exception, exc:
        data = (False, str(exc))
示例#8
0
def _create_remote_playlist(request):
    # cheking the local playlist
    result = {'error': None, 'playlist_obj': None}
    try:
        youtube_obj = request.user.social_auth.get(provider='google-oauth2')
    except:
        return result

    try:
        post_data = simplejson.loads(request.body)
    except:
        post_data = {}

    playlist_name = post_data.get('title', None)
    playlist_is_private = post_data.get('is_private', None)
    action_pl_update = False

    user_playlist, pl_created = \
        Playlist.objects.get_or_create(user=request.user)
    if not pl_created: # set last update to now
        action_pl_update = user_playlist.should_update(
            playlist_name, playlist_is_private)
        user_playlist.last_update = datetime.datetime.now()
        user_playlist.save()
    else:
        user_playlist.youtube_pl_name = playlist_name
        user_playlist.save()
    result['playlist_obj'] = user_playlist

    if user_playlist.youtube_pl_id is None and request.method == 'POST':
        credentials = AccessTokenCredentials(
            youtube_obj.extra_data.get('access_token'), 'friendlyvibe/1.0')
        youtube = build(
            'youtube', 'v3', http=credentials.authorize(httplib2.Http()))

        # create the youtube playlist
        if action_pl_update is False:
            try:
                new_playlist = youtube.playlists().insert(
                    part="snippet,status",
                    body=dict(
                        snippet=dict(
                            title=settings.DEFAULT_YOUTUBE_PLNAME,
                            description="A playlist automatically created and managed by friendlyvibe.com"
                        ),
                        status=dict(
                            privacyStatus='private' if playlist_is_private else 'public'
                        )
                    )
                ).execute()

                user_playlist.youtube_json = simplejson.dumps(new_playlist)
                user_playlist.youtube_pl_id = new_playlist.get(u'id')
                user_playlist.youtube_pl_name = playlist_name
                user_playlist.is_private = playlist_is_private
                user_playlist.save()

            except Exception, e:
                # do some signal here to KNOW the user's youtube account is disconnected
                result['error'] = str(e)
示例#9
0
def profile():
  access_token = session.get('credentials')
  credentials = AccessTokenCredentials(access_token, 'user-agent-value')

  # Only fetch a list of people for connected users.
  if credentials is None:
    response = make_response(json.dumps('Current user not connected.'), 401)
    response.headers['Content-Type'] = 'application/json'
    return response
  try:
    # Create a new authorized API client.
    http = httplib2.Http()
    http = credentials.authorize(http)
    people_resource = SERVICE.people()
    people_document = people_resource.get(userId='me').execute(http=http)
    gplusId = people_document['id']
    user = User.query.filter_by(gplusId=gplusId).count()
    print user
    response = make_response('success', 200)
    response.headers['Content-Type'] = 'application/json'
    return response

  except AccessTokenRefreshError:
    response = make_response(json.dumps('Failed to refresh access token.'), 500)
    response.headers['Content-Type'] = 'application/json'
    return response
示例#10
0
class AccessTokenCredentialsTests(unittest.TestCase):

  def setUp(self):
    access_token = 'foo'
    user_agent = 'refresh_checker/1.0'
    self.credentials = AccessTokenCredentials(access_token, user_agent,
                                              revoke_uri=GOOGLE_REVOKE_URI)

  def test_token_refresh_success(self):
    for status_code in REFRESH_STATUS_CODES:
      http = HttpMockSequence([
        ({'status': status_code}, b''),
        ])
      http = self.credentials.authorize(http)
      try:
        resp, content = http.request('http://example.com')
        self.fail('should throw exception if token expires')
      except AccessTokenCredentialsError:
        pass
      except Exception:
        self.fail('should only throw AccessTokenCredentialsError')

  def test_token_revoke_success(self):
    _token_revoke_test_helper(
        self, '200', revoke_raise=False,
        valid_bool_value=True, token_attr='access_token')

  def test_token_revoke_failure(self):
    _token_revoke_test_helper(
        self, '400', revoke_raise=True,
        valid_bool_value=False, token_attr='access_token')

  def test_non_401_error_response(self):
    http = HttpMockSequence([
      ({'status': '400'}, b''),
      ])
    http = self.credentials.authorize(http)
    resp, content = http.request('http://example.com')
    self.assertEqual(400, resp.status)

  def test_auth_header_sent(self):
    http = HttpMockSequence([
      ({'status': '200'}, 'echo_request_headers'),
      ])
    http = self.credentials.authorize(http)
    resp, content = http.request('http://example.com')
    self.assertEqual(b'Bearer foo', content[b'Authorization'])
class AccessTokenCredentialsTests(unittest.TestCase):

  def setUp(self):
    access_token = 'foo'
    user_agent = 'refresh_checker/1.0'
    self.credentials = AccessTokenCredentials(access_token, user_agent,
                                              revoke_uri=GOOGLE_REVOKE_URI)

  def test_token_refresh_success(self):
    for status_code in REFRESH_STATUS_CODES:
      http = HttpMockSequence([
        ({'status': status_code}, ''),
        ])
      http = self.credentials.authorize(http)
      try:
        resp, content = http.request('http://example.com')
        self.fail('should throw exception if token expires')
      except AccessTokenCredentialsError:
        pass
      except Exception:
        self.fail('should only throw AccessTokenCredentialsError')

  def test_token_revoke_success(self):
    _token_revoke_test_helper(
        self, '200', revoke_raise=False,
        valid_bool_value=True, token_attr='access_token')

  def test_token_revoke_failure(self):
    _token_revoke_test_helper(
        self, '400', revoke_raise=True,
        valid_bool_value=False, token_attr='access_token')

  def test_non_401_error_response(self):
    http = HttpMockSequence([
      ({'status': '400'}, ''),
      ])
    http = self.credentials.authorize(http)
    resp, content = http.request('http://example.com')
    self.assertEqual(400, resp.status)

  def test_auth_header_sent(self):
    http = HttpMockSequence([
      ({'status': '200'}, 'echo_request_headers'),
      ])
    http = self.credentials.authorize(http)
    resp, content = http.request('http://example.com')
    self.assertEqual('Bearer foo', content['Authorization'])
示例#12
0
 def get_service(self):
     """
     :return: servicio de drive
     """
     credentials = AccessTokenCredentials(self.token, None)
     http = httplib2.Http()
     http = credentials.authorize(http)
     return build('drive', 'v2', http)
 def __init__(self):
     google_auth_manager = GoogleAuthManager()
     user_agent = 'python-recaller/1.0'
     credentials = AccessTokenCredentials(
         google_auth_manager.get_access_token(), user_agent)
     http = httplib2.Http()
     http = credentials.authorize(http)
     self.service = build('calendar', 'v3', http=http)
示例#14
0
 def get_service(self):
     """
     :return: servicio de drive
     """
     credentials = AccessTokenCredentials(self.token, None)
     http = httplib2.Http()
     http = credentials.authorize(http)
     return build('drive', 'v2', http)
示例#15
0
文件: views.py 项目: rmad17/calsync
def connect_helper(user):
    social = user.social_auth.get(provider='google-oauth2')
    access_token = social.extra_data.get('access_token')
    credentials = AccessTokenCredentials(access_token, 'my-user-agent/1.0')
    http = httplib2.Http()
    http = credentials.authorize(http)
    service = build(serviceName='calendar', version='v3', http=http)
    return service
示例#16
0
def authorized_request(user, url):
    access_token = get_access_token(user)
    if access_token:
        credentials = AccessTokenCredentials(access_token, 'my-user-agent/1.0')
        http = httplib2.Http()
        http = credentials.authorize(http)
        response = do_request(http, url)
        return response
示例#17
0
 def get_authenticated_service(self):
     """ Create youtube oauth2 connection """
     credentials = AccessTokenCredentials(
         access_token=self.get_auth_code(),
         user_agent='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'
     )
     return build(
         'youtube', 'v3', http=credentials.authorize(httplib2.Http())
     )
示例#18
0
def get_authenticated_service():
    """ Create youtube oauth2 connection """
    # make credentials with refresh_token auth
    credentials = AccessTokenCredentials(access_token=get_auth_code(),
                                         user_agent='insta-python/1.0')
    # create connection to youtube api
    return build(YOUTUBE_API_SERVICE_NAME,
                 YOUTUBE_API_VERSION,
                 http=credentials.authorize(httplib2.Http()))
示例#19
0
def get_email(access_token):
    creds = AccessTokenCredentials(access_token, 'fooapi/0.1')
    h = creds.authorize(Http())
    resp, content = h.request(app.config['GOOGLE_API_INFO_URL'])
    if resp['status'] != '200':
        raise UserProfileAccessException('Unable to access the user profile.')

    data = json.loads(content)
    return  data['email']
示例#20
0
 def get_service(self, serviceName, version):
     token = self.get_access_token()
     credentials = AccessTokenCredentials(token,
                                          'Demisto Gmail integration')
     if PROXY or DISABLE_SSL:
         http_client = credentials.authorize(
             self.get_http_client_with_proxy())
         return discovery.build(serviceName, version, http=http_client)
     return discovery.build(serviceName, version, credentials=credentials)
示例#21
0
def executor(userId):
    bucket_name = "jingle-skill-bucket"
    s3 = boto3.client('s3')

    try:
        # Download the token.
        s3.download_file(bucket_name, 'data/' + str(userId) + '/token.pkl',
                         "/tmp/" + str(userId) + '_token.pkl')

        # Read-in the access token.
        access_token = pickle.load(
            open("/tmp/" + str(userId) + '_token.pkl', "rb"))
        credentials = AccessTokenCredentials(access_token, 'alexa-skill/1.0')
        http = credentials.authorize(httplib2.Http())
        service = build('gmail', 'v1', http=http)

        try:
            # Download the existing all_mails object and last_mail_id from the bucket if available.
            s3.download_file(bucket_name,
                             'data/' + str(userId) + '/all_mails.pkl',
                             "/tmp/" + str(userId) + '_all_mails.pkl')
            s3.download_file(bucket_name,
                             'data/' + str(userId) + '/last_mail_id.pkl',
                             "/tmp/" + str(userId) + '_last_mail_id.pkl')

            # Read-in both the files.
            all_mails = pickle.load(
                open("/tmp/" + str(userId) + '_all_mails.pkl', "rb"))
            last_mail_id = pickle.load(
                open("/tmp/" + str(userId) + '_last_mail_id.pkl', "rb"))
        except:
            # Read-in both the files.
            all_mails = None
            last_mail_id = None

        last_mail_id, all_mails = get_emails(last_mail_id, all_mails, service)

        checklist = []
        # Get the required information.
        for i in all_mails:
            # Construct the summary for each mail object.
            all_mails[i] = summarize_body(all_mails[i])

            # Get the dates for the mail as well.
            all_mails[i] = end_date_getter(all_mails[i])

            # It keeps appending the new checklist tasks to the existing set of checklist tasks across all the sender_email tags.
            checklist = get_checklist_objects(all_mails[i], checklist)

        # Write items into the bucket, and notify SQS.
        write_checklist(checklist, last_mail_id, all_mails, userId)

        return 'Success!'

    except:
        return 'Failue!'
示例#22
0
def get_user_email_from_token(access_token):
    if debug: print >> sys.stderr,'Called '+sys._getframe().f_code.co_name
    user_email = None
    credentials = AccessTokenCredentials(access_token, 'test-user')
    http = credentials.authorize(httplib2.Http())
    user_info_service = build('oauth2', 'v2', http=http)
    user_info = user_info_service.userinfo().get().execute()
    if 'email' in user_info:
        user_email = user_info['email']
    return user_email
示例#23
0
def create_service(userid):
    """
    :param userid:  currently logged in user
    :return: gmail api service instance for making gmail api calls (eg. Sending email in this case )
    """
    user = User.query.get(int(userid))
    data = json.loads(user.tokens)
    credentials = AccessTokenCredentials(data['access_token'], None)
    service = build('gmail', 'v1', http=credentials.authorize(Http()))
    return service
示例#24
0
 def get_authenticated_service(self,
                               access_token,
                               service='youtube',
                               version='v3'):
     credentials = AccessTokenCredentials(access_token=access_token,
                                          user_agent='Podcast')
     return build(service,
                  version,
                  cache_discovery=False,
                  http=credentials.authorize(httplib2.Http()))
class AccessTokenCredentialsTests(unittest.TestCase):
    def setUp(self):
        access_token = "foo"
        user_agent = "refresh_checker/1.0"
        self.credentials = AccessTokenCredentials(access_token, user_agent)

    def test_token_refresh_success(self):
        # Older API (GData) respond with 403
        for status_code in ['401', '403']:
            http = HttpMockSequence([
                ({
                    'status': status_code
                }, ''),
            ])
            http = self.credentials.authorize(http)
            try:
                resp, content = http.request("http://example.com")
                self.fail("should throw exception if token expires")
            except AccessTokenCredentialsError:
                pass
            except Exception:
                self.fail("should only throw AccessTokenCredentialsError")

    def test_non_401_error_response(self):
        http = HttpMockSequence([
            ({
                'status': '400'
            }, ''),
        ])
        http = self.credentials.authorize(http)
        resp, content = http.request('http://example.com')
        self.assertEqual(400, resp.status)

    def test_auth_header_sent(self):
        http = HttpMockSequence([
            ({
                'status': '200'
            }, 'echo_request_headers'),
        ])
        http = self.credentials.authorize(http)
        resp, content = http.request('http://example.com')
        self.assertEqual('Bearer foo', content['Authorization'])
示例#26
0
    def __init__(self, access_token, collection_name=''):
        
        '''
            a method to initialize the driveClient class
            
        :param access_token: string with oauth2 access token for users account
        :param collection_name: [optional] string with name of collection for import
        '''    

        title = '%s.__init__' % self.__class__.__name__
    
    # construct input validation model
        self.fields = jsonModel(self._class_fields)
        
    # validate inputs
        input_fields = {
            'access_token': access_token,
            'collection_name': collection_name
        }
        for key, value in input_fields.items():
            object_title = '%s(%s=%s)' % (title, key, str(value))
            self.fields.validate(value, '.%s' % key, object_title)
    
    # construct access token
        self.access_token = access_token
        
    # construct drive client
        import httplib2
        from googleapiclient import discovery
        from oauth2client.client import AccessTokenCredentials
        google_credentials = AccessTokenCredentials(self.access_token, 'my-user-agent/1.0')
        google_http = httplib2.Http()
        google_http = google_credentials.authorize(google_http)
        google_drive = discovery.build('drive', 'v3', http=google_http)
        self.drive = google_drive.files()
    
    # construct collection properties
        self.permissions_write = True
        self.permissions_content = True
        self.drive_space = 'drive'
        self.space_id = ''
        if collection_name:
            self.collection_name = collection_name
        else:
            self.collection_name = 'My Drive'
    
    # construct file object
        from labpack import __module__
        from jsonmodel.loader import jsonLoader
        drive_rules = jsonLoader(__module__, 'storage/google/drive-rules.json')
        self.object_file = drive_rules['file_object']
        
    # validate access token
        self._validate_token()
示例#27
0
 def get_client(self):
     """
     Get an authenticated calendar api v3 instance.
     """
     token = self.get_access_token()
     if self.client is None:
         credentials = AccessTokenCredentials(token, 'vetware/1.0')
         # credentials = SignedJwtAssertionCredentials(self.email, self.private_key,
         #                                             "https://www.googleapis.com/auth/calendar")
         http = credentials.authorize(Http())
         self.client = build('calendar', 'v3', http=http)
     return self.client
示例#28
0
 def dispatch(self):
     self._checkauth()
     self._decode()
     if self._token is None:
         self.abort(401)
     else:
         credentials = AccessTokenCredentials(self._token, "mirror-api-upload-handler/1.0")
         http = httplib2.Http()
         http = credentials.authorize(http)
         http.timeout = 60
         self._service = build("mirror", "v1", http=http, discoveryServiceUrl=utils.discovery_service_url)
         super(UploadHandler, self).dispatch()
示例#29
0
def authenticate(service,
                 discovery,
                 version,
                 sub=None,
                 access_token=None,
                 http=None):
    """
    Authenticate to the Gmail API with the account specified by 'sub'.

    :param service: The API service object to authentication.
    :param discovery: The service descriptor file to use for API endpoint discovery.
    :param version: The version of the Gmail API to authentication to.
    :param sub: (optional) The user to authenticate the service object to.
    :param access_token: (optional) The OAuth2 token (usually from the cache) to use for authentication.
    :param http: Optional HTTP object to use (used in tests).
    :return: A tuple of (the authenticated credential object, the authenticated http object,
             and the service object).
    """

    if access_token:
        credentials = AccessTokenCredentials(access_token,
                                             user_agent="mailbeaker/1.0")
    else:
        logging.info("No access_token provided, establishing new token.",
                     extra={"email": sub})

        key = settings.GOOGLE_OAUTH2_PRIVATE_KEY
        credentials = \
            SignedJwtAssertionCredentials(service_account_name=settings.GOOGLE_OAUTH2_SERVICE_ACCOUNT_EMAIL,
                                          private_key=key,
                                          scope=settings.GOOGLE_OAUTH2_SCOPE,
                                          sub=sub)

    if not http:
        # Authorize the httplib2.Http object with our credentials
        http = httplib2.Http()
        http = credentials.authorize(http)

    # We'll read the description of this API's function from
    # a JSON input file. Normally the client reaches out to either:
    # - https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest
    # - https://www.googleapis.com/discovery/v1/apis/admin/directory_v1/rest
    # ... to get this information via apiclient.discovery.build(),
    # but that method causes a significant perfomance impact.
    path = os.path.dirname(os.path.realpath(__file__))
    path = os.path.join(path, discovery)
    discovery = open(path).read()
    service = build_from_document(discovery,
                                  http=http,
                                  base="https://www.googleapis.com/")

    return credentials, http, service
示例#30
0
def connect_helper(user):
    c = user.social_auth.get(provider='google-oauth2')
    access_token = c.tokens['access_token']

    credentials = AccessTokenCredentials(access_token, 'my-user-agent/1.0')
    http = httplib2.Http()
    http = credentials.authorize(http)
    service = build(serviceName='calendar',
                    version='v3',
                    http=http,
                    developerKey='...')

    return service
示例#31
0
def add_to_google_calendar(event_id, selection_source):
    """
    Adds event to user's google calendar

    Arguments:
        event_id (str): id of the event being selected
        selection_source (str): location of link

    Returns:
        resp (Flask Response): Varies depending on whether user is logged in
    """
    if current_user.is_authenticated:
        try:
            # adds user selection to database
            selected_event = EventSelection(
                user_id=current_user.id,
                event_id=event_id,
                selection_type='calendar',
                selection_source=selection_source,
                date_selected=datetime.datetime.today())
            db.session.add(selected_event)
            db.session.commit()

            # gets google calendar event of object
            event = db.session.query(Event).filter_by(
                id=event_id).one().google_calendar_event

            # add event to google calendar
            credentials = AccessTokenCredentials(current_user.token, None)
            http = credentials.authorize(httplib2.Http())
            service = discovery.build('calendar', 'v3', http=http)
            event = service.events().insert(calendarId='primary',
                                            body=event).execute()

            # redirect user to main page
            flash('Event added to Google Calendar', 'success')
            resp = make_response(redirect(url_for('all_events_viewer')))
            resp.set_cookie('add_event', 'false')
            resp.set_cookie('scroll_position', 'event_{}'.format(event_id))
            return resp

        # if user token has expired log the user out and redirect to login page
        except AccessTokenCredentialsError:
            logout_user()

    resp = make_response(redirect(url_for('login')))
    resp.set_cookie('event_id', event_id)
    resp.set_cookie('selection_source', selection_source)
    resp.set_cookie('add_event', 'true')
    return resp
示例#32
0
def get_authenticated_service():
    """ Create youtube oauth2 connection """
    # make credentials with refresh_token auth
    credentials = AccessTokenCredentials(access_token=get_auth_code(), user_agent='insta-python/1.0')
    # create httplib proxy connection
    if settings.USE_PROXY:
        import socks
        # set socks proxy to ssh tunnel
        socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, 'localhost', 1080)
        # wrap httplib via proxy
        socks.wrapmodule(httplib2)
    # create connection to youtube api
    return build(
        settings.YOUTUBE_API_SERVICE_NAME, settings.YOUTUBE_API_VERSION, http=credentials.authorize(httplib2.Http()))
示例#33
0
def loggedin(request):
    try: 
        link = UserSocialAuth.get_social_auth_for_user(request.user).get().tokens

        access_token = link['access_token']

        # OAuth dance
        credentials = AccessTokenCredentials(access_token, 'my-user-agent/1.0')
        http = httplib2.Http()
        http = credentials.authorize(http)
        service = build('calendar', 'v3', http=http)


        # Snippet that lists all calendar events
        #request = service.events().list(calendarId='primary')
        
        #while request != None:
          ## Get the next page.
          #response = request.execute()
          ## Accessing the response like a dict object with an 'items' key
          ## returns a list of item objects (events).
          #for event in response.get('items', []):
            ## The event object is a dict object with a 'summary' key.
            #print repr(event.get('summary', 'NO SUMMARY')) + '\n'
          ## Get the next request object by passing the previous request object to
          ## the list_next method.
          #request = service.events().list_next(request, response)

        #except AccessTokenRefreshError:
        ## The AccessTokenRefreshError exception is raised if the credentials
        ## have been revoked by the user or they have expired.
        #print ('The credentials have been revoked or expired, please re-run'
               #'the application to re-authorize')

        # working event
        event = {
          'summary': "summary",
          'description': "description",
          'start' : { 'dateTime' : "2013-04-01T15:00:00.000Z"},
          'end' : { 'dateTime' : "2013-04-01T17:00:00.000Z"}
        }


        #created_event = service.events().insert(calendarId='primary', body=event).execute()

        #print "Created Event: %s" % created_event['id']
        return render_to_response("loggedin.html", RequestContext(request))

    except: 
        return render_to_response("main.html", RequestContext(request))
示例#34
0
    def file_authed(self, request1):
        if request1.times == 1:

            current_user = endpoints.get_current_user()
            if "HTTP_AUTHORIZATION" in os.environ:
                (tokentype,
                 token) = os.environ["HTTP_AUTHORIZATION"].split(" ")

            credentials = AccessTokenCredentials(token, 'my-user-agent/1.0')
            http = httplib2.Http()
            #http = credentials.authorize(http)

            service = discovery.build('drive', 'v2', http=http)
            #storage = StorageByKeyName(CredentialsModel, current_user.user_id(), 'credentials')
            #credentials = storage.get()
            http = credentials.authorize(http)

            body = {
                'title': request1.filename,
                'description': 'Encrypted',
                'mimeType': 'text/plain'
            }

            media_body = MediaIoBaseUpload(StringIO.StringIO(
                request1.filedata),
                                           'text/plain',
                                           resumable=False)

            results = service.files().insert(body=body,
                                             media_body=media_body).execute()

            fileReturn = FileResponse()
            fileReturn.filename = request1.filename
            fileReturn.filedata = request1.filedata
            fileReturn.user = (current_user.email()
                               if current_user is not None else 'Anonymous')
            return fileReturn  #Greeting(message='hello %s' % (email,))
        else:
            dbx = dropbox.Dropbox('REPLACE THIS WITH YOUR DROPBOX API KEY')
            #dbx.users_get_current_account()
            fileplus = '/' + request1.filename + '.txt'
            dbx.files_upload(StringIO.StringIO(request1.filedata), fileplus)
            fileReturn = FileResponse()
            fileReturn.filename = request1.filename
            fileReturn.filedata = request1.filedata
            fileReturn.user = (current_user.email()
                               if current_user is not None else 'Anonymous')
            return fileReturn
def index():
    try:
        http = httplib2.Http()
        access_token = getAccessToken()
        credentials = AccessTokenCredentials(access_token, 'my-user-agent/1.0')
        http = httplib2.Http()
        http = credentials.authorize(http)
        service = build(serviceName='oauth2', version='v2', http=http)
        resp = service.userinfo().get().execute()
        email = resp['email']
        resp = service.tokeninfo(access_token=access_token).execute()
        return Response(json.dumps(resp, sort_keys=True, indent=4),
                        mimetype='application/json')
    except Exception as e:
        logging.error("Error: " + str(e))
        abort(500)
示例#36
0
 def validate_google(self, access_token, uid):
     try:
         credential = AccessTokenCredentials(access_token, 'jasonpi/1.0')
     except AccessTokenCredentialsError:
         raise exceptions.ValidationError(_('Invalid access token'))
     http = httplib2.Http()
     http = credential.authorize(http)
     service = build("people", "v1", http=http)
     user = service.people().get(
         resourceName='people/me',
         personFields='addresses,emailAddresses,names,genders,birthdays'
     ).execute()
     user_id = user['resourceName'].split('/')[1]
     if uid != user_id:
         raise exceptions.ValidationError(
             _('Google user id doesn\'t match'))
     return google_profile(user)
示例#37
0
    def __init__(self, user):
        self._user = user
        self._name = user.email
        self._error = False

        dev_key = config['GOOGLE_DEVELOPERS_KEY']
        try:
            credentials = AccessTokenCredentials(user.access_token, 'intranet/1.0')
        except Exception as e:
            self._error = True
            EXCEPTION("Can't refresh token for user %s: %s" % (user.email, e))
            return

        http = httplib2.Http()
        http = credentials.authorize(http)
        self._service = build(serviceName='calendar', version='v3', http=http,
           developerKey=dev_key)
示例#38
0
 def dispatch(self):
     self._checkauth()
     self._decode()
     if self._token is None:
         self.abort(401)
     else:
         credentials = AccessTokenCredentials(
             self._token, "mirror-api-upload-handler/1.0")
         http = httplib2.Http()
         http = credentials.authorize(http)
         http.timeout = 60
         self._service = build(
             "mirror",
             "v1",
             http=http,
             discoveryServiceUrl=utils.discovery_service_url)
         super(UploadHandler, self).dispatch()
示例#39
0
def getDriveService():
    #Gets the drive service instance using google drive credentials
    
    #Takes: nothing
    #Returns: a drive service instance
    
    try:
        #Google Drive Credentials (unique per account)
        ClientID = '230798942269.apps.googleusercontent.com'
        ClientSecret = 'JZ7dyNbQEHQ9XLXHxcFlcAad'
        OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive'
        REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
        
        SavedRefreshToken = '1/WjgLdc0RekqCu0s5uae1dJm9ZbmyufQWulsaXdvu3b8'
        
        h = Http(disable_ssl_certificate_validation=True)
        post_data = {'client_id':ClientID,
                     'client_secret':ClientSecret,
                     'refresh_token':SavedRefreshToken,
                     'grant_type':'refresh_token'}
        headers = {'Content-type': 'application/x-www-form-urlencoded'}
        resp, content = h.request("https://accounts.google.com/o/oauth2/token", 
                                  "POST", 
                                  urlencode(post_data),
                                  headers=headers)
        content2 = content.split()
        access_token = content2[3]
        access_token = access_token.replace('"', '')
        access_token = access_token.replace(',', '')
        
        #Exchange the code / access token for credentials
        credentials = AccessTokenCredentials(access_token, ClientID)
        
        #Intialize the drive service and return it
        http = Http(disable_ssl_certificate_validation=True)
        http = credentials.authorize(http)
        return build('drive', 'v2', http=http)
    
    #Error may occur if the user's network is down
    except httplib2.ServerNotFoundError:
        sys.exit('Can not connect to Google Drive. Please check internet connection.')
        
    #Unexpected error may occur
    except httplib2.HttpLib2Error, e:
        sys.exit('httplib2 exception: ' + str(e))
示例#40
0
def sync_youtube_videos(userobj=None):
    playlist_users = Playlist.objects.exclude(youtube_pl_id__exact=None).\
        filter(youtube_last_err=None)
    playlist_users = Playlist.objects.exclude(youtube_pl_id__exact=None)
    if userobj:
        playlist_users = playlist_users.filter(user=userobj)

    for user_items in playlist_users:
        userobj = user_items.user.social_auth.get(provider='google-oauth2')
        credentials = AccessTokenCredentials(
            userobj.extra_data.get('access_token'),  'friendlyvibe/1.0')
        youtube = build(
            'youtube', 'v3', http=credentials.authorize(httplib2.Http()))

        for plitem in user_items.playlistitem_set.filter(youtube_synced=None):
            video_add = {}
            try:
                video_add = youtube.playlistItems().insert(
                    part="snippet",
                    body=dict(
                        snippet=dict(
                            playlistId=user_items.youtube_pl_id,
                            resourceId=dict(
                                kind='youtube#video',
                                videoId=plitem.item_obj.source_identifier
                            ),
                            position=0
                        )
                    )
                ).execute()
            except AccessTokenCredentialsError, e:
                # refresh the token
                strategy = load_strategy(backend='google-oauth2')
                userobj.refresh_token(strategy)
            except Exception, e:
                # record the error so next time we won't attempt to send it
                plitem.playlist_obj.youtube_last_err = str(e)
                plitem.playlist_obj.save()

            # make a note of the successfull answer
            if video_add.get('id'):
                plitem.youtube_synced = True
                plitem.youtube_data = simplejson.dumps(video_add)
                plitem.youtube_synced = datetime.datetime.now()
                plitem.save()
示例#41
0
def getUserDetails():
  access_token = session.get('credentials')
  credentials = AccessTokenCredentials(access_token, 'user-agent-value')

  # Only fetch a list of people for connected users.
  if credentials is None:
    raise Exception("Current user not connected")
  try:
    # Create a new authorized API client.
    http = httplib2.Http()
    http = credentials.authorize(http)
    people_resource = SERVICE.people()
    people_document = people_resource.get(userId='me').execute(http=http)
    gplusId = people_document['id']
    name = people_document['displayName']
    return {'gplusId': gplusId,'name': name}
  except AccessTokenRefreshError:
    raise Exception("Failed to refresh access token")
示例#42
0
class Gmail(object):

    def __init__(self, access_token=None):
        self.credentials = AccessTokenCredentials(access_token, user_agent='')
        self._http = self.credentials.authorize(httplib2.Http())
        self.gmail_service = build('gmail', 'v1', http=self._http)

    def get_messages(self, msg_ids=[]):
        results = dict()
        for m_id in msg_ids:
            msg = self.gmail_service.users().messages().get(userId='me',
                                                            id=m_id).execute()
            if msg:
                headers = msg.get('payload').get('headers')
                temp = dict()
                for i in headers:
                    if i.get('name') in ['Subject', 'To', 'From']:
                        temp[i.get('name')] = i.get('value')
                temp['snippet'] = msg.get('snippet')
                temp['datetime'] = msg.get('internalDate')
                temp['datetime'] = dt.fromtimestamp(int(temp['datetime']) // 1000)
                if temp['From'] in results:
                    results[temp['From']].append(temp)
                else:
                    results[temp['From']] = [temp]
        return results

    def get_list_of_msgid(self, epoch_after='', emails=[], msg_type='unread'):
        ''' epoch_after : epoch in sec and get message after this epoch
            emails: list of emails
            is:unread AND after:epoch_after AND (email1 OR email2)
        '''
        query = 'is:' + msg_type
        if epoch_after:
            query += ' AND after:' + epoch_after

        if emails:
            q2 = ' OR '.join(['from:' + str(i) for i in emails])
            query += ' AND (' + q2 + ' )'

        results = self.gmail_service.users().messages().list(userId='me',
                                                             q=query).execute().get('messages', [])
        msg_ids = [message.get('id') for message in results]
        return self.get_messages(msg_ids=msg_ids)
示例#43
0
def authenticate(service, discovery, version, sub=None, access_token=None, http=None):
    """
    Authenticate to the Gmail API with the account specified by 'sub'.

    :param service: The API service object to authentication.
    :param discovery: The service descriptor file to use for API endpoint discovery.
    :param version: The version of the Gmail API to authentication to.
    :param sub: (optional) The user to authenticate the service object to.
    :param access_token: (optional) The OAuth2 token (usually from the cache) to use for authentication.
    :param http: Optional HTTP object to use (used in tests).
    :return: A tuple of (the authenticated credential object, the authenticated http object,
             and the service object).
    """

    if access_token:
        credentials = AccessTokenCredentials(access_token, user_agent="mailbeaker/1.0")
    else:
        logging.info("No access_token provided, establishing new token.",
                     extra={"email": sub})

        key = settings.GOOGLE_OAUTH2_PRIVATE_KEY
        credentials = \
            SignedJwtAssertionCredentials(service_account_name=settings.GOOGLE_OAUTH2_SERVICE_ACCOUNT_EMAIL,
                                          private_key=key,
                                          scope=settings.GOOGLE_OAUTH2_SCOPE,
                                          sub=sub)

    if not http:
        # Authorize the httplib2.Http object with our credentials
        http = httplib2.Http()
        http = credentials.authorize(http)

    # We'll read the description of this API's function from
    # a JSON input file. Normally the client reaches out to either:
    # - https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest
    # - https://www.googleapis.com/discovery/v1/apis/admin/directory_v1/rest
    # ... to get this information via apiclient.discovery.build(),
    # but that method causes a significant perfomance impact.
    path = os.path.dirname(os.path.realpath(__file__))
    path = os.path.join(path, discovery)
    discovery = open(path).read()
    service = build_from_document(discovery, http=http, base="https://www.googleapis.com/")

    return credentials, http, service
    def set(self, **kwargs):
        kwargs = self.filter(kwargs)
        db = sqlite3.connect(self.db_path)
        cursor = db.cursor()

        #get information from calling android device
        input = json.loads(json.dumps(kwargs))
        try:
            app = input['app']
            preset = input['preset']
            accesstoken = input['accesstoken']
        except KeyError:
            cursor.close()
            db.close()
            return "error: invalid input"
        try:
            radius = input['radius']
        except KeyError:
            radius = -2

        #get user id from google with access token
        try:
            credentials = AccessTokenCredentials(accesstoken, 'my-user-agent/1.0')
            http = httplib2.Http()
            http = credentials.authorize(http)
            service = build('oauth2', 'v2', http=http)
            userinfo = service.userinfo().get().execute()
            user = hashlib.sha256(userinfo['id']).hexdigest()
        except oauth2client.client.AccessTokenCredentialsError:
            cursor.close()
            db.close()
            return "error: The access_token is expired or invalid and can't be refreshed"

        try:
            cursor.execute("INSERT INTO configuration(app, user, preset, radius) VALUES(?, ?, ?, ?)", (app, user, preset, radius,))
            answer = "insert successfull"
        except sqlite3.IntegrityError:
            cursor.execute("UPDATE configuration SET preset = ?, radius = ? WHERE app = ? AND user = ?", (preset, radius, app, user, ))
            answer = "update successfull"

        db.commit()
        cursor.close()
        db.close()
        return answer
    def __init__(self, user):
        self._user = user
        self._name = user.email
        self._error = False

        dev_key = config['GOOGLE_DEVELOPERS_KEY']
        try:
            credentials = AccessTokenCredentials(user.access_token, 'intranet/1.0')
            http = httplib2.Http()
            http = credentials.authorize(http)
            self._service = build(
                serviceName='calendar',
                version='v3',
                http=http,
               developerKey=dev_key
            )
        except Exception as e:
            self._error = True
            EXCEPTION("Can't refresh token for user %s: %s" % (user.email, e))
示例#46
0
    def _authorise(self):
        """Gets AccessTokenCredentials with the ACCESS_TOKEN and USER_AGENT and
        authorises a httplib2 http object.

        If this has already been done, does nothing."""
        if self.http is not None:
            return
        assert self.ACCESS_TOKEN is not None

        # if cred.user_agent is not none, then it adds appends the
        # user-agent to the end of the existing user-agent string
        # each time request() is called...
        # ...Until you get a "headers too long" error.
        # so make it None
        cred = AccessTokenCredentials(self.ACCESS_TOKEN, None)

        # NationBuilder has a lot of problems with their SSL certs...
        self.http = httplib2.Http(disable_ssl_certificate_validation=True)
        self.http = cred.authorize(self.http)
示例#47
0
  def file_authed(self, request1):
    if request1.times == 1:
        
        current_user = endpoints.get_current_user()
        if "HTTP_AUTHORIZATION" in os.environ:
          (tokentype, token)  = os.environ["HTTP_AUTHORIZATION"].split(" ")

        credentials = AccessTokenCredentials(token, 'my-user-agent/1.0')
        http = httplib2.Http()
        #http = credentials.authorize(http)

        service = discovery.build('drive', 'v2', http=http)
        #storage = StorageByKeyName(CredentialsModel, current_user.user_id(), 'credentials')
        #credentials = storage.get()
        http = credentials.authorize(http)
        
        body = {'title':request1.filename,
                'description':'Encrypted',
                'mimeType':'text/plain'}

        media_body = MediaIoBaseUpload(StringIO.StringIO(request1.filedata), 'text/plain',resumable=False)
        
        
        results = service.files().insert(body=body,media_body=media_body).execute()
        
        fileReturn = FileResponse()
        fileReturn.filename = request1.filename
        fileReturn.filedata = request1.filedata
        fileReturn.user = (current_user.email() if current_user is not None
                 else 'Anonymous')
        return fileReturn #Greeting(message='hello %s' % (email,))
    else:
        dbx = dropbox.Dropbox('REPLACE THIS WITH YOUR DROPBOX API KEY')
        #dbx.users_get_current_account()
        fileplus = '/'+request1.filename+'.txt'
        dbx.files_upload(StringIO.StringIO(request1.filedata),fileplus)
        fileReturn = FileResponse()
        fileReturn.filename = request1.filename
        fileReturn.filedata = request1.filedata
        fileReturn.user = (current_user.email() if current_user is not None
         else 'Anonymous')
        return fileReturn
示例#48
0
def get_mails(request):
    credentials = AccessTokenCredentials(
        request.user.social_auth.get(
            provider="google-plus").extra_data.get('access_token'),
        'Testp/1.0')
    service = discovery.build('gmail',
                              'v1',
                              http=credentials.authorize(httplib2.Http()))
    nextPageToken = request.GET.get('nextPageToken')
    perpage = settings.EMAILS_PER_PAGE
    response = service.users().messages().list(
        userId='me', maxResults=perpage, pageToken=nextPageToken).execute()

    inbox = []
    result = {}
    if 'nextPageToken' in response:
        result['nextPageToken'] = response['nextPageToken']
    if 'messages' in response:
        for message in response['messages']:
            _message = service.users().messages().get(userId='me',
                                                      id=message.get('id'),
                                                      format='full').execute()
            mail = {}
            mail['snippet'] = _message.get('snippet')
            for head in _message.get('payload').get('headers'):
                if (head.get('name') == 'Subject'):
                    mail['subject'] = head.get('value')
                elif (head.get('name') == 'From'):
                    mail['from'] = head.get('value')
                elif (head.get('name') == 'To'):
                    mail['to'] = head.get('value')
                elif (head.get('name') == 'Date'):
                    mail['date'] = head.get('value')

                # mail['subject'] = ('', head.get('value'))[head.get('name') == 'Subject']
                # mail['from'] = ('', head.get('value'))[head.get('name') == 'From']
                # mail['to'] = ('', head.get('value'))[head.get('name') == 'To']
                # mail['date'] = ('', head.get('value'))[head.get('name') == 'Date']

            inbox.append(mail)
    result['emails'] = inbox
    return json.dumps(result)
示例#49
0
    def get_unknown_service(cls, credentials: Credentials,
                            **kwargs: Mapping[str, Any]):
        """Fetch a discoverable API service.

    If this is not the case (or, upon attempting to is the service an
    authorization error is raised) the service can be cleared and forced to
    reload.

    Args:

    Returns:
      service: a service for REST calls
    """
        credentials.get_credentials()
        _credentials = AccessTokenCredentials(
            credentials.token_details['access_token'], user_agent='report2bq')
        https = discovery.httplib2.Http()
        auth_https = _credentials.authorize(https)
        service = discovery.build(http=https, cache_discovery=False, **kwargs)
        return service
示例#50
0
文件: views.py 项目: pandotree/Ring
def show_docs(request):
    if request.method != 'GET':
        return HttpResponseServerError("Bad request type: " + request.method)
    http = httplib2.Http()
    instance = UserSocialAuth.objects.filter(provider='google-oauth2').get(user=request.user)

    token = instance.tokens['access_token']
    useragent = request.META['HTTP_USER_AGENT']
    credentials = AccessTokenCredentials(token, useragent)
    http = credentials.authorize(http)
    service = build('drive', 'v2', http=http)
    apirequest = service.files().list()
    while apirequest != None:
        response = apirequest.execute()
        for file in response.get('items', []):
            print repr(file.get('title')) + '\n'
        apirequest = service.files().list_next(apirequest, response)
    ctx = {
        'files': files
    }
    return render_to_response('documents.html', ctx, RequestContext(request))
示例#51
0
    def fileask_authed(self, request1):
        if request1.times == 1:

            current_user = endpoints.get_current_user()
            if "HTTP_AUTHORIZATION" in os.environ:
                (tokentype,
                 token) = os.environ["HTTP_AUTHORIZATION"].split(" ")

            credentials = AccessTokenCredentials(token, 'my-user-agent/1.0')
            http = httplib2.Http()
            #http = credentials.authorize(http)

            service = discovery.build('drive', 'v2', http=http)
            #storage = StorageByKeyName(CredentialsModel, current_user.user_id(), 'credentials')
            #credentials = storage.get()
            http = credentials.authorize(http)
            items = service.files().list(q="title = '" + request1.filename +
                                         "'").execute()['items']
            #drive_files = service.files().list(q="title = 'dan'").execute()
            download_url = items[0].get('downloadUrl')
            resp, content = service._http.request(download_url)

            fileReturn = FileResponse()
            fileReturn.filename = request1.filename
            fileReturn.filedata = content
            fileReturn.user = (current_user.email()
                               if current_user is not None else 'Anonymous')
            return fileReturn  #Greeting(message='hello %s' % (email,))
        else:
            dbx = dropbox.Dropbox('REPLACE THIS WITH YOUR DROPBOX API KEY')
            #dbx.users_get_current_account()
            fileplus = '/' + request1.filename + '.txt'
            dbx.files_upload(StringIO.StringIO(request1.filedata), fileplus)
            fileReturn = FileResponse()
            fileReturn.filename = request1.filename
            fileReturn.filedata = request1.filedata
            fileReturn.user = (current_user.email()
                               if current_user is not None else 'Anonymous')
            return fileReturn
示例#52
0
def showme():
    now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time

    token = json.loads(
        base64.urlsafe_b64decode(
            str(request.cookies.get('suez_authentication_key'))
        )
    )

    credentials = AccessTokenCredentials(
        token.get("access_token"),
        'my-user-agent/1.0')
    
    http = httplib2.Http()
    http = credentials.authorize(http)

    service = build('calendar', 'v3', http=http)

    response = []

    response.append('<html><body>')
    response.append('Getting the upcoming 10 events<br><br>')

    eventsResult = service.events().list(
        calendarId='primary', timeMin=now, maxResults=10, singleEvents=True,
        orderBy='startTime').execute()
    events = eventsResult.get('items', [])
        
    if not events:
        response.append('No upcoming events found.')
        return '<br>'.join(response)
        
    for event in events:
        start = event['start'].get('dateTime', event['start'].get('date'))
        response.append("<div>%s %s</div>" % (start, event['summary']))
        
    return ''.join(response)
示例#53
0
  def fileask_authed(self, request1):
    if request1.times == 1:
        
        current_user = endpoints.get_current_user()
        if "HTTP_AUTHORIZATION" in os.environ:
          (tokentype, token)  = os.environ["HTTP_AUTHORIZATION"].split(" ")

        credentials = AccessTokenCredentials(token, 'my-user-agent/1.0')
        http = httplib2.Http()
        #http = credentials.authorize(http)

        service = discovery.build('drive', 'v2', http=http)
        #storage = StorageByKeyName(CredentialsModel, current_user.user_id(), 'credentials')
        #credentials = storage.get()
        http = credentials.authorize(http)
        items = service.files().list(q="title = '" + request1.filename + "'").execute()['items']
        #drive_files = service.files().list(q="title = 'dan'").execute()
        download_url = items[0].get('downloadUrl')
        resp, content = service._http.request(download_url)

        fileReturn = FileResponse()
        fileReturn.filename = request1.filename
        fileReturn.filedata = content
        fileReturn.user = (current_user.email() if current_user is not None
                 else 'Anonymous')
        return fileReturn #Greeting(message='hello %s' % (email,))
    else:
        dbx = dropbox.Dropbox('REPLACE THIS WITH YOUR DROPBOX API KEY')
        #dbx.users_get_current_account()
        fileplus = '/'+request1.filename+'.txt'
        dbx.files_upload(StringIO.StringIO(request1.filedata),fileplus)
        fileReturn = FileResponse()
        fileReturn.filename = request1.filename
        fileReturn.filedata = request1.filedata
        fileReturn.user = (current_user.email() if current_user is not None
         else 'Anonymous')
        return fileReturn
示例#54
0
def getGoogleData(msg):
    # Path to the client_secret.json file downloaded from the Developer Console
    CLIENT_SECRET_FILE = "client_secret.json"

    # Check https://developers.google.com/gmail/api/auth/scopes for all available scopes
    OAUTH_SCOPE = "https://www.googleapis.com/auth/gmail.readonly"

    # Location of the credentials storage file
    STORAGE = Storage("gmail.storage")

    # Start the OAuth flow to retrieve credentials
    flow = flow_from_clientsecrets(CLIENT_SECRET_FILE, scope=OAUTH_SCOPE)
    http = httplib2.Http()

    # Try to retrieve credentials from storage or run the flow to generate them
    credentials = AccessTokenCredentials(msg, "my-user-agent/1.0")
    if credentials is None or credentials.invalid:
        credentials = run(flow, STORAGE, http=http)

    # Authorize the httplib2.Http object with our credentials
    http = credentials.authorize(http)

    # Build the Gmail service from discovery
    gmail_service = build("gmail", "v1", http=http)

    # Retrieve a page of threads
    messages = gmail_service.users().messages().list(userId="me", q="in:sent after:2014/09/01", maxResults=1).execute()

    messages = messages["messages"]
    datas = []
    for message in messages[0:1]:
        id = message["id"]
        data = gmail_service.users().messages().get(userId="me", id=id, format="full").execute()
        body = data["payload"]["body"]
        print data["snippet"]
        datas.append(data["snippet"])
    return datas
示例#55
0
    def build_from_access_token(self, access_token):
        """
        Instantiates the REST API client for the Proximity API. Full PyDoc for this
        client is available here: https://developers.google.com/resources/api-libraries/documentation/proximitybeacon/v1beta1/python/latest/index.html

        Args:
            access_token:
                a valid access token for the Proximity API.

        Returns:
            self, with a ready-to-use PB API client.
        """
        if self._client is not None:
            return self._client

        credentials = AccessTokenCredentials(access_token, 'python-api-client/1.0')

        http_auth = credentials.authorize(Http())
        self._client = build(PROXIMITY_API_NAME, PROXIMITY_API_VERSION,
                             http=http_auth,
                             cache_discovery=False,
                             discoveryServiceUrl=DISCOVERY_URI)

        return self
示例#56
0
def profile(request):
    """User logs in through google using python social login. Once the user is logged in, google calendar information is
    pulled from there account. Records of free times are created based on the time in betweeen events"""

    # Pulls information from database about the user
    user_social_auth = request.user.social_auth.get(provider='google-oauth2')
    access_token = user_social_auth.extra_data['access_token']
    calID=user_social_auth.uid
    credentials = AccessTokenCredentials(access_token, 'my-user-agent/1.0')
    http= httplib2.Http()
    http = credentials.authorize(http)

    # Builds service for google calendar
    service = build(serviceName='calendar', version='v3', http=http, developerKey='HFs_k7g6ml38NKohwrzfi_ii')
    current_datetime = datetime.datetime.now().isoformat()[:-3] + 'Z'
    calendar2 = service.events().list(calendarId=calID, timeMin=current_datetime, singleEvents=True,
                                      orderBy='startTime').execute()
    print calendar2
    # Loops through events and determines the time your calendar event ends, and how much time you have until your
    # next one
    for i in range(len(calendar2['items'])-1):
        next_start = calendar2['items'][i + 1]['start']['dateTime']
        current_end = calendar2['items'][i]['end']['dateTime']
        event = (str(calendar2['items'][i]['summary']))

        # Converts unicode information from Google into datetime objects
        curent_event_end_dateTime = datetime.datetime.strptime(current_end, '%Y-%m-%dT%H:%M:%S-07:00')
        next_event_start_dateTime = datetime.datetime.strptime(next_start, '%Y-%m-%dT%H:%M:%S-07:00')

        #find todays date
        current_date = datetime.datetime.now()

        #only allow freetimes for the next four weeks
        # if next_event_start_dateTime <= current_date + datetime.timedelta(weeks=4):

            # Currently only working with free slots greater than 3 hours
        difference = next_event_start_dateTime - curent_event_end_dateTime
        if difference >= datetime.timedelta(hours=3):

            # If freetime block is greater than 1 day, will create separate blocks of free time for each day
            if difference >= datetime.timedelta(days=1):
                hours_added = 12
                for j in range(difference.days):
                    if j == 0:
                        free_start_dateTime = curent_event_end_dateTime
                        free_end_dateTime = free_start_dateTime+relativedelta(hours=7)
                        free_time_start = free_start_dateTime.strftime('%Y-%m-%dT%H:%M:%S-07:00')
                        free_time_end = free_end_dateTime.strftime('%Y-%m-%dT%H:%M:%S-07:00')
                        free_time_amount = free_end_dateTime - free_start_dateTime
                    else:
                        free_start_dateTime = curent_event_end_dateTime + relativedelta(hours=hours_added)
                        free_end_dateTime = free_start_dateTime + relativedelta(hours=14)
                        free_time_start = free_start_dateTime.strftime('%Y-%m-%dT%H:%M:%S-07:00')
                        free_time_end = free_end_dateTime.strftime('%Y-%m-%dT%H:%M:%S-07:00')
                        free_time_amount = free_end_dateTime - free_start_dateTime
                    hours_added += 26
                    print free_time_end

                    FreeTimes.objects.create(
                        user=request.user,
                        free_time_start=free_time_start,
                        free_time_end=free_time_end,
                        free_time_amount=free_time_amount,
                        previous_event=event,
                        free_start_dateTime=free_start_dateTime,
                        free_end_dateTime=free_end_dateTime
                    )
            else:
                FreeTimes.objects.create(
                    user=request.user,
                    free_time_start=current_end,
                    free_time_end=next_start,
                    free_time_amount=difference,
                    previous_event=event,
                    free_start_dateTime=curent_event_end_dateTime,
                    free_end_dateTime=next_event_start_dateTime

                )
        # else:
        #     pass

    # Deletes any duplicate free times in database for current user
    duplicate_freeTimes = FreeTimes.objects.filter(user=request.user)
    for row in duplicate_freeTimes:
        if duplicate_freeTimes.filter(free_start_dateTime=row.free_start_dateTime).count() > 1:
            row.delete()
    success = {'success': 'success'}
    return HttpResponse(json.dumps(success), content_type="application/json")
示例#57
0
 def _init_service(self, token=None):
     token = token or self.source.get('access_token')
     creds = AccessTokenCredentials(token, 'panoply/1.0')
     http = creds.authorize(http=httplib2.Http())
     self._service = build('drive', 'v3', http=http)
示例#58
0
def parse_mail(email, token):

    credentials = AccessTokenCredentials(token, 'my-user-agent/1.0')
    http = httplib2.Http()
    http = credentials.authorize(http)
    service = discovery.build('gmail', 'v1', http=http)

    try:
        results = service.users().messages().list(userId=email,
                                                  labelIds=[label_id_one],
                                                  q=query).execute()
        if results['resultSizeEstimate'] != 0:
            mssg_list = results['messages']
            final_list = []
            for mssg in mssg_list:
                temp_dict = {}
                m_id = mssg['id']  # get id of individual message
                message = service.users().messages().get(
                    userId=email,
                    id=m_id).execute()  # fetch the message using API
                payld = message['payload']  # get payload of the message
                headr = payld['headers']  # get header of the payload

                for one in headr:  # getting the Subject
                    if one['name'] == 'Subject':
                        msg_subject = one['value']
                        temp_dict['Subject'] = msg_subject
                    else:
                        pass

                for two in headr:  # getting the date
                    if two['name'] == 'Date':
                        msg_date = two['value']
                        date_parse = (parser.parse(msg_date))
                        m_date = (date_parse.date())
                        temp_dict['Date'] = str(m_date)
                    else:
                        pass

                for three in headr:  # getting the Sender
                    if three['name'] == 'From':
                        msg_from = three['value']
                        temp_dict['Sender'] = msg_from
                    else:
                        pass

                temp_dict['Snippet'] = message[
                    'snippet']  # fetching message snippet

                try:
                    # Fetching message body
                    mssg_parts = payld['parts']  # fetching the message parts
                    part_one = mssg_parts[
                        0]  # fetching first element of the part
                    part_body = part_one[
                        'body']  # fetching body of the message
                    part_data = part_body[
                        'data']  # fetching data from the body
                    part_data1 = payld['parts'][0]['body']['data']
                    clean_one = part_data1.replace(
                        "-", "+")  # decoding from Base64 to UTF-8
                    clean_one = clean_one.replace(
                        "_", "/")  # decoding from Base64 to UTF-8
                    clean_two = base64.b64decode(bytes(
                        clean_one, 'UTF-8'))  # decoding from Base64 to UTF-8
                    soup = BeautifulSoup(clean_two, "lxml")
                    mssg_body = soup.body()
                    temp_dict['Message_body'] = mssg_body

                except:
                    pass

                temp_dict['Attachments'] = {}
                for part in message['payload']['parts']:
                    if part['filename']:

                        if 'data' in part['body']:
                            data = part['body']['data']
                        else:
                            att_id = part['body']['attachmentId']
                            att = service.users().messages().attachments().get(
                                userId=email, messageId=m_id,
                                id=att_id).execute()
                            data = att['data']
                            file_data = base64.urlsafe_b64decode(
                                data.encode('UTF-8'))
                            path = os.path.join(store_dir, part['filename'])
                            with open(path, 'wb') as f:
                                f.write(file_data)
                        temp_dict['Attachments'][part['filename']] = att_id

                final_list.append(
                    temp_dict
                )  # This will create a dictonary item in the final list
            return final_list

        else:
            return "No message with matching key words!"

    except HttpError as error:
        return 'An error occurred: %s' % error