def oauth_redirect(request, response):
    # Take email to authenticate, then when user is authenticated generate session and store session.
    data = request.data
    code_grant = data["code_grant"]

    code = exchange_token(code_grant)

    if code is not None:
        jwt_id_token = code["id_token"]
        id_token = jwt.decode(jwt_id_token.encode("utf-8"),
                              options={"verify_signature": False})
        user_id = id_token["email"]
        sessionToken = str(uuid4())
        store_session(sessionToken, user_id)
        user_info = get_user_info(user_id)

        new_user = False
        if user_info is None:
            new_user = True

        response.body = {"new_user": new_user}
        response.set_session(sessionToken)
    else:
        raise WebException(status_code=HTTPStatus.BAD_REQUEST,
                           message="Invalid credentials")

    return response
def create_checkout_session(request, response):
    priceID = request.data["priceId"]
    domain_url = os.environ["URL"]

    try:
        # Create new Checkout Session for the order
        # Other optional params include:
        # [billing_address_collection] - to display billing address details on the page
        # [customer] - if you have an existing Stripe Customer ID
        # [customer_email] - lets you prefill the email input in the form

        # ?session_id={CHECKOUT_SESSION_ID} means the redirect will have the session ID set as a query param
        checkout_session = stripe.checkout.Session.create(
            success_url=domain_url +
            "/Success.html?session_id={CHECKOUT_SESSION_ID}",
            cancel_url=domain_url + "/Cancel.html",
            payment_method_types=["card"],
            mode="subscription",
            line_items=[{
                "price": priceID,
                "quantity": 1
            }],
        )
        # line_items = stripe.checkout.Session.list_line_items(checkout_session["id"])
        # response.body = line_items
        response.body = {"sessionId": checkout_session["id"]}
        return response
    except Exception as e:
        raise WebException(status_code=HTTPStatus.BAD_REQUEST,
                           message=str(e)) from e
def updateTalent(request, response):
    data = request.data
    file = data["photo"]
    image = base64.b64decode(str(file))
    URL = data["url"]
    targetKey = getUUID(URL)

    # Setting other values
    talent_name = data["talentName"]
    talent_bio = data["talentBio"]
    # UPDATE THIS 2 VARIABLES TO NOT BE HARDCODED
    bucketName = "csc-assignment-photo-bucket-aloy"
    bucketRegion = "us-east-1"

    try:
        s3Response = init_client().upload_fileobj(image, bucketName, targetKey)
        logging.info("updateTalentImage -- S3 Update response: %s", s3Response)

        # Set the s3 URL to current Image
        URL = "https://" + bucketName + ".s3." + bucketRegion + ".amazonaws.com/" + targetKey

        # Update mySql table
        updateQuery = "UPDATE talent SET UrlLink='%s', Name='%s', Bio='%s' WHERE UrlLink LIKE '%s'", (
            URL, talent_name, talent_bio, targetKey)
        uploadToSql(updateQuery)

    except ClientError as e:
        logging.error("updateTalentImage -- %s", e)
        raise WebException(status_code=HTTPStatus.BAD_REQUEST,
                           message=str(e)) from e

    return response
def init_client():
    try:
        return boto3.client('s3', region_name='us-east-1')
    except ClientError as e:
        logging.error("init_client -- %s", e)
        raise WebException(status_code=HTTPStatus.BAD_REQUEST,
                           message=str(e)) from e
Beispiel #5
0
    def resolve_function(self):
        self.function = APILIST.get(self.method, {}).get(self.endpoint, None)
        if not self.function:
            raise WebException(status_code=HTTPStatus.NOT_FOUND,
                               message="Invalid API")

        return self
Beispiel #6
0
    def retrieve_user(self):
        session_cookie = self.cookies.get("session", None)
        if session_cookie is None:
            self.session_token = None
        else:
            self.session_token = session_cookie.value

        if self.endpoint in [
            "create-checkout-session",
            "get-publishable-key",
            "customer-portal",
            "manage-billing",
            "create-comment",
            "checkout-session",
            "logout",
        ]:
            print("Logged In Method Invoked")
            self.username = get_session_username(self.session_token)
            print(self.username)
            if not self.username:
                raise WebException(
                    status_code=HTTPStatus.UNAUTHORIZED, message="Unauthenticated User"
                )
            user_info = get_user_info(self.username)
            if user_info is None:
                self.paiduser = False
            else:
                self.paiduser = (
                    True if user_info["subscription_type"] == "Paid" else False
                )
            print(self.paiduser)

        return self
Beispiel #7
0
 def parse_data(self):
     if self.method in ["GET", "DELETE"]:
         qsp = self.event.get("queryStringParameters", {})
         self.data = {} if qsp is None else qsp
     elif self.method in ["POST", "PUT"]:
         body = self.event.get("body", "{}")
         body = "{}" if not body else body
         try:
             self.data = json.loads(body)
         except Exception as ex:
             raise WebException(status_code=HTTPStatus.BAD_REQUEST,
                                message="Invalid JSON") from ex
     return self
def init_client():
    try:
        connection = pymysql.connect(
            host=os.environ["RDS_HOST"],
            user=os.environ["RDS_USER"],
            password=os.environ["RDS_PASSWORD"],
            database=os.environ["RDS_DATABASE"],
        )
        logging.info("Connection to mySql server successful!")
        return connection
    except WebException as e:
        logging.exception("RDS MySQL Connection Failed")
        raise WebException()
Beispiel #9
0
def webhook_received(request, response):
    webhook_secret = os.environ["STRIPE_WEBHOOK_SECRET"]
    raw_body = request.event.get("body", "")
    request_data = request.data
    if webhook_secret:
        # Retrieve the event by verifying the signature using the raw body and secret if webhook signing is configured.
        signature = request.headers.get("stripe-signature")
        try:
            event = stripe.Webhook.construct_event(raw_body, signature,
                                                   webhook_secret)
            data = event["data"]
        except Exception as e:
            print(e)
            raise WebException(status_code=HTTPStatus.BAD_REQUEST,
                               message=str(e)) from e
        # Get the type of webhook event sent - used to check the status of PaymentIntents.
        event_type = event["type"]
    else:
        data = request_data["data"]
        event_type = request_data["type"]

    data_object = data["object"]
    # print(data_object)
    now = datetime.now()
    customer_id = data_object["customer"]
    username = get_username_from_customerid(customer_id)
    subscription_plan = ""
    subscription_id = data_object["items"]["data"][0]["price"]["id"]
    if subscription_id == os.environ["FREE_PRICE_ID"]:
        subscription_plan = "Free"
    elif subscription_id == os.environ["PRO_PRICE_ID"]:
        subscription_plan = "Paid"

    print("event " + event_type)

    if event_type in [
            "customer.subscription.updated", "invoice.payment_succeeded"
    ]:
        lastPayment = now.strftime("%d/%m/%Y %H:%M:%S")
        create_or_update_user_info(username, customer_id, subscription_plan,
                                   lastPayment)
        mysql_lastPayment = now.strftime("%Y-%m-%d %H:%M:%S")
        updateUserData(username, subscription_plan, mysql_lastPayment)
        print("Payment updated!")

    if event_type == "customer.subscription.deleted":
        delete_item(username)
        print("Subscription deleted!")
    return response
Beispiel #10
0
def get_talent_detail(request, response):
    data = request.data

    try:
        getTalentData = f"Select * from talent where TalentId = {data['talentId']}"
        talentResult = getResult(getTalentData)

        oneResult = talentResult[0]
        talentDict = {
            "urlLink": oneResult["UrlLink"],
            "name": oneResult["Name"],
            "bio": oneResult["Bio"],
        }
        response.body = talentDict
        return response

    except Exception as e:
        raise WebException(status_code=HTTPStatus.BAD_REQUEST,
                           message=str(e)) from e
def uploadImage(request, response):
    # Load file
    data = request.data
    print(data)
    file = data["photo"]
    image = base64.b64decode(str(file))

    # Validations
    # if (containsHumanFace(file) == False):
    #     raise WebException(status_code=HTTPStatus.BAD_REQUEST, message="uploadImage -- File failed Validations.")

    # Setting UUID for this file
    objectKey = str(uuid.uuid4())
    logging.info("uploadImage -- New UUID: %s", objectKey)

    # Setting other values
    talent_name = data["talentName"]
    talent_bio = data["talentBio"]
    # UPDATE THIS 2 VARIABLES TO NOT BE HARDCODED
    bucketName = "csc-assignment-2-photo-bucket-aloy"
    bucketRegion = "us-east-1"

    try:
        # Uploading file to S3
        s3 = boto3.resource('s3')
        # obj = s3.Object(bucketName, objectKey)
        # obj.put(Body=file)
        s3.Bucket(bucketName).put_object(key=object, Body=file)

        # Set the s3 URL to current Image
        URL = "https://" + bucketName + ".s3." + bucketRegion + ".amazonaws.com/" + objectKey

        # Upload to mySql table
        insertQuery = "INSERT INTO talent (UrlLink, Name, Bio) VALUES (%s, %s, %s)", (
            URL, talent_name, talent_bio)
        uploadToSql(insertQuery)

    except Exception as e:
        logging.error("uploadImage -- %s", e)
        raise WebException(status_code=HTTPStatus.BAD_REQUEST,
                           message=str(e)) from e

    return response
