def get(self):
        if not WhiteTokenModel.is_jti_whitelisted(get_raw_jwt()["jti"]):
            return {'message': 'Not logged in'}, 205
        try:
            print("Starting", flush=True)
            current_user = get_jwt_identity()
            userid = request.args.get('userid')
            tripid = request.args.get('tripid')
            print("Got data", flush=True)

            # If a tripid is provided, it will return just that trip
            if (tripid):
                print("tripid was provided", flush=True)
                trip = Trip.find_by_tid(int(tripid))
                print("Found trip", flush=True)
                # Making sure that the user asking for the trip has access to it, either because the user owns it, or is friends with the owner
                isFriends = Friends.find_by_uid_and_fid(
                    current_user, trip.user_id)
                if (trip.user_id != current_user and isFriends == None):
                    print("No access", flush=True)
                    return {
                        "message": "You do not have access to that trip"
                    }, 203
                elif (isFriends.friend_status == "accepted"
                      or trip.user_id == current_user):
                    print("Returning", flush=True)
                    return {
                        "message":
                        "The trip with id {} was found".format(tripid),
                        "trips": [trip.trip_json],
                        "tid": trip.trip_id,
                        "username": User.find_by_uid(trip.user_id).user_name
                    }, 200

            if (not userid):
                userId = current_user
            else:
                userId = userid

            if (current_user == userId
                    or Friends.find_by_uid_and_fid(current_user, userId)):
                all_trips = Trip.find_all_public_trips(userId)
                return {
                    "message":
                    "The trips of user {} was found".format(
                        User.find_by_uid(userId).user_name),
                    "trips":
                    json.dumps(all_trips)
                }, 200
            else:
                return {
                    "message":
                    "You are not friends with the requested user, therefore you cannot get their trips"
                }, 203

        except Exception as error:
            return {
                "message": "Something went wrong on the server",
                "error": str(error)
            }, 500
Beispiel #2
0
def reject_friend(request):
    status = ''
    if request.method=='POST':
         check_reject_user = Friends.objects(friend1=request.user.id,myfriendslist__myfriends_ids=request.POST['rejectfriendid'])
         if check_reject_user:
             f = Friends.objects(friend1=request.user.id).update_one(pull__myfriendslist={'myfriends_ids':request.POST['rejectfriendid']})
             if f:
                 status = 'rejected'
    userinfo = getuserdetailsbyid(request.POST['rejectfriendid'])
    return render(request,'profile2.html',{'f_status':status,'user_details':userinfo,'selid':request.POST['rejectfriendid']})
Beispiel #3
0
    def handle_verification(cls, handler, user_id,signup_token,verification_type,invite_token):
        # it should be something more concise like
        # self.auth.get_user_by_token(user_id, signup_token)
        # unfortunately the auth interface does not (yet) allow to manipulate
        # signup tokens concisely
        user, ts = handler.user_model.get_by_auth_token(int(user_id), signup_token,
                                                     'signup')

        if not user:
            logging.info(
              'Could not find any userId with id "%s" signup token "%s"',
              user_id,
              signup_token)
            handler.display_message("Not found - if you've already followed this link there is no need to do it again")
            return

        # store userId data in the session
        handler.auth.set_session(handler.auth.store.user_to_dict(user), remember=True)

        if verification_type == 'v':
            # remove signup token,
            # we don't want users to come back with an old link
            handler.user_model.delete_signup_token(handler.user_id, signup_token)

            if not user.verified:
                user.verified = True
                user.put()
            try:
              if invite_token and invite_token != 'none':
                inv = Invite.checkInviteToken(invite_token)
                Friends.addFriends(inv, handler.user_id)
                Invite.delInviteToken(invite_token)
                logging.info("passwordVerificationHandler complete "+user.email_address)
            except:
              logging_ext.error(
                "Failed to add friend: passwordVerificationHandler GET",
                exc_info=True)
            handler.render_template('signup-complete.html')
        elif verification_type == 'p':
            # supply userId to the page
            params = {
                'userId': user,
                'token': signup_token
            }
            handler.render_template('resetpassword.html', params)
        else:
            logging.info('verification type not supported')
            handler.abort(404)
Beispiel #4
0
def friends():

    form = FriendsForm()

    if 'email' not in session:
        return redirect(url_for('signin'))

    user = User.query.filter_by(email=session['email']).first()

    if user is None:
        return redirect(url_for('signin'))

    if request.method == 'POST':
        if form.validate() == False:
            return render_template('friends.html', form=form)
        else:
            newfriend = Friends(form.f_firstname.data, form.f_lastname.data,
                                form.f_email.data, form.f_phone.data, user.uid)
            db.session.add(newfriend)
            db.session.commit()

            flash('Record was successfully added')
            return redirect(url_for('profile'))
            #return "[1] Create a new user [2] sign in the user [3] redirect to the user's profile"

    elif request.method == 'GET':
        return render_template('friends.html', form=form)
Beispiel #5
0
 def obj_get_list(self, bundle, **kwargs):
     user_id = bundle.request.GET.get('user_id')
     user = MyUser.objects.get(user_id=user_id)
     username = user.username
     '''update friends list first'''
     get_friends(username)
     return Friends.objects(user_id=user_id)
