Exemple #1
0
    def get_current_user(self, request: web.RequestHandler) -> dict:
        cookies = dict()
        # Pass through cookies
        for name in request.request.cookies:
            cookies[name] = request.get_cookie(name)

        if "noteable_auth" not in cookies:
            logging.debug(f"No noteable_auth cookie found - got {','.join(request.request.cookies)}")
            return None

        encoded = cookies["noteable_auth"]
        result = jwt.decode(encoded, self.jwt_key, algorithms=["HS256"])

        # TODO this _ to - transformation is unfortunate but the alternatives are also bad
        # Due to changes in the API in aug/sept 2020 the username was transformed for the UI to appear
        # as 1-xyz instead of 1_xyz. This was due to K8S only supporting DNS compatible characters for some reasources
        # which _ isn't. The other nice benefit was to get rid of %2F in places. Unfortunately nbexchange used this
        # same API and its username format was changed at the same time.
        # The username is used in the path to user assignment submissions and is recorded in the nbexchange database
        # and on the NFS filesystem. Changing this back would require these usernames are reformatted from their
        # 1-xyz format back to 1_xyz
        transformed_username = result["username"].replace("_", "-", 1)

        # We need to strip out forward slashes from the username. If not, the created paths will be invalid
        transformed_username = transformed_username.replace("/", "-")

        return {
            "name": transformed_username,
            "full_name": result.get("n_fn", ""),
            "course_id": result["n_cid"],
            "course_title": result["n_cnm"],
            "course_role": result["n_rl"],
            "org_id": result["n_oid"],
            "cust_id": result["n_cust_id"],
        }
Exemple #2
0
def _get_user_identificators(
        request_handler: RequestHandler) -> Dict[str, Any]:
    return {
        f'custom_{key}': request_handler.get_cookie(key)
        for key in _REQUIRED_COOKIE_KEYS
    }
def track_page_view(handler):
    """
    // Track a page view, updates all the cookies and campaign tracker,
    // makes a server side request to Google Analytics and writes the transparent
    // gif byte data to the response.
    """
    time_tup = time.localtime(time.time() + COOKIE_USER_PERSISTENCE)

    # set some useful items in environ:
    x_utmac = handler.request.arguments.get('x_utmac', '')

    domain = handler.request.headers.get('Host', '')

    # Get the referrer from the utmr parameter, this is the referrer to the
    # page that contains the tracking pixel, not the referrer for tracking
    # pixel.
    document_referer = handler.request.arguments.get('utmr', [])
    if not document_referer or document_referer == "0":
        document_referer = "-"
    else:
        document_referer = document_referer[0]
        document_referer = unquote(document_referer)

    document_path = handler.request.arguments.get('utmp', '')
    if document_path:
        document_path = document_path[0]
        document_path = unquote(document_path)

    account = handler.request.arguments.get('utmac', '')
    if account:
        account = account[0]

    user_agent = handler.request.headers.get('User-Agent', '')

    # // Try and get visitor cookie from the request.
    cookie = RequestHandler.get_cookie(handler, COOKIE_NAME)

    guidheader = handler.request.headers.get("X-DCMGUID", '')
    if not guidheader:
        guidheader = handler.request.headers.get("X-UP-SUBNO", '')
    if not guidheader:
        guidheader = handler.request.headers.get("X-JPHONE-UID", '')
    if not guidheader:
        guidheader = handler.request.headers.get("X-EM-UID", '')

    visitor_id = get_visitor_id(guidheader, account, user_agent, cookie)

    # // Always try and add the cookie to the response.
    # cookie = SimpleCookie()
    # cookie[COOKIE_NAME] = visitor_id
    # morsel = cookie[COOKIE_NAME]
    # morsel['expires'] = time.strftime('%a, %d-%b-%Y %H:%M:%S %Z', time_tup)
    # morsel['path'] = COOKIE_PATH
    expires = datetime(*time_tup[0:6])
    RequestHandler.set_cookie(handler, COOKIE_NAME, visitor_id, expires=expires)

    utm_gif_location = "http://www.google-analytics.com/__utm.gif"
    i = handler.request.headers.get("X-Forwarded-For", handler.request.headers.get("X-Real-Ip", None))
    if not i:
        i = handler.request.remote_ip
    i = i.split(",")[0]
    for utmac in [account, x_utmac]:
        if not utmac:
            continue
        # // Construct the gif hit url.
        utm_url = (utm_gif_location + "?" +
                "utmwv=" + VERSION +
                "&utmn=" + get_random_number() +
                "&utmhn=" + quote(domain) +
                "&utmsr=" + handler.request.arguments.get('utmsr', [''])[0] +
                "&utme=" + handler.request.arguments.get('utme', [''])[0] +
                "&utmr=" + quote(document_referer) +
                "&utmp=" + quote(document_path) +
                "&utmac=" + utmac +
                "&utmcc=__utma%3D999.999.999.999.999.1%3B" +
                "&utmvid=" + visitor_id +
                "&utmip=" + get_ip(i) +
                "&utmul=" + handler.request.headers.get("Accept-Language", '-') +
                "&utmcs=" + handler.request.headers.get("Accept-Charset", '-')
        )
        # dbgMsg("utm_url: " + utm_url)
        send_request_to_google_analytics(utm_url, handler)

    # // If the debug parameter is on, add a header to the response that contains
    # // the url that was used to contact Google Analytics.
    # headers = [('Set-Cookie', str(cookie).split(': ')[1])]
    headers = []
    if handler.request.arguments.get('utmdebug', False):
        headers.append(('X-GA-MOBILE-URL', utm_url))

    # Finally write the gif data to the response
    response = write_gif_data()
    response_headers = response['response_headers']
    response_headers.extend(headers)
    return response
