コード例 #1
0
ファイル: users.py プロジェクト: abhiram-n/Circles-Server
def getFriends():
    if not g.user:
        print("ERROR: No user associated with the token to get friends for.")
        return "", constants.STATUS_SERVER_ERROR

    db.create_all()
    toReturn = {"count": 0, "friends": []}
    if g.user.friends:
        for friendRow in g.user.friends:
            friend = User.query.get(friendRow.friendId)
            if friend:
                userDetails = {
                    "name": friend.name,
                    "id": friend.id,
                    "numCards": 0,
                    "profileImgUrl": friend.profileImgUrl
                }
                if friend.cards:
                    userDetails["numCards"] = len(friend.cards)
                toReturn["friends"].append(userDetails)
                toReturn["count"] += 1
            else:
                print("WARNING: No Friend found with ID: " +
                      str(friendRow.friendId))

    db.session.close()
    return jsonify(toReturn), constants.STATUS_OK
コード例 #2
0
def respondToAccessRequest():
    if "requestId" not in request.json:
        print("ERROR: No access request id provided to respond to")
        return "", constants.STATUS_BAD_REQUEST

    if "action" not in request.json:
        print("ERROR: No status provided to respond to access request with")
        return "", constants.STATUS_BAD_REQUEST

    action = request.json["action"]
    requestId = request.json["requestId"]
    db.create_all()
    accessRequest = AccessRequest.query.get(requestId)
    if g.user.id != accessRequest.toUserId:
        print("ERROR: Only the sender can respond to an access request: " +
              str(g.user.id))
        return "", constants.STATUS_BAD_REQUEST

    if accessRequest.status == action:
        print("WARNING: Access request status already at the desired state:" +
              str(action))
        db.session.close()
    else:
        data = {
            "requestId": str(accessRequest.id),
            "type": constants.ACCESS_REQUEST_NOTIFICATION_TYPE,
            "isUserSender":
            "true"  # the notification is sent to the user who created/sent the request
        }

        fcmToken = accessRequest.sender.fcmToken
        accessRequest.status = action
        accessRequest.resolvedOn = datetime.datetime.now(
            tz=pytz.timezone(constants.TIMEZONE_KOLKATA))
        if (action == constants.ACCESS_REQUEST_ACCEPTED):
            notification = createNotificationForAcceptedAccessRequest(
                g.user.name)
        else:
            notification = createNotificationForDeclinedAccessRequest(
                g.user.name)

        if (not commitToDB()):
            print('ERROR: Problem resolving the access request')
            return "", constants.STATUS_SERVER_ERROR

        t = Thread(target=utils.sendDeviceNotification,
                   args=(fcmToken, notification, data))
        t.start()

        try:
            if (action == constants.ACCESS_REQUEST_ACCEPTED):
                smsText = "New request created: " + str(requestId)
                notifyFounders = Thread(target=utils.sendSMSToFounders,
                                        args=(smsText, ))
                notifyFounders.start()
        except Exception as err:
            print('ERROR: Could not send sms to founders for request: ' +
                  str(requestId) + ' with error: ' + str(err))

    return "", constants.STATUS_OK
コード例 #3
0
ファイル: posts.py プロジェクト: abhiram-n/Circles-Server
def createNewPost():
    if "text" not in request.json:
        print("ERROR: No text in the post to be created")
        return "", constants.STATUS_BAD_REQUEST

    text = request.json["text"]
    createdOn = datetime.datetime.now(
        tz=pytz.timezone(constants.TIMEZONE_KOLKATA))
    db.create_all()
    post = Post(text=text, createdOn=createdOn)
    g.user.posts.append(post)
    db.session.add(post)
    db.session.commit()

    friendFcmTokens = []
    if g.user.friends:
        for friendRow in g.user.friends:
            friend = User.query.get(friendRow.friendId)
            if friend:
                friendFcmTokens.append(friend.fcmToken)
    postId = post.id
    creatorName = g.user.name
    db.session.close()
    t = Thread(target=sendPostNotificationsToFriends,
               args=(friendFcmTokens, creatorName, postId))
    t.start()

    return "", constants.STATUS_OK
コード例 #4
0
ファイル: posts.py プロジェクト: abhiram-n/Circles-Server
def getPosts():
    postType = "sent" if "type" not in request.args else request.args["type"]
    db.create_all()
    toReturn = {"count": 0, "posts": []}
    if postType == "sent":
        if g.user.posts:
            for post in g.user.posts:
                toReturn["posts"].append({"id": post.id, "text": post.text, "creatorId": post.creatorId, \
                   "creatorName": post.creator.name, "createdOn": utils.getDateTimeAsString(post.createdOn), "creatorImgUrl": post.creator.profileImgUrl})
                toReturn["count"] += 1
    else:
        allPosts = []
        if g.user.friends:
            for friendRow in g.user.friends:
                friend = User.query.get(friendRow.friendId)
                if friend and friend.posts and len(friend.posts) > 0:
                    for post in friend.posts:
                        allPosts.append(post)

        if allPosts != []:
            allPosts = sorted(allPosts,
                              key=lambda post: post.createdOn,
                              reverse=True)
            for post in allPosts:
                toReturn["posts"].append({"id": post.id, "text": post.text, "creatorId": post.creatorId, \
                            "createdOn": utils.getDateTimeAsString(post.createdOn), "creatorImgUrl": post.creator.profileImgUrl, \
                            "creatorName": post.creator.name})
                toReturn["count"] += 1

    db.session.close()
    return jsonify(toReturn), constants.STATUS_OK
コード例 #5
0
def getFriendRequestsReceived():
    if not g.user:
        print(
            'ERROR: There is no user associated for getting friend request received.'
        )
        return "", constants.STATUS_BAD_REQUEST

    status = request.args["status"] if "status" in request.args else None
    db.create_all()
    friendRequests = None
    if status:
        friendRequests = FriendRequest.query.filter_by(
            toUserId=g.user.id).filter_by(status=status).order_by(
                desc(FriendRequest.createdOn)).all()
    else:
        friendRequests = FriendRequest.query.filter_by(
            toUserId=g.user.id).order_by(desc(FriendRequest.createdOn)).all()
    if not friendRequests:
        return jsonify({"count": 0}), constants.STATUS_OK

    count = len(friendRequests)
    toReturn = {"count": count, "requests": []}
    for friendRequest in friendRequests:
        senderName = friendRequest.sender.name
        toReturn['requests'].append({"requestId": friendRequest.id, "name": senderName, "phoneNumber": friendRequest.sender.phoneNumber, \
            "id": friendRequest.fromUserId, "createdOn": utils.getDateTimeAsString(friendRequest.createdOn), "profileImgUrl": friendRequest.sender.profileImgUrl, \
            "resolvedOn": utils.getDateTimeAsString(friendRequest.resolvedOn), "status": friendRequest.status})
    db.session.close()
    return jsonify(toReturn), constants.STATUS_OK
コード例 #6
0
def removeFriend():
    if "friendId" not in request.json:
        print('ERROR: No friendID field provided to remove.')
        return "", constants.STATUS_BAD_REQUEST

    if not g.user.friends or len(g.user.friends):
        print("ERROR: Cannot remove friend as user has no friends in db.")
        return "", constants.STATUS_BAD_REQUEST

    friendId = request.json["friendId"]
    db.create_all()

    for friendRow in g.user.friends:
        if friendId == friendRow.friendId:
            g.user.friends.remove(friendRow)
            fRequest = FriendRequest.query.get(friendRow.fRequestId)
            db.session.delete(friendRow)
            db.session.delete(
                fRequest
            )  #TODO: Try to see if it is removed from user's requests
            if (not commitToDB()):
                print(
                    "ERROR: Something went wrong in deleting the friend ID:" +
                    str(friendId))
                return "", constants.STATUS_SERVER_ERROR

            return "", constants.STATUS_OK

    db.session.close()
    print("ERROR: User has no friend with friendID: " + str(friendId))
    return "", constants.STATUS_SERVER_ERROR
コード例 #7
0
def cancelFriendRequest():
    if "requestId" not in request.json:
        print("ERROR: ID of the friend request to cancel is missing")
        return "", constants.STATUS_BAD_REQUEST

    if not g.user:
        print(
            'ERROR: There is no user associated for friend request cancellation.'
        )
        return "", constants.STATUS_BAD_REQUEST

    requestId = request.json["requestId"]
    db.create_all()
    friendRequest = FriendRequest.query.get(requestId)
    if not friendRequest:
        print("ERROR: No friend request found with id: " + str(requestId))
        return "", constants.STATUS_BAD_REQUEST
    g.user.fRequests_rec.remove(friendRequest)
    friendRequest.sender.fRequests_sent.remove(friendRequest)
    db.session.delete(friendRequest)
    if (not commitToDB()):
        print('ERROR: Problem cancelling the friend request')
        return "", constants.STATUS_SERVER_ERROR

    return "", constants.STATUS_OK