Beispiel #6
0
def friend(userid=None, friendid=None):
    code = 400
    if request.method == 'GET':
        if 'userid' and 'page' in request.data:
            userid = int(request.json.get('userid'))
            page = int(request.json.get('page'))
        else:
            abort(code)

        count = Friends.query.count()
        record = Friends.query.filter_by(user_fk=userid).paginate(
            page, PER_PAGE, count)

        code = 204
        if record is not None:
            listid = []
            items = record.items
            for r in items:
                listid.append(r.friend_id)

            result = []
            result = {'page': 1, 'total': 0, 'pages': 1, 'items': result}
            if len(listid) > 0:
                res = db.session.query(Users).filter(
                    Users.user_fk.in_((listid))).all()

                if res is not None:
                    code = 200
                    result = []
                    for r in res:
                        result.append({
                            'userid': r.user_fk,
                            'username': r.name,
                            'email': r.email,
                            'phone': r.phone
                        })
                    result = {
                        'page': record.page,
                        'total': record.total,
                        'pages': record.pages,
                        'items': result
                    }
                    return json.dumps(result), code

                else:
                    return json.dumps(result), code
            else:
                return json.dumps(result), code
        else:
            return json.dumps(messageNoContent), code

    if request.method == 'POST':
        if userid and friendid is not None:
            record = Friends(userid, friendid)
            db.session.add(record)
            db.session.commit()
            code = 201
        return json.dumps({"message": "Created "}), code

    return abort(code)
Beispiel #7
0
def person_follow(id):
    user = checkUser()
    friend = Friends(id=str(uuid1()), user_id=user.id, friend_id=id)
    r = make_response('''<script>alter(关注成功);history.go(-1);</script>''')
    db.session.add(friend)
    db.session.commit()
    return r
Beispiel #8
0
 def post(self):
   """
   accept a friend request
   :return:
   """
   other_id = int(self.request.params['unfriend_id'])
   my_id = int(self.user_id)
   low = min(other_id, my_id)
   high = max(other_id, my_id)
   record = Friends.query(Friends.lower == low, Friends.higher == high).get()
   if record:
     record.key.delete()
     # delete invites
     inv_from = InviteInternal.query().\
       filter(InviteInternal.inviter == other_id).\
       filter(InviteInternal.invitee == my_id)
     for i in inv_from:
       i.key.delete()
     inv_to = InviteInternal.query().\
       filter(InviteInternal.inviter == my_id).\
       filter(InviteInternal.invitee == other_id)
     for i in inv_to:
       i.key.delete()
     self.response.out.write("OK")
     return
   self.response.out.write("FAIL")
Beispiel #9
0
def add_friend(request):
    status = ''
    if request.method=='POST':
        no_friends_check = Friends.objects(friend1=request.user.id)
        if no_friends_check:
            check_requested_user = Friends.objects(friend1=request.user.id,myfriendslist__myfriends_ids=request.POST['addfriendid'])
            if check_requested_user:
                status='alredysent'
            else:
                Friends.objects(friend1=request.user.id).update_one(push__myfriendslist={'myfriends_ids':request.POST['addfriendid'],'status':'1'})
                status = "hasbeensent"
        else:
            Friends.objects.create(friend1=request.user.id,myfriendslist=[{'myfriends_ids':request.POST['addfriendid'],'status':'1'}])
            status = 'hasbeensent'
        userinfo = getuserdetailsbyid(request.POST['addfriendid'])
    return render(request,'profile2.html',{'f_status':status,'user_details':userinfo,'selid':request.POST['addfriendid']})
Beispiel #10
0
    def get(self):
        if not WhiteTokenModel.is_jti_whitelisted(get_raw_jwt()["jti"]):
            return {'message': 'Not logged in'}, 205
        try:
            # Getting the uid from the jwt.
            current_user = get_jwt_identity()

            # Getting the Friend List from the database through the model in models.py
            friend_objects = Friends.find_by_uid(current_user)

            # Checks if no object got returned in the query, then return 404 Not Found.
            if friend_objects == None:
                return {"message": "Error: Friend objects not found"}, 204

            friend_list = []

            for friend_object in friend_objects:
                friend_user = User.find_by_uid(friend_object.friend_id)
                friend_list.append({
                    "name": friend_user.user_name,
                    "status": friend_object.friend_status
                })

            return {
                "message": "The uid was found",
                "uid": current_user,
                "friends": friend_list
            }, 202

        except Exception as err:
            return {
                "message": "Something went wrong on the server",
                "error": str(err)
            }, 500
Beispiel #11
0
def accept(sender):
    if request.method == "POST":
        fr = Friends(sender, session["user"])
        db.session.add(fr)
        req = Requests.query.filter_by(user_1=int(sender)).all()
        for i in req:
            db.session.delete(i)
        db.session.commit()
    return redirect("/requests")
