Detect ic or local environment from within a canister

I am trying to toggle some functionality within a canister. Basically I want authentication to be on when the canister is deployed to the IC, and off when it isn’t. This is the solution I am using:

#[update]
async fn graphql_mutation_custom(mutation_string: String, variables_json_string: String) -> String {
    if sudograph::ic_cdk::api::id().to_text() == "rrkah-fqaaa-aaaaa-aaaaq-cai" {
        let lastmjs_principal = ic_cdk::export::Principal::from_text("w4mle-jylwh-yxyar-mvozx-mewo2-wftxg-ntcay-ukzec-ag2sy-upbuy-zae").expect("should be able to decode");
    
        if ic_cdk::caller() != lastmjs_principal {
            panic!("Not authorized");
        }
    }

    return graphql_mutation(mutation_string, variables_json_string).await;
}

Basically I am hard-coding the deployed canister id and checking it with ic_cdk::api::id().to_text(). But I can see it being very useful in a variety of other scenarios to be able to check what network the canister is deployed to, perhaps a function such as ic_cdk::api::network_id()

You could use the canister’s initialization arguments to carry that boolean flag.

Not sure about the Rust CDK myself, but in Motoko, you’d author an actor class with an argument, and you could use dfx or another tool (like ic-repl) to give that argument when you deploy.

Using ic-repl, you’d modify this example and pass the boolean in place of the unit value () argument:

1 Like