def getAllTalents(request, response):
    connection = pymysql.connect(host=os.environ["RDS_HOST"],
                                 user=os.environ["RDS_USER"],
                                 password=os.environ["RDS_PASSWORD"],
                                 database=os.environ["RDS_DATABASE"])
    logging.info("getAllTalents -- Connection to mySql server successful!")
    try:
        cur = connection.cursor()
        rows = cur.fetchall()
        allTalentsJson = json.dumps(rows)
        response.body = allTalentsJson
        return response

    except ClientError as e:
        logging.error(e)
        raise WebException(status_code=HTTPStatus.BAD_REQUEST,
                           message="uploadImage -- File failed Validations.")
    finally:
        logging.info("uploadToSql -- Closing mySql connection")
        connection.close()
def deleteTalent(request, response):
    data = request.data
    URL = data["url"]
    targetKey = getUUID(URL)

    # UPDATE THIS VARIABLE TO NOT BE HARDCODED
    bucketName = "csc-assignment-photo-bucket-aloy"

    try:
        s3Response = init_client().delete_object(bucketName, targetKey)
        logging.info("deleteTalent -- S3 Delete response: %s", s3Response)

        # Delete mySql table
        deleteQuery = "DELETE FROM talents WHERE UrlLink LIKE '%s'", (
            targetKey)
        uploadToSql(deleteQuery)

    except ClientError as e:
        logging.error("deleteTalent -- %s", e)
        raise WebException(status_code=HTTPStatus.BAD_REQUEST,
                           message=str(e)) from e

    return response
def create_comment(request, response):
    data = request.data
    now = datetime.now()
    count = 0
    paId = ""

    try:
        insert_comment_query = "Insert into comment_management (UserId, TalentId, Comment, ParentId, CreatedAt, UpdatedAt) Values (%s, %s, %s, %s, %s, %s);"
        getNewCommentId = "Select LAST_INSERT_ID();"
        userId = int(data["userId"])
        comment = data["content"]
        createdAt = now.strftime("%Y-%m-%d %H:%M:%S")
        updatedAt = now.strftime("%Y-%m-%d %H:%M:%S")
        parentId = 0
        if not data["parent"] is None:
            parentId = int(data["parent"])
        else:
            parentId = None
        talentId = int(data["talentId"])
        commentId = insertComment(
            insert_comment_query,
            getNewCommentId,
            (userId, talentId, comment, parentId, createdAt, updatedAt),
        )
        count = 1

        id = [id[0] for id in commentId]

        if count == 1:

            get_new_comment_query = f"Select CommentId, c.UserId, Comment, ParentId, c.CreatedAt, c.UpdatedAt, UrlLink, Name, Bio, FullName, us.Subscription from talent t, comment_management c, users u, user_subscription us where c.TalentId = {data['talentId']} and CommentId = {id[0]} and c.TalentId = t.TalentId and u.Id = c.UserId and u.Subscription = us.Id;"

            comment_result = getResult(get_new_comment_query)

            oneResult = comment_result[0]
            if oneResult["ParentId"] is None:
                paId = None
            else:
                paId = int(oneResult["ParentId"])
            createdBy = ""
            createdByCurrentUser = True
            if int(oneResult["UserId"]) == int(data["userId"]):
                createdBy = "You"
                createdByCurrentUser = True
            else:
                createdBy = oneResult["FullName"]
                createdByCurrentUser = False

            commentDict = {
                "id": int(oneResult["CommentId"]),
                "parent": paId,
                "content": oneResult["Comment"],
                "fullname": createdBy,
                "created": str(oneResult["CreatedAt"]),
                "modified": str(oneResult["UpdatedAt"]),
                "createdByCurrentUser": createdByCurrentUser,
            }
            response.body = commentDict

            return response

    except Exception as e:
        raise WebException(status_code=HTTPStatus.BAD_REQUEST,
                           message=str(e)) from e
def init_client():
    try:
        return boto3.client("dynamodb", region_name="us-east-1")
    except ClientError as ce:
        logging.exception("DynamoDB Failed")
        raise WebException()
