Exemplo n.º 1
0
async def read_item(item_id: Optional[str] = Cookie(None)
                    ):  #declare Cookie params, first = default
    return {"item_id": item_id}
Exemplo n.º 2
0
async def serve_page(
    request: Request,
    course_name: constr(max_length=512),  # type: ignore
    pagepath: constr(max_length=512),  # type: ignore
    RS_info: Optional[str] = Cookie(None),
    mode: Optional[str] = None,
):
    if mode and mode == "browsing":
        use_services = False
        user = None
    else:
        use_services = True
        user = request.state.user
        rslogger.debug(f"user = {user}, course name = {course_name}")
    # Make sure this course exists, and look up its base course.
    # Since these values are going to be read by javascript we
    # need to use lowercase true and false.
    if user:
        logged_in = "true"
        user_is_instructor = await is_instructor(request)
        serve_ad = False
    else:
        logged_in = "false"
        activity_info = {}
        user_is_instructor = False
        serve_ad = True

    course_row = await fetch_course(course_name)
    # check for some error conditions
    if not course_row:
        raise HTTPException(status_code=404,
                            detail=f"Course {course_name} not found")
    else:
        # The course requires a login but the user is not logged in
        if course_row.login_required and not user:
            rslogger.debug(
                f"User not logged in: {course_name} redirect to login")
            return RedirectResponse(url="/runestone/default/accessIssue")

        # The user is logged in, but their "current course" is not this one.
        # Send them to the courses page so they can properly switch courses.
        if user and user.course_name != course_name:
            user_course_row = await fetch_course(user.course_name)
            rslogger.debug(
                f"Course mismatch: course name: {user.course_name} does not match requested course: {course_name} redirecting"
            )
            if user_course_row.base_course == course_name:
                return RedirectResponse(
                    url=f"/ns/books/published/{user.course_name}/{pagepath}")
            return RedirectResponse(
                url=
                f"/runestone/default/courses?requested_course={course_name}&current_course={user.course_name}"
            )

    rslogger.debug(f"Base course = {course_row.base_course}")
    chapter = os.path.split(os.path.split(pagepath)[0])[1]
    subchapter = os.path.basename(os.path.splitext(pagepath)[0])
    if user:
        activity_info = await fetch_page_activity_counts(
            chapter, subchapter, course_row.base_course, course_name,
            user.username)

    # The template path comes from the base course's name.
    templates = Jinja2Templates(directory=safe_join(
        settings.book_path,
        course_row.base_course,
        "published",
        course_row.base_course,
    ))
    course_attrs = await fetch_all_course_attributes(course_row.id)
    rslogger.debug(f"HEY COURSE ATTRS: {course_attrs}")
    # TODO set custom delimiters for PreTeXt books (https://stackoverflow.com/questions/33775085/is-it-possible-to-change-the-default-double-curly-braces-delimiter-in-polymer)
    # Books built with lots of LaTeX math in them are troublesome as they tend to have many instances
    # of ``{{`` and ``}}`` which conflicts with the default Jinja2 start stop delimiters. Rather than
    # escaping all of the latex math the PreTeXt built books use different delimiters for the templates
    # templates.env is a reference to a Jinja2 Environment object
    # try - templates.env.block_start_string = "@@@+"
    # try - templates.env.block_end_string = "@@@-"

    if course_attrs.get("markup_system", "RST") == "PreTeXt":
        rslogger.debug(f"PRETEXT book found at path {pagepath}")
        templates.env.variable_start_string = "~._"
        templates.env.variable_end_string = "_.~"
        templates.env.comment_start_string = "@@#"
        templates.env.comment_end_string = "#@@"
        templates.env.globals.update({"URL": URL})

    # enable compare me can be set per course if its not set provide a default of true
    if "enable_compare_me" not in course_attrs:
        course_attrs["enable_compare_me"] = "true"

    reading_list = []
    if RS_info:
        values = json.loads(RS_info)
        if "readings" in values:
            reading_list = values["readings"]

    #   TODO: provide the template google_ga as well as ad servings stuff
    #   settings.google_ga
    await create_useinfo_entry(
        UseinfoValidation(
            event="page",
            act="view",
            div_id=pagepath,
            course_id=course_name,
            sid=user.username if user else "Anonymous",
            timestamp=datetime.utcnow(),
        ))
    subchapter_list = await fetch_subchaptoc(course_row.base_course, chapter)
    # TODO: restore the contributed questions list ``questions`` for books (only fopp) that
    # show the contributed questions list on an Exercises page.
    context = dict(
        request=request,
        course_name=course_name,
        base_course=course_row.base_course,
        user_id=user.username if user else "",
        # _`root_path`: The server is mounted in a different location depending on how it's run (directly from gunicorn/uvicorn or under the ``/ns`` prefix using nginx). Tell the JS what prefix to use for Ajax requests. See also `setting root_path <setting root_path>` and the `FastAPI docs <https://fastapi.tiangolo.com/advanced/behind-a-proxy/>`_. This is then used in the ``eBookConfig`` of :doc:`runestone/common/project_template/_templates/plugin_layouts/sphinx_bootstrap/layout.html`.
        new_server_prefix=request.scope.get("root_path"),
        user_email=user.email if user else "",
        downloads_enabled="true" if course_row.downloads_enabled else "false",
        allow_pairs="true" if course_row.allow_pairs else "false",
        activity_info=json.dumps(activity_info),
        settings=settings,
        is_logged_in=logged_in,
        subchapter_list=subchapter_list,
        serve_ad=serve_ad,
        is_instructor="true" if user_is_instructor else "false",
        use_services="true" if use_services else "false",
        readings=reading_list,
        **course_attrs,
    )
    # See `templates <https://fastapi.tiangolo.com/advanced/templates/>`_.
    try:
        return templates.TemplateResponse(pagepath, context)
    except TemplateNotFound:
        raise HTTPException(
            status_code=404,
            detail=
            f"Page {pagepath} not found in base course {course_row.base_course}.",
        )