コード例 #8
0
def sendAuthCode():
    if "phoneNumber" not in request.json:
        print('ERROR: No phone number found to send code to.')
        return "", constants.STATUS_BAD_REQUEST

    mustExist = None if "mustExist" not in request.json else request.json[
        "mustExist"]
    codeLength = constants.AUTH_CODE_LENGTH if "length" not in request.json else request.json[
        "length"]
    db.create_all()
    phoneNumber = request.json["phoneNumber"]
    hashkey = os.environ["APP_KEY"]

    if mustExist is not None:
        currentUser = User.query.filter_by(phoneNumber=phoneNumber).first()
        if mustExist and not currentUser:
            print('ERROR: Not sending as there is no user to verify with: ' +
                  str(phoneNumber))
            db.session.close()
            return "", constants.STATUS_PRECONDITION_FAILED
        elif currentUser and not mustExist:
            print('ERROR: Not sending code as user already exists: ' +
                  str(phoneNumber))
            db.session.close()
            return "", constants.STATUS_PRECONDITION_FAILED

    code = utils.generateAuthCode(codeLength)
    expiration = datetime.datetime.now(
        tz=pytz.timezone(constants.TIMEZONE_KOLKATA)) + datetime.timedelta(
            minutes=10)

    # Is there any existing verification left
    oldVerification = AuthCodeVerification.query.filter_by(
        phoneNumber=phoneNumber).first()
    if oldVerification:
        print('Found an old verification')
        oldVerification.code = code
        oldVerification.expiration = expiration
    else:
        verification = AuthCodeVerification(phoneNumber=phoneNumber,
                                            code=code,
                                            expiration=expiration)
        db.session.add(verification)

    if (not commitToDB()):
        print('ERROR: Problem creating verification for number: ' +
              str(phoneNumber))
        return "", constants.STATUS_SERVER_ERROR

    smsBody = code + " is your code to log in to Circles. This code will expire in 10 minutes. \n\n" + hashkey
    if not utils.sendSMS(smsBody, phoneNumber):
        print('ERROR: Could not send SMS to phone: ' + str(phoneNumber))
        return "", constants.STATUS_BAD_REQUEST

    return "", constants.STATUS_OK
コード例 #9
0
def getFriendRequestInfo():
    if "id" not in request.args:
        print("ERROR: No id of friend request provided")
        return "", constants.STATUS_BAD_REQUEST

    requestId = request.args["id"]
    db.create_all()
    friendRequest = FriendRequest.query.get(requestId)
    if not friendRequest:
        print("ERROR: No friend request found for getFriendRequest with id: " +
              str(requestId))
        db.session.close()
        return "", constants.STATUS_BAD_REQUEST

    if friendRequest.toUserId != g.user.id and friendRequest.fromUserId != g.user.id:
        print(
            "ERROR: Cannot get Friend request info when the user is not involved. User: "******" Req: " + str(requestId))
        db.session.close()
        return "", constants.STATUS_BAD_REQUEST

    toReturn = {
        "senderId":
        friendRequest.fromUserId,
        "senderName":
        friendRequest.sender.name,
        "senderImgUrl":
        friendRequest.sender.profileImgUrl,
        "senderPhone":
        friendRequest.sender.phoneNumber,
        "numSenderCards":
        0 if friendRequest.sender.cards is None else len(
            friendRequest.sender.cards),
        "recipientId":
        friendRequest.toUserId,
        "recipientName":
        friendRequest.recipient.name,
        "recipientImgUrl":
        friendRequest.recipient.profileImgUrl,
        "recipientPhone":
        friendRequest.recipient.phoneNumber,
        "numRecipientCards":
        0 if friendRequest.recipient.cards is None else len(
            friendRequest.recipient.cards),
        "createdOn":
        utils.getDateTimeAsString(friendRequest.createdOn),
        "resolvedOn":
        utils.getDateTimeAsString(friendRequest.resolvedOn),
        "status":
        friendRequest.status,
    }

    db.session.close()
    return jsonify(toReturn), constants.STATUS_OK
コード例 #10
0
def createNewFriendRequest():
    if "to" not in request.json:
        print("ERROR: There are no recipients for this request")
        return "", constants.STATUS_BAD_REQUEST

    if not g.user:
        print('ERROR: There is no user associated for friend request.')
        return "", constants.STATUS_BAD_REQUEST

    if request.json["to"] == g.user.id:
        print('ERROR: Cannot send friendrequest to the same user id: ' +
              str(request.json["to"]))
        return "", constants.STATUS_BAD_REQUEST

    to = request.json["to"]
    createdOn = datetime.datetime.now(
        tz=pytz.timezone(constants.TIMEZONE_KOLKATA))
    db.create_all()

    # Check if friend request already exists
    if FriendRequest.query.filter_by(fromUserId=g.user.id).filter_by(toUserId=to).first() or \
        FriendRequest.query.filter_by(fromUserId=to).filter_by(toUserId=g.user.id).first():
        print("ERROR: Friend request between: " + str(g.user.id) + " and: " +
              str(to) + " already exists")
        db.session.close()
        return "", constants.STATUS_CONFLICT_ERROR

    # Create new request
    friendRequest = FriendRequest(createdOn=createdOn,
                                  status=constants.FRIEND_REQUEST_ACTIVE)
    recipient = User.query.get(to)

    if not recipient:
        print("ERROR: No friend request recipient found with id: " + str(to))
        return "", constants.STATUS_BAD_REQUEST

    g.user.fRequests_sent.append(friendRequest)
    recipient.fRequests_rec.append(friendRequest)
    db.session.add(friendRequest)
    db.session.commit()

    notification = createNotificationForNewFriendRequest(g.user.name)
    data = {
        "requestId": str(friendRequest.id),
        "type": constants.FRIEND_REQUEST_NOTIFICATION_TYPE
    }
    fcmToken = recipient.fcmToken

    db.session.close()
    t = Thread(target=utils.sendDeviceNotification,
               args=(fcmToken, notification, data))
    t.start()
    return "", constants.STATUS_OK
コード例 #11
0
def createNewAccessRequest():
    if "to" not in request.json:
        print("ERROR: No user id provided to send the access request to")
        return "", constants.STATUS_BAD_REQUEST

    if "amount" not in request.json:
        print("ERROR: No amount provided to send access request for")
        return "", constants.STATUS_BAD_REQUEST

    if "cardId" not in request.json:
        print("ERROR: No cardId provided to send access request for")
        return "", constants.STATUS_BAD_REQUEST

    amount = request.json["amount"]
    to = request.json["to"]
    cardId = int(request.json["cardId"])
    shortDesc = constants.DATETIME_NOT_AVAILABLE if "shortDesc" not in request.json else request.json[
        "shortDesc"]
    mutualFriendName = None if "mutualFriendName" not in request.json else request.json[
        "mutualFriendName"]
    db.create_all()
    recipient = User.query.options(load_only('fcmToken')).get(to)
    if not recipient:
        print("ERROR: No user found with id: " + str(to) +
              " to send access request to")
        db.session.close()
        return "", constants.STATUS_BAD_REQUEST

    timeNow = datetime.datetime.now(
        tz=pytz.timezone(constants.TIMEZONE_KOLKATA))
    accessRequest = AccessRequest(cardId=cardId, amount=amount, shortDesc=shortDesc, mutualFriendName=mutualFriendName, \
                                status=constants.ACCESS_REQUEST_UNACCEPTED, createdOn=timeNow)
    g.user.aRequests_sent.append(accessRequest)
    recipient.aRequests_rec.append(accessRequest)
    db.session.add(accessRequest)
    db.session.commit()

    # Send notification in parallel
    notification = createNotificationForAccessRequest(g.user.name, cardId) if not mutualFriendName \
                    else createNotificationForSecondDegreeAccessRequest(g.user.name, mutualFriendName)
    fcmToken = recipient.fcmToken
    data = {
        "requestId": str(accessRequest.id),
        "type": constants.ACCESS_REQUEST_NOTIFICATION_TYPE,
    }

    db.session.close()
    t = Thread(target=utils.sendDeviceNotification,
               args=(fcmToken, notification, data))
    t.start()

    return "", constants.STATUS_OK
コード例 #12
0
def checkIfUserExists():
    if "idCode" not in request.args:
        print('ERROR: No idCode provided to check invite code for')
        return "", constants.STATUS_BAD_REQUEST

    idCode = request.args["idCode"]
    idCode = idCode.upper()
    db.create_all()
    exists = 0
    invitee = User.query.filter_by(idCode=idCode).first()
    if invitee:
        exists = 1

    db.session.close()
    return jsonify({"exists": exists}), constants.STATUS_OK
コード例 #13
0
def getAccessRequestInfo():
    if "id" not in request.args:
        print("ERROR: No id of access request provided")
        return "", constants.STATUS_BAD_REQUEST

    requestId = request.args["id"]
    db.create_all()
    accessRequest = AccessRequest.query.get(requestId)
    if not accessRequest:
        print("ERROR: No access request found for getAccessRequest with id: " +
              str(requestId))
        db.session.close()
        return "", constants.STATUS_BAD_REQUEST

    status = getAccessRequestStatus(accessRequest.createdOn,
                                    accessRequest.status)

    if accessRequest.toUserId != g.user.id and accessRequest.fromUserId != g.user.id:
        print(
            "ERROR: Cannot get access request info when the user is not involved. User: "******" Req: " + str(requestId))
        db.session.close()
        return "", constants.STATUS_BAD_REQUEST

    toReturn = {
        "senderId": accessRequest.fromUserId,
        "senderName": accessRequest.sender.name,
        "senderPhoneNumber": accessRequest.sender.phoneNumber,
        "senderFcmToken": accessRequest.sender.fcmToken,
        "senderImgUrl": accessRequest.sender.profileImgUrl,
        "recipientId": accessRequest.toUserId,
        "recipientName": accessRequest.recipient.name,
        "recipientPhoneNumber": accessRequest.recipient.phoneNumber,
        "recipientFcmToken": accessRequest.recipient.fcmToken,
        "recipientImgUrl": accessRequest.recipient.profileImgUrl,
        "amount": accessRequest.amount,
        "cardId": accessRequest.cardId,
        "cardName": getCardNameFromId(accessRequest.cardId),
        "status": status,
        "shortDesc": accessRequest.shortDesc,
        "mutualFriendName": accessRequest.mutualFriendName,
        "createdOn": utils.getDateTimeAsString(accessRequest.createdOn)
    }

    db.session.close()
    return jsonify(toReturn), constants.STATUS_OK
コード例 #14
0
ファイル: users.py プロジェクト: abhiram-n/Circles-Server
def updateUPI():
    if "upiID" not in request.json:
        print('ERROR: upiID parameter is required for updating UPI ID.')
        return "", constants.STATUS_BAD_REQUEST

    if not g.user:
        print('ERROR: There is no user associated with the token.')
        return "", constants.STATUS_BAD_REQUEST

    db.create_all()
    thisUser = g.user
    thisUser.upiID = request.json["upiID"]
    if (not commitToDB()):
        print('ERROR: Problem updating UPIID: ' + str(g.user.phoneNumber))
        return "", constants.STATUS_SERVER_ERROR

    return "", constants.STATUS_OK
コード例 #15
0
ファイル: users.py プロジェクト: abhiram-n/Circles-Server
def getProfile():
    db.create_all()

    # Check if profile is accessible to user
    accessible = False
    if "id" in request.args:
        if request.args["id"] == g.user.id:
            accessible = True
        else:
            if g.user.friends:
                for friendRow in g.user.friends:
                    if str(friendRow.friendId) == request.args["id"]:
                        accessible = True
                        break
    else:
        accessible = True

    if not accessible:
        print('ERROR: This user cannot access the profile.')
        db.session.close()
        return "", constants.STATUS_BAD_REQUEST

    thisUser = g.user if "id" not in request.args else User.query.get(
        request.args['id'])

    if not thisUser:
        print('ERROR: There is no user associated to get the profile for.')
        db.session.close()
        return "", constants.STATUS_BAD_REQUEST

    userCardIds = thisUser.cards
    responseString = {
        "name": thisUser.name,
        "phoneNumber": thisUser.phoneNumber,
        "cards": [],
        "upiID": thisUser.upiID,
        "profileImgUrl": thisUser.profileImgUrl,
    }

    if userCardIds:
        for cardId in userCardIds:
            cardName = getCardNameFromId(cardId)
            responseString["cards"].append({"name": cardName, "id": cardId})

    db.session.close()
    return jsonify(responseString), constants.STATUS_OK
コード例 #16
0
ファイル: users.py プロジェクト: abhiram-n/Circles-Server
def updateCards():
    if not g.user:
        print('ERROR: There is no user associated with the token.')
        return "", constants.STATUS_BAD_REQUEST
    db.create_all()
    thisUser = g.user

    # Cards
    selectedCards = json.loads(request.json["cards"])
    cards = []
    for selectedCard in selectedCards:
        if selectedCard["id"] not in cards:
            cards.append(selectedCard["id"])

    # remove the userid from existing cards
    if thisUser.cards is not None:
        for cardId in thisUser.cards:
            theCard = Card.query.get(cardId)
            if theCard is not None and theCard.users is not None:
                while thisUser.id in theCard.users:
                    theCard.users.remove(
                        thisUser.id
                    )  # there may be cases when duplicate ids exist so remove all.
                flag_modified(theCard, 'users')
    db.session.commit()
    print('Finished removing cards for user: '******'users')
    print('Finished adding cards for user: '******'cards')
    if (not commitToDB()):
        print('ERROR: Could not update cards for ID: ' + str(thisUser.id))
        return "", constants.STATUS_SERVER_ERROR

    return "", constants.STATUS_OK
コード例 #17
0
def getFriendRequestsSent():
    if not g.user:
        print(
            'ERROR: There is no user associated for getting friend requests sent.'
        )
        return "", constants.STATUS_BAD_REQUEST

    db.create_all()
    friendRequests = g.user.fRequests_sent
    if not friendRequests:
        return jsonify({"count": 0}), constants.STATUS_OK

    count = len(friendRequests)
    toReturn = {"count": count, "requests": []}
    for friendRequest in friendRequests:
        recipientName = friendRequest.recipient.name
        toReturn['requests'].append({"requestId": friendRequest.id,  \
            "id": friendRequest.toUserId, "name": recipientName, "createdOn": utils.getDateTimeAsString(friendRequest.createdOn), \
            "profileImgUrl": friendRequest.recipient.profileImgUrl, "resolvedOn": utils.getDateTimeAsString(friendRequest.resolvedOn), "status": friendRequest.status})
    db.session.close()
    return jsonify(toReturn), constants.STATUS_OK
コード例 #18
0
ファイル: users.py プロジェクト: abhiram-n/Circles-Server
def searchUser():
    if "idCode" not in request.args:
        print("ERROR: Cannot search for users without invite code.")
        return "", constants.STATUS_BAD_REQUEST

    if g.user.idCode.upper() == request.args["idCode"].upper():
        print('ERROR: Cannot return the same user when searching idCode')
        return "", constants.STATUS_BAD_REQUEST

    idCode = request.args["idCode"]
    idCode = idCode.upper()
    db.create_all()
    targetUser = User.query.options(load_only(
        "name", "id", "profileImgUrl")).filter_by(idCode=idCode).first()
    toReturn = {"count": 0}
    if targetUser:
        toReturn["count"] = 1
        toReturn["name"] = targetUser.name
        toReturn["id"] = targetUser.id
        toReturn["profileImgUrl"] = targetUser.profileImgUrl
    db.session.close()
    return jsonify(toReturn), constants.STATUS_OK
コード例 #19
0
def loginAfterPhoneAuth():
    if ("phoneNumber" not in request.json or "fcmToken" not in request.json):
        print("ERROR: Required parameters missing in phoneAuthLogin")
        return "", constants.STATUS_BAD_REQUEST
    phoneNumber = request.json['phoneNumber']
    fcmToken = ""
    if request.json['fcmToken']:
        fcmToken = request.json['fcmToken']

    db.create_all()
    currentUser = User.query.filter_by(phoneNumber=phoneNumber).first()

    if not currentUser:
        print("ERROR: Failed to fetch user with phone: " + str(phoneNumber))
        return "", constants.STATUS_UNAUTHORIZED

    currentUser.fcmToken = fcmToken
    currentUser.suspended = False
    access_token = currentUser.generate_auth_token(
        expiration=constants.TOKEN_EXPIRATION,
        key=os.environ['SECRET_KEY']).decode('ascii')
    try:
        db.session.commit()
    except Exception as err:
        db.session.rollback()
        print('ERROR: Exception while committing to database for phone: ' +
              str(phoneNumber) + ' error:' + str(err))
        db.session.close()
        return "", constants.STATUS_SERVER_ERROR

    userId = currentUser.id
    userPhoneNumber = currentUser.phoneNumber
    db.session.close()
    return jsonify({
        'access_token': access_token,
        "id": userId,
        "phoneNumber": userPhoneNumber
    }), constants.STATUS_OK
コード例 #20
0
ファイル: posts.py プロジェクト: abhiram-n/Circles-Server
def getPostInfo():
    if "id" not in request.args:
        print("ERROR: No post id provided")
        return "", constants.STATUS_BAD_REQUEST

    db.create_all()
    postId = request.args["id"]
    post = Post.query.get(request.args["id"])
    if not post:
        print('ERROR: No post found with given id: ' + str(postId))
        return "", constants.STATUS_BAD_REQUEST

    toReturn = {
        "id": post.id,
        "creatorName": post.creator.name,
        "creatorImgUrl": post.creator.profileImgUrl,
        "creatorId": post.creatorId,
        "text": post.text,
        "createdOn": utils.getDateTimeAsString(post.createdOn),
    }

    db.session.close()
    return jsonify(toReturn), constants.STATUS_OK
コード例 #21
0
def verifyAuthCode():
    if "phoneNumber" not in request.json:
        print('ERROR: No phone number found to verify code for.')
        return "", constants.STATUS_BAD_REQUEST

    if "code" not in request.json:
        print('ERROR: No code received for verification')
        return "", constants.STATUS_BAD_REQUEST

    phoneNumber = request.json["phoneNumber"]
    code = request.json["code"]
    db.create_all()

    # ensure verification is pending
    pendingVerification = AuthCodeVerification.query.filter_by(
        phoneNumber=phoneNumber).first()
    if not pendingVerification:
        print('ERROR: No verification pending for this phone number: ' +
              str(phoneNumber))
        db.session.close()
        return "", constants.STATUS_BAD_REQUEST

    # Check if code is the same
    if code != pendingVerification.code:
        db.session.close()
        return jsonify({"status": constants.CODE_VERIFICATION_FAILED
                        }), constants.STATUS_OK

    # Check expiry and delete the verification record
    now = datetime.datetime.now(tz=pytz.timezone(constants.TIMEZONE_KOLKATA))
    status = constants.CODE_VERIFICATION_SUCCEEDED
    if now > pendingVerification.expiration:
        print('ERROR: Code has expired for phone: ' + str(phoneNumber))
        status = constants.CODE_VERIFICATION_EXPIRED
    db.session.delete(pendingVerification)
    commitToDB()  # ignore failures here, not important to fail the request
    return jsonify({"status": status}), constants.STATUS_OK
