Esempio n. 1
0
def api_register_fbuser(*, email, name, passwd, number, birthday):
    if not name or not name.strip():
        raise APIValueError('name')
    if not email or not _RE_EMAIL.match(email):
        raise APIValueError('email')
    if not passwd or not _RE_SHA1.match(passwd):
        raise APIValueError('passwd')
    if not number.isdigit():
        raise APIValueError('number should > 0')
 	#if not birthday:
     #   raise APIValueError('birthday') 
    print("number:" + number)
    #validation user          
    fbusers = yield from FBUser.findAll('email=?', [email])
    if len(fbusers) > 0:
        raise APIError('register:failed', 'email', 'Email is already in use.')

    uid = next_id()
    sha1_passwd = '%s:%s' % (uid, passwd)

    fbuser = FBUser(id=uid, name=name.strip(), email=email, passwd=hashlib.sha1(sha1_passwd.encode('utf-8')).hexdigest(), number=number, birthday=birthday.strip())
    yield from fbuser.save()

    # make session cookie:
    r = web.Response()
    r.set_cookie(COOKIE_NAME, user2cookie(fbuser, 86400), max_age=86400, httponly=True)
    fbuser.passwd = '******'
    r.content_type = 'application/json'
    r.body = json.dumps(fbuser, cls=CJsonEncoder, ensure_ascii=False).encode('utf-8')
    return r
Esempio n. 2
0
def api_register_fbuser(*, email, name, passwd):
    if not name or not name.strip():
        raise APIValueError('name')
    if not email or not _RE_EMAIL.match(email):
        raise APIValueError('email')
    if not passwd or not _RE_SHA1.match(passwd):
        raise APIValueError('passwd')
    users = yield from FBUser.findAll('email=?', [email])
    if len(users) > 0:
        raise APIError('register:failed', 'email', 'Email is already in use.')
    uid = next_id()
    sha1_passwd = '%s:%s' % (uid, passwd)
    fbuser = FBUser(id=uid,
                    name=name.strip(),
                    email=email,
                    passwd=hashlib.sha1(
                        sha1_passwd.encode('utf-8')).hexdigest(),
                    image='http://www.gravatar.com/avatar/%s?d=mm&s=120' %
                    hashlib.md5(email.encode('utf-8')).hexdigest())
    yield from fbuser.save()
    # make session cookie:
    r = web.Response()
    r.set_cookie(COOKIE_NAME,
                 user2cookie(user, 86400),
                 max_age=86400,
                 httponly=True)
    user.passwd = '******'
    r.content_type = 'application/json'
    r.body = json.dumps(user, ensure_ascii=False).encode('utf-8')
    return r
Esempio n. 3
0
def api_get_fbusers(*, page='1'):
    page_index = get_page_index(page)
    num = yield from FBUser.findNumber('count(id)')
    p = Page(num, page_index)
    if num == 0:
        return dict(page=p, users=())
    fbusers = yield from FBUser.findAll(orderBy='created_at desc', limit=(p.offset, p.limit))
    for u in fbusers:
        u.passwd = '******'
    return dict(page=p, users=fbusers)
Esempio n. 4
0
def api_get_fbusers(*, page='1'):
    page_index = get_page_index(page)
    num = yield from FBUser.findNumber('count(id)')
    p = Page(num, page_index)
    if num == 0:
        return dict(page=p, users=())
    fbusers = yield from FBUser.findAll(orderBy='created_at desc',
                                        limit=(p.offset, p.limit))
    for u in fbusers:
        u.passwd = '******'
    return dict(page=p, users=fbusers)
Esempio n. 5
0
 def get(self):
     uid = self.request.get("uid",'534881870')
     user = FBUser.get_by_key_name(uid)
     friends = memcache.get(key='FriendReports_%s')
     if not friends:
         friends = FBUser.gql('WHERE friends = :1 ORDER BY name,id',user.key()).run()
         memcache.add(key='FriendReports_%s' % str(user.id),value=friends,time=240)
     base_path = os.path.join(os.path.dirname(__file__).replace('reports',''), "templates")
     path = os.path.join(base_path, "header.html")
     self.response.out.write(template.render(path, {}))
     args = dict(user=user,friends=friends)
     path = os.path.join(base_path, "user.html")
     self.response.out.write(template.render(path, args))
     path = os.path.join(base_path, "footer.html")
     self.response.out.write(template.render(path, {}))
Esempio n. 6
0
 def get(self):
     uid = self.request.get("uid",'534881870')
     # Key
     #userKey = escape(self.request.get('uk','')
     #user = db.get(userKey)
     user = FBUser.get_by_key_name(uid)
     friends = memcache.get(key='FriendReports_%s' % uid)
     if not friends and user:
         friends = FBUser.gql('WHERE friends = :1 ORDER BY name,id',user.key()).run()
         memcache.add(key='FriendReports_%s' % str(user.id),value=friends,time=240)
     if user:
         data = [{'name':f.name,
                  'id':f.id,
                  'pic':'http://graph.facebook.com/%s/picture?type=square' % f.id,
                  'friends':[ff.id_or_name() for ff in f.friends]} for f in friends]
         self.response.out.write(json.dumps(data))
Esempio n. 7
0
def cookie2user(cookie_str):
    '''
    Parse cookie and load user if cookie is valid.
    '''
    if not cookie_str:
        return None
    try:
        L = cookie_str.split('-')
        if len(L) != 3:
            return None
        uid, expires, sha1 = L
        if int(expires) < time.time():
            return None
        user = yield from FBUser.find(uid)
        if user is None:
            return None
        s = '%s-%s-%s-%s' % (uid, user.passwd, expires, _COOKIE_KEY)
        if sha1 != hashlib.sha1(s.encode('utf-8')).hexdigest():
            logging.info('invalid sha1')
            return None
        user.passwd = '******'
        return user
    except Exception as e:
        logging.exception(e)
        return None
Esempio n. 8
0
 def _storeFriends(self,friends,start=0,end=300,user_key=None):
     ''' Store friends as User objects
     '''
     users = []
     for friend in friends[start:end]:
         bFriends = [str(uid) for uid in friend.get('friends',user_key)] #user_key and [user_key,] or []
         fId = str(friend.get('id',friend.get('uid')))
         fName = friend.get('name')
         fFirstName = friend.get('first_name')
         fLastName = friend.get('last_name')
         fBirthday = friend.get('birthday_date')
         fSex = friend.get('sex')
         profile = {'id':fId,
                    'name':fName,
                    'first_name':fFirstName,
                    'last_name':fLastName,
                    'birthday':fBirthday,
                    'gender':fSex}
         user = FBUser.get_or_insert(key_name=str(fId),**profile)
         for k,v in profile.items():
             value = getattr(user,k)
             if v and not(v==value):
                 setattr(user,k,v)
         users.append(user)
     db.put(users)
     return users
Esempio n. 9
0
 def post(self):
     uid = self.request.get("user_id")
     start = self.request.get("start",0)
     end = self.request.get("end",0)
     user = FBUser.get_by_key_name(uid)
     logging.debug('User ID (%s) Start (%s) End(%s)' % (str(user.id),str(start),str(end)))
     data = memcache.get('friends_%s' % str(user.id))
     if not data:
         graph = facebook.GraphAPI(user.access_token)
         friends = graph.get_connections(user.id, "friends")
         friends = friends.get('data',[])
     else:
         friends = data
     try:
         friends = self._storeFriends(friends,int(start),int(end),user.key())
         actualFriends = user.friends
         friends = [f.key() for f in friends if f.key() not in actualFriends]
         actualFriends.extend(friends)
         user.friends = actualFriends
         user.put()
     except DeadlineExceededError:
         self.response.clear()
         self.response.set_status(500)
         self.response.out.write("This operation could not be completed in time...")
     finally:
         queues = memcache.get('queues_%s' % str(user.id))
         queues.remove((int(start),int(end)))
         if queues:
             # Ainda temos uma fila?
             memcache.replace('queues_%s' % str(user.id),queues)
         else:
             logging.debug('Adding friendsFriendsUp')
             taskqueue.add(queue_name='friendsFriendsUp' ,url='/queue/queueFriends', params={'user_id':user.id,})
