def end_session():
    #  print("session end request", session_app.current_request.headers)
    # new_cookie = session_app.current_request.headers['Cookie']
    # print("cookie information for session end request", new_cookie)
    user_id = global_auth.get_authorized_user_id(session_app.current_request)
    session_id = global_auth.get_authorized_session_id(
        session_app.current_request)
    email = global_auth.get_authorized_email(session_app.current_request)
    if not user_id or not session_id or not email:
        return Response(body={"message": "session not found"}, status_code=400)
    session_audit_payload = {
        "sessionId": session_id,
        "statusId": 3,
        "status": "COMPLETED",
        "timestamp": str(datetime.utcnow())
    }
    user_audit_payload = {
        "userId": user_id,
        "roleId": 3,
        "status": "LEFT",
        "timestamp": str(datetime.utcnow()),
        'email': email
    }
    audit_controller.update_audit("session", session_audit_payload)
    audit_controller.update_audit("user", user_audit_payload)
    session_status_payload = {"sessionId": session_id, "status": "COMPLETED"}
    update_session_status(session_status_payload)

    return Response(body={"message": "success"}, status_code=200)
def update_session_audit():
    body = audit_app.current_request.json_body
    if not body:
        return Response(body={"message": "no required details"},
                        status_code=422)
    if not body.get("status", False):
        return Response({"message": "status field is required"},
                        status_code=422)
    body['uid'] = str(uuid4())
    body['sessionId'] = global_auth.get_authorized_session_id(
        audit_app.current_request)
    response = global_db_handler.get_session_audit_db().add_item(body)
    return Response(body={"message": "updated"}, status_code=200)
def update_session_status_api():
    body = session_app.current_request.json_body
    log.info(f"session status update {body}")

    if not body or not body.get('status', False):
        return Response(
            body={'message': 'empty body, status field is required '},
            status_code=422)
    if not body.get('sessionId', False):
        body['sessionId'] = global_auth.get_authorized_session_id(
            session_app.current_request)
    response = global_db_handler.get_session_db().update_item(body)
    return Response(body=response, status_code=200)
def test_jwt_session():
    user_id = global_auth.get_authorized_user_id(session_app.current_request)
    session_id = global_auth.get_authorized_session_id(
        session_app.current_request)
    user_data = global_auth.get_authorized_user_data(
        session_app.current_request)
    email = global_auth.get_authorized_email(session_app.current_request)
    response = {
        "sessionId": session_id,
        "userId": user_id,
        "user_data": user_data,
        "email": email
    }
    response = global_db_handler.replace_decimals(response)
    return {"message": response}
def update_session_duration():
    body = session_app.current_request.json_body
    log.info(f"session status update {body}")

    if not body or not body.get('duration', False):
        return Response(
            body={'message': 'empty body, duration field is required'},
            status_code=422)

    if not isinstance(body['duration'], int):
        return Response(body={'message': 'duration field is int'},
                        status_code=422)

    if not body.get('sessionId', False):
        body['sessionId'] = global_auth.get_authorized_session_id(
            session_app.current_request)
    response = global_db_handler.get_session_db().update_duration(body)
    response = global_db_handler.replace_decimals(response)
    return Response(body=response, status_code=200)
Example #6
0
def update_feedback():
    body = feedback_app.current_request.json_body
    if not body:
        return Response(body={"message": "no required details"},
                        status_code=422)
    if not body.get("rating", False) or not body.get("note", False):
        return Response(
            body={"message": "rating and note fields are mandatory"},
            status_code=422)
    log.info(feedback_app.current_request.context)
    body['uid'] = str(uuid4())
    body['sessionId'] = global_auth.get_authorized_session_id(
        feedback_app.current_request)
    current_user_data = global_auth.get_authorized_user_data(
        feedback_app.current_request)
    body['email'] = current_user_data['email']
    body['role'] = current_user_data['role']
    body['userId'] = current_user_data['userId']
    body['timestamp'] = str(datetime.utcnow())

    response = global_db_handler.get_feedback_db().add_item(body)
    return Response(body={"message": "updated"}, status_code=200)
