Skip to content

Instantly share code, notes, and snippets.

@peterpeterparker
Created July 23, 2021 08:22
Show Gist options
  • Save peterpeterparker/c604e0341e585164f574349743b10182 to your computer and use it in GitHub Desktop.
Save peterpeterparker/c604e0341e585164f574349743b10182 to your computer and use it in GitHub Desktop.
Motoko Hello World with permission check
import Hash "mo:base/Hash";
import Principal "mo:base/Principal";
import Text "mo:base/Text";
import Debug "mo:base/Debug";
import Error "mo:base/Error";
// Motoko Playground:
// https://m7sm4-2iaaa-aaaab-qabra-cai.raw.ic0.app/
// Documentation:
// Role based: https://sdk.dfinity.org/docs/developers-guide/tutorials/access-control.html
// Base type: https://sdk.dfinity.org/docs/base-libraries/principal
actor HelloWorld {
type Id = Hash.Hash;
// Stable to maintain value when canister is upgraded.
// Only compatible with primitive type. Otherwise need hooks to copy and restore values.
stable var helloWorld: Text = "";
public shared({ caller }) func set(phrase : Text): async() {
await require_permission( caller );
helloWorld := phrase;
};
private func require_permission(user: Principal) : async () {
// getPrincipalText() value
if (user == Principal.fromText("user-principal")) {
throw Error.reject("test");
};
};
public query func getHash(): async Text {
let textHash = Text.hash(helloWorld);
// Does not output in playground. https://github.com/dfinity/motoko-playground/issues/61
Debug.print(debug_show(textHash));
return helloWorld;
};
public query({ caller }) func getPrincipalText(): async Text {
return Principal.toText(caller);
};
public query({ caller }) func getPrincipalId(): async Id {
return getUserId(caller);
};
private func getUserId(user: Principal) : Id {
return Principal.hash(user);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment