Beispiel #1
0
def get_user_from_api_key(api_key, query_id):
    if not api_key:
        return None

    user = None

    # TODO: once we switch all api key storage into the ApiKey model, this code will be much simplified
    org = current_org._get_current_object()
    try:
        user = models.User.get_by_api_key_and_org(api_key, org)
    except models.NoResultFound:
        try:
            api_key = models.ApiKey.get_by_api_key(api_key)
            user = models.ApiUser(api_key, api_key.org, [])
        except models.NoResultFound:
            if query_id:
                query = models.Query.get_by_id_and_org(query_id, org)
                if query and query.api_key == api_key:
                    user = models.ApiUser(api_key,
                                          query.org,
                                          query.groups.keys(),
                                          name="ApiKey: Query {}".format(
                                              query.id))

    return user
Beispiel #2
0
def jwt_token_load_user_from_request(request):
    org = current_org._get_current_object()

    payload = None

    if org_settings['auth_jwt_auth_cookie_name']:
        jwt_token = request.cookies.get(
            org_settings['auth_jwt_auth_cookie_name'], None)
    elif org_settings['auth_jwt_auth_header_name']:
        jwt_token = request.headers.get(
            org_settings['auth_jwt_auth_header_name'], None)
    else:
        return None

    if jwt_token:
        payload, token_is_valid = jwt_auth.verify_jwt_token(
            jwt_token,
            expected_issuer=org_settings['auth_jwt_auth_issuer'],
            expected_audience=org_settings['auth_jwt_auth_audience'],
            algorithms=org_settings['auth_jwt_auth_algorithms'],
            public_certs_url=org_settings['auth_jwt_auth_public_certs_url'],
        )
        if not token_is_valid:
            raise Unauthorized('Invalid JWT token')

    if not payload:
        return

    try:
        user = models.User.get_by_email_and_org(payload['email'], org)
    except models.NoResultFound:
        user = create_and_login_user(current_org, payload['email'],
                                     payload['email'])

    return user
Beispiel #3
0
def load_user(user_id_with_identity):
    org = current_org._get_current_object()

    '''
    Users who logged in prior to https://github.com/getredash/redash/pull/3174 going live are going
    to have their (integer) user_id as their session user identifier.
    These session user identifiers will be updated the first time they visit any page so we add special
    logic to allow a frictionless transition.
    This logic will be removed 2-4 weeks after going live, and users who haven't
    visited any page during that time will simply have to log in again.
    '''

    is_legacy_session_identifier = str(user_id_with_identity).find('-') < 0

    if is_legacy_session_identifier:
        user_id = user_id_with_identity
    else:
        user_id, _ = user_id_with_identity.split("-")

    try:
        user = models.User.get_by_id_and_org(user_id, org)
        if user.is_disabled:
            return None

        if is_legacy_session_identifier:
            login_user(user, remember=True)
        elif user.get_id() != user_id_with_identity:
            return None

        return user
    except models.NoResultFound:
        return None
Beispiel #4
0
def get_user_from_secret_key(secret_key, signature, request):
    if not all([secret_key, signature]):
        raise Unauthorized("Invalid embed request")

    timestamp = request.args.get("timestamp", None)
    if not timestamp:
        raise Unauthorized("Lost timestamp")

    now = int(time.time())
    timestamp = int(timestamp)
    ttl = int(org_settings["embed_urls_expired_seconds"])
    if (timestamp + ttl <  now) or (timestamp - ttl > now):
        raise Unauthorized("Invalid timestamp")

    user = None
    org = current_org._get_current_object()
    try:
        application = models.Application.get_by_secret_key(secret_key)
    except models.NoResultFound:
        raise Unauthorized("Unknown application")
    else:
        if application.is_active:
            if check_embed_signature(request, application.secret_token, timestamp, signature):
                user = models.ApiUser(application.id, org, [], name="Application: {}".format(application.name))
            else:
                raise Unauthorized("Invalid serect token")
        else:
            raise Unauthorized("Inactive appclication")
    return user
Beispiel #5
0
def jwt_token_load_user_from_request(request):
    org = current_org._get_current_object()

    payload = None

    if org_settings['auth_jwt_auth_cookie_name']:
        jwt_token = request.cookies.get(org_settings['auth_jwt_auth_cookie_name'], None)
    elif org_settings['auth_jwt_auth_header_name']:
        jwt_token = request.headers.get(org_settings['auth_jwt_auth_header_name'], None)
    else:
        return None

    if jwt_token:
        payload, token_is_valid = jwt_auth.verify_jwt_token(
            jwt_token,
            expected_issuer=org_settings['auth_jwt_auth_issuer'],
            expected_audience=org_settings['auth_jwt_auth_audience'],
            algorithms=org_settings['auth_jwt_auth_algorithms'],
            public_certs_url=org_settings['auth_jwt_auth_public_certs_url'],
        )
        if not token_is_valid:
            raise Unauthorized('Invalid JWT token')

    if not payload:
        return

    try:
        user = models.User.get_by_email_and_org(payload['email'], org)
    except models.NoResultFound:
        user = create_and_login_user(current_org, payload['email'], payload['email'])

    return user