コード例 #22
0
def getAccessRequestsSent():
    if not g.user:
        print(
            'ERROR: There is no user associated for getting access requests sent.'
        )
        return "", constants.STATUS_BAD_REQUEST

    db.create_all()
    accessRequests = AccessRequest.query.filter_by(
        fromUserId=g.user.id).order_by(desc(AccessRequest.createdOn)).all()
    if not accessRequests:
        return jsonify({"count": 0}), constants.STATUS_OK

    count = len(accessRequests)
    toReturn = {"count": count, "requests": []}
    for accessRequest in accessRequests:
        recipientName = accessRequest.recipient.name
        cardName = getCardNameFromId(accessRequest.cardId)
        toReturn['requests'].append({"requestId": accessRequest.id, "cardId": accessRequest.cardId, "cardName": cardName, \
            "id": accessRequest.toUserId, "name": recipientName, "profileImgUrl": accessRequest.recipient.profileImgUrl, \
            "createdOn": utils.getDateTimeAsString(accessRequest.createdOn), "resolvedOn": utils.getDateTimeAsString(accessRequest.resolvedOn), \
            "shortDesc": accessRequest.shortDesc, "status": getAccessRequestStatus(accessRequest.createdOn, accessRequest.status), "amount": accessRequest.amount})
    db.session.close()
    return jsonify(toReturn), constants.STATUS_OK
コード例 #23
0
def signup():
    if ("name" not in request.json or "phoneNumber" not in request.json
            or "cards" not in request.json or "fcmToken" not in request.json):
        print('ERROR: One of the required fields is missing')
        return "", constants.STATUS_BAD_REQUEST

    if ("password" not in request.json and "phoneAuth" not in request.json):
        print('ERROR: No password or phone verification found.')
        return "", constants.STATUS_BAD_REQUEST

    name = request.json["name"]
    phoneNumber = request.json["phoneNumber"]
    inviteCodeUsed = request.json["inviteCode"]
    fcmToken = ""
    profileImgUrl = "" if "profileImgUrl" not in request.json else request.json[
        "profileImgUrl"]
    fcmToken = "" if "fcmToken" not in request.json else request.json[
        "fcmToken"]
    created_time = utils.getDateTimeAsString(
        datetime.datetime.now(tz=pytz.timezone(constants.TIMEZONE_KOLKATA)))

    # Cards
    selectedCards = json.loads(request.json["cards"])
    cards = []
    for selectedCard in selectedCards:
        cards.append(selectedCard["id"])

    strPhone = str(phoneNumber)
    print('Adding user: '******'ERROR: User with phone number already exists')
        db.session.close()
        return "", constants.STATUS_CONFLICT_ERROR

    newUser = User(name=name,
                   fcmToken=fcmToken,
                   upiID="",
                   phoneNumber=phoneNumber,
                   inviteCodeUsed=inviteCodeUsed,
                   cards=cards,
                   suspended=False,
                   joined=created_time,
                   idCode=idCode,
                   profileImgUrl=profileImgUrl)

    # SQLAlchemy not aware of ARRAY changes unless flag_modified is called
    flag_modified(newUser, 'cards')
    db.session.add(newUser)

    try:
        db.session.flush()
        for selectedCard in selectedCards:
            theCard = Card.query.get(selectedCard["id"])
            if theCard is not None:
                if theCard.users is None:
                    theCard.users = []
                theCard.users.append(newUser.id)
                flag_modified(theCard, 'users')
        db.session.commit()
        newUserId = newUser.id
        newUserPhone = newUser.phoneNumber
        access_token = newUser.generate_auth_token(
            expiration=constants.TOKEN_EXPIRATION,
            key=os.environ['SECRET_KEY']).decode('ascii')
    except exc.IntegrityError as ex:
        db.session.rollback()
        print('ERROR: For User: '******'. Exception while committing to database: ' + str(ex))
        return "", constants.STATUS_CONFLICT_ERROR
    except Exception as err:
        db.session.rollback()
        print('ERROR: For User: '******'. Exception while committing to database: ' + str(err))
        return "", constants.STATUS_SERVER_ERROR
    finally:
        db.session.close()

    return jsonify({
        'access_token': access_token,
        'id': newUserId,
        "phoneNumber": newUserPhone
    }), constants.STATUS_OK
