Exemplo n.º 1
0
async def authorize(request):
    """ User login (authorization)
    """
    required_fields = ["id", "password"]
    utils.validate_fields(required_fields, request.json)
    password = request.json.get("password")
    hashed_pwd = hashlib.sha256(password.encode("utf-8")).hexdigest()
    auth_info = await auth_query.fetch_info_by_username(request)
    email = auth_info.get("email")
    if auth_info.get("hashed_password") is None:
        if request.app.config.DEMO_MODE:
            token = generate_api_key(
                request.app.config.SECRET_KEY, auth_info.get("user_id")
            )
            return utils.create_authorization_response(
                token,
                {
                    "message": "Authorization (demo mode) successful",
                    "user_id": auth_info.get("user_id"),
                },
            )
        if not email:
            raise ApiUnauthorized(
                "Unauthorized: No password nor email is set on this account"
            )
        # TODO: send email confirmation with password set link
        raise ApiUnauthorized("Unauthorized: No password is set")
    if auth_info.get("hashed_password") != hashed_pwd:
        # TODO: rate limit password attempts
        raise ApiUnauthorized("Unauthorized: Incorrect password")
    token = generate_api_key(request.app.config.SECRET_KEY, auth_info.get("user_id"))
    return utils.create_authorization_response(
        token,
        {"message": "Authorization successful", "user_id": auth_info.get("user_id")},
    )
Exemplo n.º 2
0
def auth_via_ldap(user_map, password, env):
    """Authorize via LDAP credentials to access NEXT."""
    ldap_server = env("LDAP_SERVER")
    if ldap_server:
        server = Server(ldap_server)
        conn = Connection(
            server, user=user_map["remote_id"], password=password, read_only=True
        )
        if not conn.bind():
            ldap_login_msg = re.search(
                "data ([0-9a-fA-F]*), v[0-9a-fA-F]*", conn.result["message"]
            )
            if ldap_login_msg and ldap_login_msg.group(1):
                ldap_err_code = ldap_login_msg.group(1)
                login_error = LDAP_ERR_MESSAGES.get(
                    ldap_err_code, LDAP_ERR_MESSAGES["default"]
                )
            else:
                login_error = LDAP_ERR_MESSAGES["default"]

            raise ApiUnauthorized(login_error)
        conn.unbind()

        token = generate_api_key(env("SECRET_KEY"), user_map["next_id"])
        return utils.create_authorization_response(
            token,
            {"message": "Authorization successful", "next_id": user_map["next_id"]},
        )
    raise ApiBadRequest("Missing LDAP_SERVER env variable.")
Exemplo n.º 3
0
async def auth_via_next(user, password, env):
    """Authorization via NEXT stored credentials to access NEXT"""
    auth_info = await get_auth_by_next_id(user["next_id"])

    # check if a password is set on the account.
    if auth_info["hashed_password"] is None:
        raise ApiUnauthorized("No password is set on this account.")

    salt = auth_info.get("salt")
    hashed_password = auth_info.get("hashed_password")

    # compare the hashes.
    check_password = compare_hash(
        hashed_password,
        hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, 100000).hex(),
    )

    if not check_password:
        raise ApiUnauthorized("Incorrect username or password.")

    token = generate_api_key(env("SECRET_KEY"), user["next_id"])
    return utils.create_authorization_response(
        token,
        {"message": "Authorization successful", "next_id": auth_info.get("next_id")},
    )
Exemplo n.º 4
0
async def authorize(request):
    required_fields = ["id", "password"]
    utils.validate_fields(required_fields, request.json)

    password = request.json.get("password")
    hashed_pwd = hashlib.sha256(password.encode("utf-8")).hexdigest()
    auth_info = await auth_query.fetch_info_by_user_name(
        request.app.config.DB_CONN, request.json.get("id")
    )
    if auth_info is None or auth_info.get("hashed_password") != hashed_pwd:
        raise ApiUnauthorized("Unauthorized: Incorrect user id or password")
    token = generate_api_key(request.app.config.SECRET_KEY, auth_info.get("user_id"))
    return json({"data": {"authorization": token, "user_id": auth_info.get("user_id")}})
Exemplo n.º 5
0
async def auth_via_next(user, password, env):
    """Authorization via NEXT stored credentials to access NEXT"""
    hashed_pwd = hashlib.sha256(password.encode("utf-8")).hexdigest()
    auth_info = await get_auth_by_next_id(user["next_id"])
    if auth_info["hashed_password"] is None:
        raise ApiUnauthorized("No password is set on this account.")
    if auth_info["hashed_password"] != hashed_pwd:
        raise ApiUnauthorized("The password you entered is incorrect.")

    token = generate_api_key(env("SECRET_KEY"), user["next_id"])
    return utils.create_authorization_response(
        token,
        {"message": "Authorization successful", "next_id": auth_info.get("next_id")},
    )