def session_notify_api():
    log.info("notification api")
    session_id = global_auth.get_authorized_session_id(
        session_app.current_request)
    user_data = global_auth.get_authorized_user_data(
        session_app.current_request)
    user_role = user_data['role']
    phone_number_list = []
    email_list = []
    log.info(f"user role {user_role}")
    if user_role == "student":
        user_details = global_db_handler.get_session_db().get_user_details(
            session_id, "tutor")
        log.info(f"tutor details to notify session {user_details}")
        phone_number_list = [{
            "user_details": {
                "first_name": user_details["tutor"]["firstName"],
                "phone_number": user_details["tutor"]["phoneNumber"]
            }
        }]
        email_list = [{
            "user_details": {
                "first_name": user_details["tutor"]["firstName"],
                "email": user_details["tutor"]["email"]
            }
        }]
    elif user_role == "tutor":
        user_details = global_db_handler.get_session_db().get_user_details(
            session_id, "student")
        log.info(f"student details to notify session {user_details}")
        for each_item in user_details['students']:
            log.debug(each_item)
            phone_number_list.append({
                "user_details": {
                    "phone_number": each_item["phoneNumber"],
                    "first_name": each_item["firstName"]
                }
            })
            email_list.append({
                "user_details": {
                    "email": each_item["email"],
                    "first_name": each_item["firstName"]
                }
            })
    else:
        log.info(f"unknown user role. may be level admin ?. {user_role}")
        return Response(body={"message": "user role not identified"},
                        status_code=400)
    log.info(f'sending email to users with info {user_details}')
    response = {
        'email_list': email_list,
        'phone_number_list': phone_number_list
    }
    phone_status = global_auth.invokeLambda.invoke(
        FunctionName=
        f"arn:aws:lambda:{os.environ['CURRENT_REGION']}:886064876783:function:sessions-app-dev"
        f"-SessionNotificationsPhone",
        InvocationType="RequestResponse",
        Payload=json.dumps(response))
    log.info(f"text messages sent {phone_status}")
    email_status = global_auth.invokeLambda.invoke(
        FunctionName=
        f"arn:aws:lambda:{os.environ['CURRENT_REGION']}:886064876783:function:sessions-app-dev"
        f"-SessionNotificationsEmail",
        InvocationType="RequestResponse",
        Payload=json.dumps(response))

    log.info(f"emails sent {email_status}")

    return Response(body={
        "phoneStatus":
        phone_status['ResponseMetadata']['HTTPStatusCode'],
        "emailStatus":
        email_status['ResponseMetadata']['HTTPStatusCode']
    },
                    status_code=202)
def generate_openvidu_token():
    """
    handles openvidu connections and token related stuff
    :return: openvidu url and token
    """
    try:

        body = session_app.current_request.json_body

        session_id = global_auth.get_authorized_session_id(
            session_app.current_request)
        data = {
            "mediaMode": "ROUTED",
            "recordingMode": "ALWAYS",
            "customSessionId": session_id
        }
        log.info("connecting to openvidu")
        headers = {
            'Content-type': 'application/json',
            'Connection': 'keep-alive'
        }
        openvidu_session_response = requests.post(
            OPENVIDU_URL + 'sessions',
            headers=headers,
            json=data,
            verify=False,
            auth=HTTPBasicAuth(os.environ['OPENVIDU_USERNAME'],
                               os.environ['OPENVIDU_PASSWORD']))
        if openvidu_session_response.status_code == 409 or openvidu_session_response.status_code == 200:
            token_data = {
                "session": session_id,
                "data": json.dumps(body, separators=(',', ':'))
            }

            openvidu_token_response = requests.post(
                OPENVIDU_URL + 'tokens',
                headers=headers,
                json=token_data,
                verify=False,
                auth=HTTPBasicAuth(os.environ['OPENVIDU_USERNAME'],
                                   os.environ['OPENVIDU_PASSWORD']))
            json_response = openvidu_token_response.json()
            data = json.loads(json_response['data'])
            print(data, "data")
            openvidu_token_response.json()['data'] = data
            response = {
                'id': json_response['id'],
                'sessionId': json_response['session'],
                'role': json_response['role'],
                'data': data,
                'token': json_response['token']
            }

            log.info('{}'.format(openvidu_token_response.__dict__))
            return Response(body=response, status_code=200)

    except Exception as e:
        log.info('exception while calling openvidu {}'.format(e.args))
        return Response(body={
            "message": "unable to create session",
            "code": "open_vidu_issue"
        },
                        status_code=400)