Ejemplo n.º 1
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)
Ejemplo n.º 2
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)
Ejemplo n.º 3
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
Ejemplo n.º 4
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}))