Exemplo n.º 6
0
def create_user_response(request, public_key):
    token = generate_api_key(request.app.config.SECRET_KEY, public_key)
    user_resource = {
        "id": public_key,
        "name": request.json.get("name"),
        "username": request.json.get("username"),
        "email": request.json.get("email"),
        "ownerOf": [],
        "administratorOf": [],
        "memberOf": [],
        "proposals": [],
    }
    if request.json.get("manager"):
        user_resource["manager"] = request.json.get("manager")
    if request.json.get("metadata"):
        user_resource["metadata"] = request.json.get("metadata")
    return json({"data": {"authorization": token, "user": user_resource}})
Exemplo n.º 7
0
def create_user_response(request, user_id):
    token = generate_api_key(request.app.config.SECRET_KEY, user_id)
    user_resource = {
        "id": user_id,
        "name": request.json.get("name"),
        "username": request.json.get("username"),
        "email": request.json.get("email"),
        "ownerOf": [],
        "administratorOf": [],
        "memberOf": [],
        "proposals": [],
    }
    if request.json.get("manager"):
        user_resource["manager"] = request.json.get("manager")
    if request.json.get("metadata"):
        user_resource["metadata"] = request.json.get("metadata")
    return utils.create_authorization_response(token, {
        "message": "Authorization successful",
        "user": user_resource
    })
def ldap_auth_login(user):
    """" Authenticate as a test LDAP user and create a new entry in
    auth RethinkDB table.

    Args:
        user:
            dict: User table entry for imported LDAP user

    Returns:
        token:
            str: Bearer token upon user's successful authentication
    """
    env = Env()
    ldap_conn = Connection(
        SERVER,
        user=user["remote_id"],
        password="******",
        client_strategy=MOCK_SYNC,
    )

    # On successful bind, create auth table entry
    if ldap_conn.bind():
        conn = connect_to_db()
        user_map = (r.table("user_mapping").filter({
            "next_id": user["next_id"]
        }).coerce_to("array").run(conn))
        auth_entry = {
            "next_id": user["next_id"],
            "username": user["username"],
            "email": user["email"],
            "encrypted_private_key": user_map[0]["encrypted_key"],
            "public_key": user_map[0]["public_key"],
        }
        r.table("auth").insert(auth_entry).run(conn)
        conn.close()
        return generate_api_key(env("SECRET_KEY"), user["next_id"])
    return None
Exemplo n.º 9
0
async def authorize(request):
    """ API Endpoint to authenticate and login to the NEXT platform. """
    required_fields = ["id", "password", "auth_source"]
    utils.validate_fields(required_fields, request.json)
    username = request.json.get("id")
    password = request.json.get("password")
    auth_source = request.json.get("auth_source")

    if auth_source == "next":
        hashed_pwd = hashlib.sha256(password.encode("utf-8")).hexdigest()
        auth_info = await auth_query.fetch_info_by_username(request)
        email = auth_info.get("email")
        if auth_info.get("hashed_password") is None:
            if request.app.config.DEMO_MODE:
                token = generate_api_key(
                    request.app.config.SECRET_KEY, auth_info.get("user_id")
                )
                return utils.create_authorization_response(
                    token,
                    {
                        "message": "Authorization (demo mode) successful",
                        "user_id": auth_info.get("user_id"),
                    },
                )
            if not email:
                raise ApiUnauthorized("No password or email is set on this account.")
            # TODO: send email confirmation with password set link
            raise ApiUnauthorized("No password is set on this account.")
        if auth_info.get("hashed_password") != hashed_pwd:
            # TODO: rate limit password attempts
            raise ApiUnauthorized("The password you entered is incorrect.")

        token = generate_api_key(
            request.app.config.SECRET_KEY, auth_info.get("user_id")
        )
        return utils.create_authorization_response(
            token,
            {
                "message": "Authorization successful",
                "user_id": auth_info.get("user_id"),
            },
        )

    if auth_source == "ldap":
        if LDAP_SERVER:
            if username != "" and password != "":
                ldap_user_dn = await auth_query.fetch_dn_by_username(request)
                server = Server(LDAP_SERVER)
                conn = Connection(
                    server, user=ldap_user_dn, password=password, read_only=True
                )

                if not conn.bind():
                    ldap_login_msg = re.search(
                        "data ([0-9a-fA-F]*), v[0-9a-fA-F]*", conn.result["message"]
                    )
                    if ldap_login_msg and ldap_login_msg.group(1):
                        ldap_err_code = ldap_login_msg.group(1)
                        login_error = LDAP_ERR_MESSAGES.get(
                            ldap_err_code, LDAP_ERR_MESSAGES["default"]
                        )
                    else:
                        login_error = LDAP_ERR_MESSAGES["default"]

                    raise ApiUnauthorized(login_error)

                auth_info = await auth_query.fetch_info_by_username(request)
                conn.unbind()

                token = generate_api_key(
                    request.app.config.SECRET_KEY, auth_info.get("user_id")
                )
                return utils.create_authorization_response(
                    token,
                    {
                        "message": "Authorization successful",
                        "user_id": auth_info.get("user_id"),
                    },
                )
            raise ApiBadRequest(LDAP_ERR_MESSAGES["default"])
        raise ApiBadRequest("Missing LDAP_SERVER env variable.")
    raise ApiBadRequest("Invalid authentication source.")