def track_page_view(handler):
    """
    // Track a page view, updates all the cookies and campaign tracker,
    // makes a server side request to Google Analytics and writes the transparent
    // gif byte data to the response.
    """
    time_tup = time.localtime(time.time() + COOKIE_USER_PERSISTENCE)

    # set some useful items in environ:
    x_utmac = handler.request.arguments.get('x_utmac', '')

    domain = handler.request.headers.get('Host', '')

    # Get the referrer from the utmr parameter, this is the referrer to the
    # page that contains the tracking pixel, not the referrer for tracking
    # pixel.
    document_referer = handler.request.arguments.get('utmr', [])
    if not document_referer or document_referer == "0":
        document_referer = "-"
    else:
        document_referer = document_referer[0]
        document_referer = unquote(document_referer)

    document_path = handler.request.arguments.get('utmp', '')
    if document_path:
        document_path = document_path[0]
        document_path = unquote(document_path)

    account = handler.request.arguments.get('utmac', '')
    if account:
        account = account[0]

    user_agent = handler.request.headers.get('User-Agent', '')

    # // Try and get visitor cookie from the request.
    cookie = RequestHandler.get_cookie(handler, COOKIE_NAME)

    guidheader = handler.request.headers.get("X-DCMGUID", '')
    if not guidheader:
        guidheader = handler.request.headers.get("X-UP-SUBNO", '')
    if not guidheader:
        guidheader = handler.request.headers.get("X-JPHONE-UID", '')
    if not guidheader:
        guidheader = handler.request.headers.get("X-EM-UID", '')

    visitor_id = get_visitor_id(guidheader, account, user_agent, cookie)

    # // Always try and add the cookie to the response.
    # cookie = SimpleCookie()
    # cookie[COOKIE_NAME] = visitor_id
    # morsel = cookie[COOKIE_NAME]
    # morsel['expires'] = time.strftime('%a, %d-%b-%Y %H:%M:%S %Z', time_tup)
    # morsel['path'] = COOKIE_PATH
    expires = datetime(*time_tup[0:6])
    RequestHandler.set_cookie(handler,
                              COOKIE_NAME,
                              visitor_id,
                              expires=expires)

    utm_gif_location = "http://www.google-analytics.com/__utm.gif"
    i = handler.request.headers.get(
        "X-Forwarded-For", handler.request.headers.get("X-Real-Ip", None))
    if not i:
        i = handler.request.remote_ip
    i = i.split(",")[0]
    for utmac in [account, x_utmac]:
        if not utmac:
            continue
        # // Construct the gif hit url.
        utm_url = (
            utm_gif_location + "?" + "utmwv=" + VERSION + "&utmn=" +
            get_random_number() + "&utmhn=" + quote(domain) + "&utmsr=" +
            handler.request.arguments.get('utmsr', [''])[0] + "&utme=" +
            handler.request.arguments.get('utme', [''])[0] + "&utmr=" +
            quote(document_referer) + "&utmp=" + quote(document_path) +
            "&utmac=" + utmac + "&utmcc=__utma%3D999.999.999.999.999.1%3B" +
            "&utmvid=" + visitor_id + "&utmip=" + get_ip(i) + "&utmul=" +
            handler.request.headers.get("Accept-Language", '-') + "&utmcs=" +
            handler.request.headers.get("Accept-Charset", '-'))
        # dbgMsg("utm_url: " + utm_url)
        send_request_to_google_analytics(utm_url, handler)

    # // If the debug parameter is on, add a header to the response that contains
    # // the url that was used to contact Google Analytics.
    # headers = [('Set-Cookie', str(cookie).split(': ')[1])]
    headers = []
    if handler.request.arguments.get('utmdebug', False):
        headers.append(('X-GA-MOBILE-URL', utm_url))

    # Finally write the gif data to the response
    response = write_gif_data()
    response_headers = response['response_headers']
    response_headers.extend(headers)
    return response
Exemple #5
0
def get_session_user(handler: RequestHandler) -> Optional[User]:
    token = handler.get_cookie("auth")
    if token is None:
        return None
    user = session_storage.get(token)
    return user