Esempio n. 10
0
 def updateUser(self,user,profile={}):
     ''' Let's update this user
     '''
     base_properties = ['first_name','last_name','name','link','about','birthday',
                        'email','website','bio','quotes','gender',
                        'relationship_status', 'religion','political','timezone']
     list_properties = ['interested_in','meeting_for']
     geo_properties = ['hometown','location']
     for prop in base_properties:
         value = profile.get(prop)
         if hasattr(user,prop) and value:
             setattr(user,prop,value)
         
     # Update Hometown and Location               
     for prop in geo_properties:
         value = profile.get(prop)
         if hasattr(user,prop) and value:
             location = self._location(value.get('id'),value.get('name'))
             setattr(user,prop,location)
     
     if 'significant_other' in profile:
         fName = profile.get('significant_other')['name']
         fId = profile.get('significant_other')['id']
         profile = {'id':fId,'name':fName}
         user = FBUser.get_or_insert(key_name=str(fId),**profile)
         user.significant_other = tmpUser
Esempio n. 11
0
def cookie2user(cookie_str):
    '''
    Parse cookie and load user if cookie is valid.
    '''
    if not cookie_str:
        return None
    try:
        L = cookie_str.split('-')
        if len(L) != 3:
            return None
        uid, expires, sha1 = L
        if int(expires) < time.time():
            return None
        user = yield from FBUser.find(uid)
        if user is None:
            return None
        s = '%s-%s-%s-%s' % (uid, user.passwd, expires, _COOKIE_KEY)
        if sha1 != hashlib.sha1(s.encode('utf-8')).hexdigest():
            logging.info('invalid sha1')
            return None
        user.passwd = '******'
        return user
    except Exception as e:
        logging.exception(e)
        return None
Esempio n. 12
0
def authenticate(*, email, passwd):
    if not email:
        raise APIValueError('email', 'Invalid email.')
    if not passwd:
        raise APIValueError('passwd', 'Invalid password.')
    fbusers = yield from FBUser.findAll('email=?', [email])
    if len(fbusers) == 0:
        raise APIValueError('email', 'Login failed, Email not exist.')
    fbuser = fbusers[0]
    # check passwd:
    sha1 = hashlib.sha1()
    sha1.update(fbuser.id.encode('utf-8'))
    sha1.update(b':')
    sha1.update(passwd.encode('utf-8'))
    if fbuser.passwd != sha1.hexdigest():
        raise APIValueError('passwd', 'Invalid password.')
    # authenticate ok, set cookie:
    r = web.Response()
    r.set_cookie(COOKIE_NAME,
                 user2cookie(fbuser, 86400),
                 max_age=86400,
                 httponly=True)
    fbuser.passwd = '******'
    r.content_type = 'application/json'
    r.body = json.dumps(fbuser, cls=CJsonEncoder).encode('utf-8')

    return r
Esempio n. 13
0
 def get(self):
     """ Let's get the friends of this user
     """
     users = FBUser.gql("WHERE accessed = TRUE").run()
     for user in users:
         logging.debug(user.id)
         taskqueue.add(url="/queue/getFriends", params={"user_id": user.id})
     self.response.out.write("Feito")
