def appPost(self, client):
   reset = self.request.get('reset_office')
   logging.info("request %s" % self.request)
   user_token = UserToken.get_from_cookie(self.request.cookies.get('session', None))
   if user_token and user_token.fs_id and reset:
     request = User.all().filter('id =', user_token.fs_id)
     user = request.get()
     if user:
       logging.info('deleting the user!')
       user.delete()
   self.redirect(CONFIG['auth_success_uri_mobile'])
Esempio n. 2
0
  def get(self):
    user_token = UserToken.get_from_cookie(self.request.cookies.get('session', None))
    is_authd = 'false'
    if user_token and user_token.fs_id:
      client = utils.makeFoursquareClient(user_token.token)
      try:
        client.users()
        is_authd = 'true'
      except InvalidAuth:
        user_token.delete()

    self.response.out.write(is_authd)
Esempio n. 3
0
    def get(self):
        try:
            error = self.request.get('error')
            if error == "access_denied":
                raise OAuthConnectDeniedException
            elif error:
                raise OAuthConnectErrorException

            code = self.request.get('code')
            if not code:
                raise OAuthConnectErrorException

            client = utils.makeFoursquareClient()
            access_token = client.oauth.get_token(code)
            if not access_token:
                raise OAuthConnectErrorException
            client.set_access_token(access_token)
        except OAuthConnectDeniedException:
            self.redirect(CONFIG['auth_denied_uri'])
            return
        except OAuthConnectErrorException:
            path = os.path.join(os.path.dirname(__file__),
                                'templates/connect_error.html')
            self.response.out.write(
                template.render(path, {'name': CONFIG['site_name']}))
            return

        user = client.users()  # returns the auth'd users info
        fs_user_id = user['user']['id']

        existing_token = UserToken.get_by_fs_id(fs_user_id)

        if existing_token:
            token = existing_token
        else:
            token = UserToken()

        token.token = access_token
        token.fs_id = fs_user_id
        token.put()

        session = UserSession.get_or_create_session(fs_user_id)
        cookie = Cookie.SimpleCookie()
        cookie['session'] = session.session
        cookie['session']['path'] = '/'
        cookie['session']['expires'] = email.utils.formatdate(time.time() +
                                                              (14 * 86400),
                                                              localtime=False,
                                                              usegmt=True)
        self.response.headers.add_header("Set-Cookie", cookie.output()[12:])
        isMobile = utils.isMobileUserAgent(self.request.headers['User-Agent'])
        redirect_uri = CONFIG[
            'auth_success_uri_mobile'] if isMobile else CONFIG[
                'auth_success_uri_desktop']
        self.redirect(redirect_uri)
Esempio n. 4
0
    def get(self):
        user_token = UserToken.get_from_cookie(
            self.request.cookies.get('session', None))
        is_authd = 'false'
        if user_token and user_token.fs_id:
            client = utils.makeFoursquareClient(user_token.token)
            try:
                client.users()
                is_authd = 'true'
            except InvalidAuth:
                user_token.delete()

        self.response.out.write(is_authd)
 def appGet(self, client):
   data = { 'configured' : False }
   user_token = UserToken.get_from_cookie(self.request.cookies.get('session', None))
   if not (user_token and user_token.fs_id):
     self.redirect(utils.generateFoursquareAuthUri(client.oauth.client_id))
   if user_token and user_token.fs_id:
     request = User.all().filter('id =', user_token.fs_id)
     user = request.get()
     if user and user.office_id:
       data['configured'] = True
       client.set_access_token(user_token.token)
       venue_info = client.venues(user.office_id)
       data['venue_name'] = venue_info['venue']['name']
   logging.info('data %s' % data)
   path = os.path.join(os.path.dirname(__file__), 'settings.html')
   self.response.out.write(template.render(path, data))
Esempio n. 6
0
  def fetchAccessTokens(self, userIds):
    dictFromCache = memcache.get_multi(userIds, key_prefix="token:")
    idsInCache = dictFromCache.keys()
    cachedTokens = {id : self.cacheToToken(dictFromCache[id]) for id in idsInCache}

    idsMissingFromCache = list(set(userIds) - set(idsInCache))
    fetchedTokens = {x.fs_id : x.token for x in UserToken.fetch_by_fs_ids(idsMissingFromCache)}

    if idsMissingFromCache:
      # Add all missing ones that we just fetched to the cache
      failedKeys = memcache.set_multi({id : self.tokenToCache(fetchedTokens.get(id)) for id in idsMissingFromCache},
                                      key_prefix="token:", time=86400)
      if failedKeys:
        logging.error('Memcache set failed on tokens for %s' % ', '.join(failedKeys))

    cachedTokens.update(fetchedTokens)
    return cachedTokens