Beispiel #16
0
def create_comment(request, response):
    data = request.data
    now = datetime.now()
    count = 0
    paId = ""

    username = get_session_username(data["session"])

    try:
        getUserDetails = f"Select * from user_data where UserName = '******';"
        userData = getResult(getUserDetails)

        oneUserDetail = userData[0]
        insert_comment_query = "Insert into comment (UserId, TalentId, Comment, ParentId, CreatedAt, UpdatedAt) Values (%s, %s, %s, %s, %s, %s);"
        getNewCommentId = "Select LAST_INSERT_ID();"
        userId = oneUserDetail["Id"]
        comment = data["content"]
        createdAt = now.strftime("%Y-%m-%d %H:%M:%S")
        updatedAt = now.strftime("%Y-%m-%d %H:%M:%S")
        parentId = 0
        if not data["parent"] is None:
            parentId = int(data["parent"])
        else:
            parentId = None
        talentId = int(data["talentId"])
        commentId = insertComment(
            insert_comment_query,
            getNewCommentId,
            (userId, talentId, comment, parentId, createdAt, updatedAt),
        )
        count = 1

        id = [id[0] for id in commentId]

        if count == 1:

            get_new_comment_query = f"Select CommentId, UserId, Comment, ParentId, CreatedAt, UpdatedAt, UserName from comment c, user_data u where c.TalentId = {data['talentId']} and CommentId = {id[0]} and u.Id = c.UserId;"

            comment_result = getResult(get_new_comment_query)

            oneResult = comment_result[0]
            if oneResult["ParentId"] is None:
                paId = None
            else:
                paId = int(oneResult["ParentId"])
            createdBy = ""
            createdByCurrentUser = True
            if oneResult["UserName"] == str(username):
                createdBy = "You"
                createdByCurrentUser = True
            else:
                createdBy = oneResult["UserName"]
                createdByCurrentUser = False

            commentDict = {
                "id": int(oneResult["CommentId"]),
                "parent": paId,
                "content": oneResult["Comment"],
                "fullname": createdBy,
                "created": str(oneResult["CreatedAt"]),
                "modified": str(oneResult["UpdatedAt"]),
                "createdByCurrentUser": createdByCurrentUser,
            }
            response.body = commentDict

            return response

    except Exception as e:
        raise WebException(status_code=HTTPStatus.BAD_REQUEST,
                           message=str(e)) from e
Beispiel #17
0
def get_comments(request, response):
    data = request.data

    username = get_session_username(data["session"])

    commentList = []

    try:

        createdBy = ""
        createdByCurrentUser = True

        getUserDetails = f"Select SubscriptionPlan from user_data where UserName = '******';"

        getCommentOfTalent = f"Select CommentId, c.UserId, Comment, ParentId, c.CreatedAt, c.UpdatedAt, UserName from talent t, comment c, user_data u where c.TalentId = {data['talentId']} and c.TalentId = t.TalentId and u.Id = c.UserId;"

        userData = getResult(getUserDetails)

        oneUserDetail = userData[0]

        allCommentsResult = getResult(getCommentOfTalent)

        for oneComment in allCommentsResult:
            if not oneComment["ParentId"] is None:
                if str(oneComment["UserName"]) in str(username):
                    createdBy = "You"
                    createdByCurrentUser = True
                else:
                    createdBy = str(oneComment["UserName"])
                    createdByCurrentUser = False

                commentDict = {
                    "id": int(oneComment["CommentId"]),
                    "createdByCurrentUser": createdByCurrentUser,
                    "content": oneComment["Comment"],
                    "fullname": createdBy,
                    "parent": oneComment["ParentId"],
                    "created": str(oneComment["CreatedAt"]),
                    "modified": str(oneComment["UpdatedAt"]),
                }

                commentList.append(commentDict)

            else:
                if str(oneComment["UserName"]) in str(username):
                    createdBy = "You"
                    createdByCurrentUser = True

                else:
                    createdBy = oneComment["UserName"]
                    createdByCurrentUser = False

                commentDict = {
                    "id": int(oneComment["CommentId"]),
                    "createdByCurrentUser": createdByCurrentUser,
                    "content": oneComment["Comment"],
                    "fullname": createdBy,
                    "parent": None,
                    "created": str(oneComment["CreatedAt"]),
                    "modified": str(oneComment["UpdatedAt"]),
                }

                commentList.append(commentDict)

        response.body = {
            "commentResult": commentList,
            "SubscriptionPlan": oneUserDetail["SubscriptionPlan"],
        }
        return response

    except Exception as e:
        raise WebException(status_code=HTTPStatus.BAD_REQUEST,
                           message=str(e)) from e