Esempio n. 14
0
 def post(self):
     limit = 40
     uid = self.request.get("user_id")
     user = FBUser.get_by_key_name(uid)
     fql = facebook.FQL(user.access_token)
     query ={"friends":
                 """SELECT uid,first_name,last_name,name,sex,birthday_date
                    FROM 
                         user 
                    WHERE 
                         uid in (SELECT uid2 FROM friend WHERE uid1=%s)""" % str(user.id),
             "friendFriends":
                 """SELECT 
                         uid1,
                         uid2 
                    FROM 
                         friend 
                    WHERE 
                         uid1 IN (SELECT uid FROM #friends) 
                         AND uid2 in (SELECT uid FROM #friends)
                 """}
     try:
         friendsQuery,ffQuery = fql.multiquery(queries = query)
     except ValueError:
         logging.debug(fql.multiquery(queries = query))
         return ''
     friendsQuery = friendsQuery[u'fql_result_set']
     ffQuery = ffQuery[u'fql_result_set']
     tmpFF = {}
     for relation in ffQuery:
         uid1 = relation.get('uid1')
         uid2 = relation.get('uid2')
         if not str(uid1) in tmpFF:
             tmpFF[str(uid1)] = []
         tmpFF[str(uid1)].append(str(uid2))
     friends = []
     for friend in friendsQuery:
         friend['id'] = str(friend['uid'])
         friend['friends'] = tmpFF.get(str(friend['uid']),[])
         friends.append(friend)
     
     if friends:
         memcache.add(key="friends_%s" % str(user.id), value=friends, time=180)
     if tmpFF:
         memcache.add(key='queue_%s' % str(user.id),value=tmpFF,time=240)
     nUsers = len(friends)
     
     ranges = [(r,((((r+limit)<nUsers) and (r+limit)) or nUsers)) for r in range(0,nUsers,limit)]
     memcache.delete(key='queues_%s' % str(user.id))   
     tmpQueues = []
     for s,e in ranges:
         tmpQueues.append((s,e))
         logging.debug('Adiciona tarefa na fila %d - %d' % (s,e))
         taskqueue.add(queue_name='friendsUp' ,url='/queue/friend_fetch', params={'user_id':user.id,
                                                                            'start':s,
                                                                            'end':e,})
     memcache.add(key='queues_%s' % str(user.id),value=tmpQueues,time=180)                                                                       
Esempio n. 15
0
def api_register_fbuser(*, email, name, passwd, number, birthday):
    if not name or not name.strip():
        raise APIValueError('name')
    if not email or not _RE_EMAIL.match(email):
        raise APIValueError('email')
    if not passwd or not _RE_SHA1.match(passwd):
        raise APIValueError('passwd')
    if not number.isdigit():
        raise APIValueError('number should > 0')

#if not birthday:
#   raise APIValueError('birthday')
    print("number:" + number)
    #validation user
    fbusers = yield from FBUser.findAll('email=?', [email])
    if len(fbusers) > 0:
        raise APIError('register:failed', 'email', 'Email is already in use.')

    uid = next_id()
    sha1_passwd = '%s:%s' % (uid, passwd)

    fbuser = FBUser(id=uid,
                    name=name.strip(),
                    email=email,
                    passwd=hashlib.sha1(
                        sha1_passwd.encode('utf-8')).hexdigest(),
                    number=number,
                    birthday=birthday.strip())
    yield from fbuser.save()

    # make session cookie:
    r = web.Response()
    r.set_cookie(COOKIE_NAME,
                 user2cookie(fbuser, 86400),
                 max_age=86400,
                 httponly=True)
    fbuser.passwd = '******'
    r.content_type = 'application/json'
    r.body = json.dumps(fbuser, cls=CJsonEncoder,
                        ensure_ascii=False).encode('utf-8')
    return r
Esempio n. 16
0
def api_register_fbuser(*, email, name, passwd):
    if not name or not name.strip():
        raise APIValueError('name')
    if not email or not _RE_EMAIL.match(email):
        raise APIValueError('email')
    if not passwd or not _RE_SHA1.match(passwd):
        raise APIValueError('passwd')
    users = yield from FBUser.findAll('email=?', [email])
    if len(users) > 0:
        raise APIError('register:failed', 'email', 'Email is already in use.')
    uid = next_id()
    sha1_passwd = '%s:%s' % (uid, passwd)
    fbuser = FBUser(id=uid, name=name.strip(), email=email, passwd=hashlib.sha1(sha1_passwd.encode('utf-8')).hexdigest(), image='http://www.gravatar.com/avatar/%s?d=mm&s=120' % hashlib.md5(email.encode('utf-8')).hexdigest())
    yield from fbuser.save()
    # make session cookie:
    r = web.Response()
    r.set_cookie(COOKIE_NAME, user2cookie(user, 86400), max_age=86400, httponly=True)
    user.passwd = '******'
    r.content_type = 'application/json'
    r.body = json.dumps(user, ensure_ascii=False).encode('utf-8')
    return r