Esempio n. 7
0
  def get(self):
    try:
      error = self.request.get('error')
      if error == "access_denied":
        raise OAuthConnectDeniedException
      elif error:
        raise OAuthConnectErrorException

      code = self.request.get('code')
      if not code:
        raise OAuthConnectErrorException

      client = utils.makeFoursquareClient()
      access_token = client.oauth.get_token(code)
      if not access_token:
        raise OAuthConnectErrorException
      client.set_access_token(access_token)
    except OAuthConnectDeniedException:
      self.redirect(CONFIG['auth_denied_uri'])
      return
    except Exception:
      path = os.path.join(os.path.dirname(__file__),
                          'templates/connect_error.html')
      self.response.out.write(template.render(path, {'name': CONFIG['site_name']}))
      return

    user = client.users()  # returns the auth'd users info
    fs_user_id = user['user']['id']

    existing_token = UserToken.get_by_fs_id(fs_user_id)

    if existing_token:
      token = existing_token
    else:
      token = UserToken()

    token.token = access_token
    token.fs_id = fs_user_id
    token.put()

    if not memcache.set('token:%s' % fs_user_id, access_token, 86400):
      logging.error('Memcache set during oauth on token for %s' % fs_user_id)
      memcache.delete('token:%s' % fs_user_id)

    session = UserSession.get_or_create_session(fs_user_id)
    cookie = Cookie.SimpleCookie()
    cookie['session'] = session.session
    cookie['session']['path'] = '/'
    cookie['session']['expires'] = email.utils.formatdate(time.time() + (14 * 86400), localtime=False, usegmt=True)
    self.response.headers.add_header("Set-Cookie", cookie.output()[12:])
    isMobile = utils.isMobileUserAgent(self.request.headers['User-Agent'])
    redirect_uri = CONFIG['auth_success_uri_mobile'] if isMobile else CONFIG['auth_success_uri_desktop']
    self.redirect(redirect_uri)
Esempio n. 8
0
  def getAuthdStatus(self):

    # Allow cross domain access from http://www.herewithfriends.com and http://herewithfriends.appspot.com
    if (self.request.headers.get('Origin') == "http://www.herewithfriends.com"
        and self.request.headers.get('Host') == "herewithfriends.appspot.com"):
      self.response.headers.add_header("Access-Control-Allow-Origin", "http://www.herewithfriends.com")
      self.response.headers.add_header("Access-Control-Allow-Credentials", "true")

    elif (self.request.headers.get('Origin') == "http://herewithfriends.appspot.com"
          and self.request.headers.get('Host') == "herewithfriends.appspot.com"):
      self.response.headers.add_header("Access-Control-Allow-Origin", "http://herewithfriends.appspot.com")
      self.response.headers.add_header("Access-Control-Allow-Credentials", "true")

    user_token = UserToken.get_from_cookie(self.request.cookies.get('session', None))
    is_authd = False
    name = ''
    settingsSummary = ''
    settingsLink = ''
    if user_token is not None and user_token.fs_id:
      client = utils.makeFoursquareClient(user_token.token)
      try:
        user = client.users()['user']
        tokenId = user['id']
        if (tokenId != user_token.fs_id):
          is_authd = False
          user_token.delete()
        else:
          is_authd = True
          name = (user.get('firstName', '') + ' ' + user.get('lastName', '')).strip(),
          settingsSummary = self.getPermissionsSummary(user_token.fs_id)
          settingsLink = "%s/settings?userId=%s&access_token=%s" % (
                          utils.getServer(), user_token.fs_id, user_token.token)

      except InvalidAuth:
        user_token.delete()

    self.response.out.write(json.dumps({'connected': is_authd,
                                        'name': name,
                                        'settingsSummary': settingsSummary,
                                        'settingsLink' : settingsLink}))
Esempio n. 9
0
  def verifiedAccessToken(self, userId, suppliedToken):
    savedToken = self.fetchAccessToken(userId)
    if (savedToken == suppliedToken):
      return suppliedToken
    elif (self.getUserIdFromToken(suppliedToken) == userId):
      # save updated token if record exists, or create a new record
      savedTokenObj = UserToken.get_by_fs_id(userId)
      if savedTokenObj is not None:
        newToken = savedTokenObj
      else:
        newToken = UserToken()

      newToken.token = suppliedToken
      newToken.fs_id = userId
      newToken.put()

      if not memcache.set('token:%s' % userId, self.tokenToCache(suppliedToken), 86400):
        logging.error('Memcache set failed on token for %s' % user_id)
        memcache.delete('token:%s' % userId)

      return suppliedToken
    else:
      return None