Beispiel #6
0
def load_user(user_id_with_identity):
    org = current_org._get_current_object()

    '''
    Users who logged in prior to https://github.com/getredash/redash/pull/3174 going live are going
    to have their (integer) user_id as their session user identifier.
    These session user identifiers will be updated the first time they visit any page so we add special
    logic to allow a frictionless transition.
    This logic will be removed 2-4 weeks after going live, and users who haven't
    visited any page during that time will simply have to log in again.
    '''

    is_legacy_session_identifier = str(user_id_with_identity).find('-') < 0

    if is_legacy_session_identifier:
        user_id = user_id_with_identity
    else:
        user_id, _ = user_id_with_identity.split("-")

    try:
        user = models.User.get_by_id_and_org(user_id, org)
        if user.is_disabled:
            return None

        if is_legacy_session_identifier:
            login_user(user, remember=True)
        elif user.get_id() != user_id_with_identity:
            return None

        return user
    except models.NoResultFound:
        return None
Beispiel #7
0
def load_user(user_id):
    org = current_org._get_current_object()
    try:
        user = models.User.get_by_id_and_org(user_id, org)
        if user.is_disabled:
            return None
        return user
    except models.NoResultFound:
        return None
Beispiel #8
0
def load_user(user_id):
    org = current_org._get_current_object()
    try:
        user = models.User.get_by_id_and_org(user_id, org)
        if user.is_disabled:
            return None
        return user
    except models.NoResultFound:
        return None
Beispiel #9
0
def get_user_from_access_token(access_token):
    user = None
    org = current_org._get_current_object()
    try:
        token = models.AccessToken(access_token)
        if token.is_valid:
            user = models.ApiUser(access_token, org, [], name="AccessToken: {}".format(access_token), embed=True)
        else:
            raise Unauthorized("Invalid access token, Please refresh this page again.")
    except:
        raise Unauthorized("Invalid access token, Please refresh this page again.")
    return user
Beispiel #10
0
def load_user(user_id_with_identity):
    org = current_org._get_current_object()

    try:
        user_id, _ = user_id_with_identity.split("-")
        user = models.User.get_by_id_and_org(user_id, org)
        if user.is_disabled or user.get_id() != user_id_with_identity:
            return None

        return user
    except (models.NoResultFound, ValueError, AttributeError):
        return None
Beispiel #11
0
def check_remote_groups():
    """Check if there is a header of user groups and if yes
    check it against a list of allowed user groups from the settings"""
    # Quick shortcut out if remote user auth or remote groups aren't enabled
    if (
        not settings.REMOTE_USER_LOGIN_ENABLED
        or not extension_settings.REMOTE_GROUPS_ENABLED
    ):
        return

    # Generate the URL to the remote auth login endpoint
    if settings.MULTI_ORG:
        org = current_org._get_current_object()
        remote_auth_path = url_for("remote_user_auth.login", org_slug=org.slug)
    else:
        remote_auth_path = url_for("remote_user_auth.login")

    # Then only act if the request is for the remote user auth view
    if request.path.startswith(remote_auth_path):
        remote_groups = settings.set_from_string(
            request.headers.get(extension_settings.REMOTE_GROUPS_HEADER) or ""
        )
        # Finally check if the remote groups found in the request header
        # intersect with the allowed remote groups
        if not extension_settings.REMOTE_GROUPS_ALLOWED.intersection(remote_groups):
            logger.error(
                "User groups provided in the %s header are not "
                "matching the allowed groups.",
                extension_settings.REMOTE_GROUPS_HEADER,
            )
            # Otherwise redirect back to the frontpage
            unsafe_next_path = request.args.get("next")
            next_path = get_next_path(unsafe_next_path)
            if settings.MULTI_ORG:
                org = current_org._get_current_object()
                index_url = url_for("redash.index", org_slug=org.slug, next=next_path)
            else:
                index_url = url_for("redash.index", next=next_path)
            return redirect(index_url)
Beispiel #12
0
def get_user_from_api_key(api_key, query_id):
    if not api_key:
        return None

    user = None

    # TODO: once we switch all api key storage into the ApiKey model, this code will be much simplified
    org = current_org._get_current_object()
    try:
        user = models.User.get_by_api_key_and_org(api_key, org)
    except models.NoResultFound:
        try:
            api_key = models.ApiKey.get_by_api_key(api_key)
            user = models.ApiUser(api_key, api_key.org, [])
        except models.NoResultFound:
            if query_id:
                query = models.Query.get_by_id_and_org(query_id, org)
                if query and query.api_key == api_key:
                    user = models.ApiUser(api_key, query.org, query.groups.keys(), name="ApiKey: Query {}".format(query.id))

    return user
Beispiel #13
0
def load_user(user_id):
    org = current_org._get_current_object()
    try:
        return models.User.get_by_id_and_org(user_id, org)
    except models.NoResultFound:
        return None
Beispiel #14
0
def load_user(user_id):
    org = current_org._get_current_object()
    try:
        return models.User.get_by_id_and_org(user_id, org)
    except models.NoResultFound:
        return None
Beispiel #15
0
 def current_org(self):
     return current_org._get_current_object()
Beispiel #16
0
 def current_org(self):
     return current_org._get_current_object()