コード例 #24
0
def respondToFriendRequest():
    if "action" not in request.json:
        print(
            "ERROR: There are no actions specified in the friend request response"
        )
        return "", constants.STATUS_BAD_REQUEST

    if "requestId" not in request.json:
        print("ERROR: ID of the friend request is missing")
        return "", constants.STATUS_BAD_REQUEST

    if not g.user:
        print(
            'ERROR: There is no user associated for friend request response.')
        return "", constants.STATUS_BAD_REQUEST

    action = request.json["action"]
    requestId = request.json["requestId"]
    db.create_all()

    if "limit" in request.json:
        limit = request.json["limit"]
        if g.user.friends and len(g.user.friends) >= limit:
            print('ERROR: User: '******' has reached the limit of friend requests')
            db.session.close()
            return "", constants.STATUS_PRECONDITION_FAILED

    friendRequest = FriendRequest.query.get(requestId)
    if not friendRequest:
        print("ERROR: No friend request found with id: " + str(requestId))
        db.session.close()
        return "", constants.STATUS_BAD_REQUEST

    if g.user.id != friendRequest.toUserId:
        print(
            "ERROR: Cannot respond to request that is not sent to the user id: "
            + str(g.user.id))
        db.session.close()
        return "", constants.STATUS_BAD_REQUEST

    if friendRequest.status == action:
        print("WARNING: Friend request status already at the desired state:" +
              str(action))
        db.session.close()
    else:
        data = {
            "requestId": str(friendRequest.id),
            "type": constants.FRIEND_REQUEST_NOTIFICATION_TYPE,
            "isUserSender":
            "true"  # the notification is sent to the user who sent the request
        }
        fcmToken = friendRequest.sender.fcmToken

        notification = createNotificationForDeclinedFriendRequest(g.user.name)
        friendRequest.status = action
        timeNow = datetime.datetime.now(
            tz=pytz.timezone(constants.TIMEZONE_KOLKATA))
        friendRequest.resolvedOn = timeNow
        if (action == constants.FRIEND_REQUEST_ACCEPTED):
            friendFirstRow = Friend(fRequestId=requestId,
                                    friendId=friendRequest.fromUserId,
                                    startedOn=timeNow)
            g.user.friends.append(friendFirstRow)
            friend = User.query.get(friendRequest.fromUserId)
            friendSecondRow = Friend(fRequestId=requestId,
                                     friendId=g.user.id,
                                     startedOn=timeNow)
            friend.friends.append(friendSecondRow)
            db.session.add(friendFirstRow)
            db.session.add(friendSecondRow)
            notification = createNotificationForAcceptedFriendRequest(
                g.user.name)

        if (not commitToDB()):
            print('ERROR: Problem resolving the friend request')
            return "", constants.STATUS_SERVER_ERROR

    t = Thread(target=utils.sendDeviceNotification,
               args=(fcmToken, notification, data))
    t.start()

    return "", constants.STATUS_OK
コード例 #25
0
ファイル: users.py プロジェクト: abhiram-n/Circles-Server
def searchCardholders():
    if "cardId" not in request.args:
        print("ERROR: Cardholders cannot be obtained without cardId")
        return "", constants.STATUS_BAD_REQUEST

    db.create_all()
    cardId = request.args["cardId"]
    toReturn = {"numFirst": 0, "numSecond": 0, "first": [], "second": []}

    theCard = Card.query.get(cardId)

    if not theCard:
        print("ERROR: There is not card matching the given cardId: " +
              str(cardId))
        return "", constants.STATUS_BAD_REQUEST

    cardIds = []
    if theCard.objectType == constants.CARD_TYPE_TAG:
        cardsWithTag = Card.query.filter_by(tagId=theCard.id)
        for cardWithTag in cardsWithTag:
            cardIds.append(int(cardWithTag.id))
    else:
        cardIds = [int(cardId)]

    processedIds = []
    friendIds = []

    # Search first degree friends with card
    for friendRow in g.user.friends:
        if str(friendRow.friendId) in processedIds:
            continue

        friendIds.append(friendRow.friendId)
        friend = User.query.get(friendRow.friendId)
        processedIds.append(str(friendRow.friendId))
        if not friend:
            print("WARNING: No friend with id: " + str(friendRow.friendId))
            continue

        if not friend.cards:
            continue

        for oneCardId in cardIds:
            if oneCardId in friend.cards:
                toReturn["first"].append({"name": friend.name, "id": friend.id, "phoneNumber": friend.phoneNumber, \
                    "cardId": oneCardId, "cardName": getCardNameFromId(oneCardId)})
                toReturn["numFirst"] += 1

    # Search second degree friends with card
    for friendId in friendIds:
        friend = User.query.get(friendId)
        if not friend:
            continue

        for secondDegreeFriendRow in friend.friends:
            # Ignore the current user in the list of friends
            if secondDegreeFriendRow.friendId == g.user.id or str(
                    secondDegreeFriendRow.friendId) in processedIds:
                continue

            secondDegreeFriend = User.query.get(secondDegreeFriendRow.friendId)
            processedIds.append(str(secondDegreeFriendRow.friendId))
            if not secondDegreeFriend:
                print("WARNING: No second degree friend with id: " +
                      str(secondDegreeFriendRow.friendId))
                continue

            if not secondDegreeFriend.cards:
                continue

            for oneCardId in cardIds:
                if oneCardId in secondDegreeFriend.cards:
                    toReturn["second"].append({"name": secondDegreeFriend.name, "id": secondDegreeFriend.id, \
                        "cardId": oneCardId, "cardName": getCardNameFromId(oneCardId), "friendName": friend.name})
                    toReturn["numSecond"] += 1

    db.session.close()
    return jsonify(toReturn), constants.STATUS_OK