Esempio n. 10
0
  def friendCheckinTaskQueue(self):
    userId = self.request.get('userId')
    checkinId = self.request.get('checkinId')
    token = self.request.get('access_token')

    access_token = self.verifiedAccessToken(userId, token)
    if (access_token):
      client = utils.makeFoursquareClient(access_token)

      selectedUserParam = self.request.get('selected')
      logging.debug('selected = %s' % selectedUserParam)
      selectedUserIds = selectedUserParam.split('-')

      checkin_json = self.getCoreCheckin(checkinId, client)
      venueId = checkin_json['venue']['id']
      sourceName = checkin_json['user']['firstName']
      sourceId = checkin_json['user']['id']
      if (sourceId != userId):
        logging.error("User %s attempted to access checkin for user %s" % (userId, sourceId))
        self.error(400)
        return
      successComment = 'Check-in by %s.' % sourceName.encode('utf-8')
      newCheckin = dict({'venueId': venueId, 'broadcast': 'public', 'shout': successComment})
      if 'event' in checkin_json:
        newCheckin['eventId'] = checkin_json['event']['id']

      friends = client.users.friends()['friends']['items']
      allFriendIds = [friend['id'] for friend in friends if (friend.get('relationship', 'friend') == 'friend')]
      allowedFriendTokens = self.getFriendTokens(userId, allFriendIds)

      successNames = []
      disconnectedNames = []

      for selectedUserId in selectedUserIds:
        matching = [friend for friend in friends if friend['id'] == selectedUserId]
        token = allowedFriendTokens.get(selectedUserId)
        if (len(matching) > 0 and token is not None):
          friendObj = matching[0]
          client.set_access_token(token)
          try:
            friendCheckin = client.checkins.add(newCheckin)['checkin']
            if 'user' not in friendCheckin:
              friendCheckin['user'] = {'id': friendObj['id'], 'firstName': friendObj['firstName']}
            successNames.append(friendObj['firstName'])

            # Update history
            history = CheckinHistory()
            history.source_fs_id = sourceId
            history.target_fs_id = friendObj['id']
            history.target_fs_name = (friendObj.get('firstName', '') + ' ' + friendObj.get('lastName', '')).strip()
            history.put()

            ## successComment moved to shout instead of post due to complaints
            # self.makeContentInfo( checkin_json = friendCheckin,
            #                       content = json.dumps({'checkinFrom': sourceName}),
            #                       text = successComment,
            #                       post = True)
          except InvalidAuth:
            # If a user disconnects the app, we can then have an invalid token
            logging.info('invalid oauth - deleting token for %s' % friendObj['id'])
            disconnectedNames.append(friendObj['firstName'])
            tokenObj = UserToken.get_by_fs_id(selectedUserId)
            if (tokenObj is not None):
              tokenObj.delete()
              memcache.delete('token:%s' % selectedUserId)

          except Exception as inst:
            logging.error('Failed to check in user %s-%s: %s' % (friendObj['firstName'], friendObj['id'], str(inst)))

      client.set_access_token(access_token) # restore token to original user
      successNamesStr = ", ".join(successNames)
      disconnectedNamesStr = ", ".join(disconnectedNames)

      if (len(successNames) > 0):
        message = "You just checked in: %s" % successNamesStr
        self.makeContentInfo( checkin_json = checkin_json,
                              content = json.dumps({'successNames': successNames, 'message': message}),
                              text = message,
                              post = True)

      if (len(disconnectedNames) > 0):
        message = "Failed to check in the following users as they have disconnected the app: %s" % disconnectedNamesStr
        self.makeContentInfo( checkin_json = checkin_json,
                              content = json.dumps({'disconnectedNames': disconnectedNames, 'message': message}),
                              text = message,
                              post = True)

      logging.info('%s (%s) checked in: %s' % (sourceName, sourceId, successNamesStr))
      self.response.out.write(json.dumps({'successNames': successNames}))
	def fetchAccessToken(self, user_id):
		request = UserToken.all()
		request.filter("fs_id =", str(user_id))
		user_token = request.get()
		return user_token.token if user_token else None
 def fetchAccessToken(self, user_id):
     request = UserToken.all()
     request.filter("fs_id = ", str(user_id))
     user_token = request.get()
     return user_token.token if user_token else None