Exemplo n.º 3
0
 def cookies(token: str = Cookie(None)):
     return {"token": token}
Exemplo n.º 4
0
def process_cookie(response: Response, cookie: Optional[str] = Cookie(None)):
	if cookie is None:
		cookie = str(uuid.uuid4())
		response.set_cookie(key="cookie", value=cookie, max_age=315576000)
Exemplo n.º 5
0
async def get_cookie_or_client(websocket: WebSocket,
                               session: str = Cookie(None),
                               x_client: str = Header(None)):
    if session is None and x_client is None:
        await websocket.close(code=status.WS_1008_POLICY_VIOLATION)
    return session or x_client
Exemplo n.º 6
0
async def read_items(ads_id: Optional[str] = Cookie(None)):
    return {"ads_id": ads_id}
Exemplo n.º 7
0
def get_welcome_session(session_token: str = Cookie(None), format: str = ""):
    print(homework3.saved_cookies)
    if session_token not in homework3.saved_cookies:
        raise HTTPException(status_code=401)
    return get_response_by_format(format)
Exemplo n.º 8
0
def welcome_session(request: Request, format: Optional[str] = None, session_token: str = Cookie(None)):
	log_request(request)
	return welcome(app.cookie_tokens, session_token, format)
Exemplo n.º 9
0
def delete_patient(pk: int, response: Response, cookie: str = Cookie(None)):
    if cookie not in app.sessions:
        raise HTTPException(status_code=401, detail="Unathorised")
    patients.pop(pk)
    response.status_code = status.HTTP_204_NO_CONTENT
def user_must_be_logged_CHECK(session_token: str = Depends(Cookie())):
    print(session_token)
Exemplo n.º 11
0
def logout_session(request: Request, response: Response, format: Optional[str] = "plain", session_token: str = Cookie(None)):
	log_request(request)	
	return logout(app.cookie_tokens, session_token, format)
Exemplo n.º 12
0
async def get_current_user_from_cookie(token: Optional[str] = Cookie(None)):
    if token is None:
        raise HTTPException(status_code=401, detail=f"Token cookie is missing")
    return await _get_current_user_from_token(token)