Beispiel #12
0
def get_selected_user_info(request,username):
    f_status = 'addfriend'
    user_details = User.objects.get(username=username)
    friendslist = Friends.objects(friend1=request.user.id,myfriendslist__myfriends_ids=str(user_details.id))
    selected_udi = user_details.id
    loggeduserid = request.user.id
    if selected_udi==loggeduserid:
        f_status = 'selectedmyself'
    else:
        if friendslist:
            f_status = sel_frnd_status(user_details,selected_udi,friendslist)
    return render(request,'profile2.html',{'f_status':f_status,'user_details':user_details,'selid':selected_udi})
Beispiel #13
0
 def post(self):
   """
   accept a friend request
   :return:
   """
   from_id = self.request.params['from_id']
   #find the invite
   # inv = InviteInternal.all().get()
   # inv = InviteInternal.all().filter("invitee =", self.user_id).get()
   inv = InviteInternal.query().\
     filter(InviteInternal.invitee == self.user_id).\
     filter(InviteInternal.inviter == int(from_id)).\
     get()
   if not inv:
     self.response.out.write("NO INVITE")
     return
   Friends.addFriends(self.user_id, from_id)
   logging.info("FriendsApiAccept %s from %s"%(self.user_id, from_id))
   #delete invite
   inv.accepted = True
   inv.when = datetime.datetime.now()
   inv.put()
   self.response.out.write("OK")
Beispiel #14
0
    def get(self):
        if not WhiteTokenModel.is_jti_whitelisted(get_raw_jwt()["jti"]):
            return {'message': 'Not logged in'}, 205

        try:
            current_user = get_jwt_identity()

            friends = Friends.find_by_uid(current_user)
            if len(friends) == 0:
                return {"message": "You have no friends"}, 204

            trips = []

            for friend in friends:
                if friend.friend_status == "accepted":
                    friendUser = User.find_by_uid(friend.friend_id)
                    friendsTrips = Trip.find_all_trips(friend.friend_id)

                    for trip in friendsTrips:
                        tripObject = {
                            "tripid": trip.trip_id,
                            "username": friendUser.user_name,
                            "tripjson": trip.trip_json
                        }
                        trips.append(tripObject)

            return {
                "message": "Your friends' trips were found",
                "trips": trips
            }, 200

        except Exception as error:
            return {
                "message": "Something went wrong on the server",
                "error": error
            }, 500
Beispiel #15
0
    def post(self):
        if not WhiteTokenModel.is_jti_whitelisted(get_raw_jwt()["jti"]):
            return {'message': 'Not logged in'}, 205

        current_user = get_jwt_identity()
        data = friend_edit_parser.parse_args()

        if not data["friend_name"]:
            return {'message': 'Friend name is required'}, 203

        friend_user = User.find_by_username(data["friend_name"])
        if friend_user == None:
            return {"message": "Friends user object not found"}, 204

        if not data["status"]:
            return {'message': 'Status is required'}, 203

        try:
            if data["status"] == "send":
                friend_object = Friends.find_by_uid_and_fid(
                    current_user, friend_user.user_id)
                if friend_object != None:
                    return {"message": "Error: Already on list"}, 203
                friends_friend_object = Friends.find_by_uid_and_fid(
                    friend_user.user_id, current_user)
                if friends_friend_object != None:
                    return {"message": "Error: Already on friends list"}, 203

                if friend_user.user_id == current_user:
                    return {
                        "message": "Error: Can't send a request to yourself"
                    }, 203

                own_friend_entry = Friends(user_id=current_user,
                                           friend_id=friend_user.user_id,
                                           friend_status="sent")
                friends_friend_entry = Friends(user_id=friend_user.user_id,
                                               friend_id=current_user,
                                               friend_status="received")
                own_friend_entry.save_to_db()
                friends_friend_entry.save_to_db()
                return {'message': "Friend request sent."}, 201

            if data["status"] == "accept":
                friend_object = Friends.find_by_uid_and_fid(
                    current_user, friend_user.user_id)
                if friend_object == None:
                    return {"message": "Friend object not found"}, 204
                friends_friend_object = Friends.find_by_uid_and_fid(
                    friend_user.user_id, current_user)
                if friends_friend_object == None:
                    return {"message": "Friends friend object not found"}, 204

                if friend_object.friend_status != "received" or friends_friend_object.friend_status != "sent":
                    return {
                        "message": "Can't accept because there is no request."
                    }, 203

                friend_object.friend_status = "accepted"
                friends_friend_object.friend_status = "accepted"

                friend_object.commit()
                friends_friend_object.commit()

                return {'message': "Friend request accepted."}, 201

            if data["status"] == "delete":
                friend_object = Friends.find_by_uid_and_fid(
                    current_user, friend_user.user_id)
                if friend_object == None:
                    return {"message": "Friend object not found"}, 204
                friends_friend_object = Friends.find_by_uid_and_fid(
                    friend_user.user_id, current_user)
                if friends_friend_object == None:
                    return {"message": "Friends friend object not found"}, 204

                friend_object.delete_from_db()
                friends_friend_object.delete_from_db()

                return {
                    'message':
                    'Friend entry for friend {} was deleted'.format(
                        friend_user.user_name),
                }, 201

            return {'message': "Invalid status."}, 201
        except Exception as err:
            return {'message': 'Something went wrong', "error": str(err)}, 500