Esempio n. 17
0
def editpref(request):
    """lets the user set her preferences
    """
#    me = request.facebook.graph.get_object('me')
    me = {}
    me['name'] = 'xyz'
    me['id'] = '69DFS3242R'

    try:
        # get user data from DB
        fbuser = FBUser.objects.get(fbid=me['id'])
    except FBUser.DoesNotExist:
        # that id is not in the DB, so create it
        # I am not using get_or_create() because
        # the user might have changed her name on FB
        fbuser = FBUser(fbid=me['id'], name=me['name'])
        fbuser.save()

    form = forms.UserPrefForm(instance=fbuser)
    #return render_to_response('editpref.html',
    #                          {'form': form},
    #                          context_instance=RequestContext(request))
    return render(request, 'editpref.html',
                  {'form': form})
Esempio n. 18
0
 def current_user(self):
     if not hasattr(self, "_current_user"):
         self._current_user = None
         self.cookie = facebook.get_user_from_cookie(self.request.cookies, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET)
         if self.cookie:
             user = FBUser.get_by_key_name(self.cookie["uid"])
             graph = facebook.GraphAPI(self.cookie["access_token"])
             profile = graph.get_object("me")
             if not user:
                 user = self.createUser(accessed=True,profile=profile)
                 user.access_token = self.cookie["access_token"]
             elif user.access_token != self.cookie["access_token"]:
                 user.access_token = self.cookie["access_token"]
             self.updateUser(user,profile=profile)
             user.accessed = True
             user.put()
             self._current_user = user
     return self._current_user
Esempio n. 19
0
 def post(self):
     limit = 100
     user_id = self.request.get("user_id")
     logging.debug('QueueFriends Start')
     data = memcache.get('queue_%s' % str(user_id))
     if not data:
         return ''
     users = FBUser.get_by_key_name(data.keys())
     nUsers = len(users)
     dictUsers = dict([(u.id,u.key()) for u in users])
     ranges = [(r,((((r+limit)<nUsers) and (r+limit)) or nUsers)) for r in range(0,nUsers,limit)]
     for s,e in ranges:
         tmpUsers = []
         for user in users[s:e]:
             actualFriends = user.friends
             newFriends = [dictUsers.get(uid,None) for uid in data[user.id] if not(dictUsers.get(uid,None) in actualFriends)]
             actualFriends.extend([k for k in newFriends if k])
             if actualFriends:
                 user.friends = actualFriends
             tmpUsers.append(user)
         db.put(tmpUsers)
     memcache.delete('queue_%s' % str(user_id))
Esempio n. 20
0
def authenticate(*, email, passwd):
    if not email:
        raise APIValueError('email', 'Invalid email.')
    if not passwd:
        raise APIValueError('passwd', 'Invalid password.')
    fbusers = yield from FBUser.findAll('email=?', [email])
    if len(fbusers) == 0:
        raise APIValueError('email', 'Login failed, Email not exist.')
    fbuser = fbusers[0]
    # check passwd:
    sha1 = hashlib.sha1()
    sha1.update(fbuser.id.encode('utf-8'))
    sha1.update(b':')
    sha1.update(passwd.encode('utf-8'))
    if fbuser.passwd != sha1.hexdigest():
        raise APIValueError('passwd', 'Invalid password.')
    # authenticate ok, set cookie:
    r = web.Response()
    r.set_cookie(COOKIE_NAME, user2cookie(fbuser, 86400), max_age=86400, httponly=True)
    fbuser.passwd = '******'
    r.content_type = 'application/json'
    r.body = json.dumps(fbuser, cls=CJsonEncoder).encode('utf-8')

    return r
Esempio n. 21
0
 def getUserById(self,id):
     ''' Given a user_id we get a instance of FBUser
     '''
     return FBUser.get_by_key_name(id)
 def init_me(self):
     t = Graph.fetch_user_information(self.graph, True)
     self.me = FBUser(t[u'uid'], t[u'name'], t[u'interests'])
 def init_friends(self):
     for l in Graph.fetch_user_information(self.graph, False):
         self.friends.append(FBUser(l[u'uid'], l[u'name'], l[u'interests']))