Exemplo n.º 13
0
def welcome_session(response: Response,
                    format: Optional[str] = None,
                    session_token: str = Cookie(None)):
    response.status_code = 401
    if session_token in app.session_tokens:
        return return_message(text="Welcome!", message_format=format)
async def hidden_cookie(
    hidden_cookie: Optional[str] = Cookie(None, include_in_schema=False)
):
    return {"hidden_cookie": hidden_cookie}
Exemplo n.º 15
0
def logout(response: Response, session_token: str = Cookie(None)):
	if session_token not in app.session_tokens:
		response.status_code = status.HTTP_401_UNAUTHORIZED
		return MESSAGE_UNAUTHORIZED
	response.headers["Location"] = "/"
Exemplo n.º 16
0
def logout(response: Response, cookie: str = Cookie(None)):
    if cookie not in app.sessions:
        return RedirectResponse(url='/')
    response.delete_cookie(key='cookie')
    app.sessions.clear()
    return RedirectResponse(url='/')
Exemplo n.º 17
0
def get_user_if_logged(auth_token: Optional[str] = Cookie(
    None, alias=config.auth_token_name)) -> Optional[UserOut]:
    return get_user_from_token(auth_token) if auth_token is not None else None
Exemplo n.º 18
0
def read_item(name: str, cookie: str = Cookie(None)):
    if cookie not in app.sessions:
        raise HTTPException(status_code=403, detail="Unathorised")
    return HelloResp(msg=f"Hello {name}")
Exemplo n.º 19
0
def cookie(cookie_id: Optional[str] = Cookie(default=None)):
    return {'cookie_id': cookie_id}
Exemplo n.º 20
0
def check_cookie(session_token: str = Cookie(None)):
    if session_token not in app.ses:
        session_token = None
    else:
        return session_token
Exemplo n.º 21
0
def query_or_cookie_extractor(
  q: str = Depends(query_extractor), last_query: Optional[str] = Cookie(None)
):
  if not q:
    return last_query
  return q
Exemplo n.º 22
0
def read_items(*, ads_id: str = Cookie(None)):
    return {"ads_id": ads_id}
Exemplo n.º 23
0
def verify_cookie(session_token: str = Cookie(None)):
    if session_token not in app.sessions:
        session_token = None
    return session_token
Exemplo n.º 24
0
def secured_data(*, response: Response, session_token: str = Cookie(None)):
    if session_token not in router.access_tokens:
        raise HTTPException(status_code=403, detail="Unauthorised")
    else:
        return {"message": "Secure content!!!"}
Exemplo n.º 25
0
async def read_items(ads_id: Union[str, None] = Cookie(default=None)):
    return {"ads_id": ads_id}
Exemplo n.º 26
0
async def index(request : Request, spotify_user_id : Optional[str] = Cookie(None)):
    print('spotify_user_id:', spotify_user_id)
    if spotify_user_id is None:
        return RedirectResponse(url=OAUTH2.url)
    return templates.TemplateResponse("index.html",{"request" : request})
Exemplo n.º 27
0
def get_text_preprocessing_task_progress(user_uuid: str = Cookie(None)):
    global topic_model_training_tasks

    if (not user_uuid) or (user_uuid not in topic_model_training_tasks):
        raise HTTPException(status_code=404, detail="未找到相应的训练对象!")
    return topic_model_training_tasks[user_uuid].text_preprocessing_progress
Exemplo n.º 28
0
async def read_items(
    *, session_id: str = Cookie(None)):  # Try adding alias="session-id"
    return {"session_id": session_id}
Exemplo n.º 29
0
async def read_items(ads_id=Cookie('test')):
    return {"ads_id": ads_id}
Exemplo n.º 30
0
def get_profile(user_id: int, db: Session = Depends(get_db), token: Optional[str] = Cookie(None)):
	ret = get_user(db, user_id)
	if ret:
		return ProfileResponse(data = ret, success = True, error = False)
	else:
		return ErrorResponse(msg = "Error while getting data")