shopify_rust/
auth_wrapper.rs

1use textnonce::TextNonce;
2
3use crate::ShopifyApp;
4
5/// This is an implementation of the `ShopifyApp` struct.
6///
7/// # Examples
8///
9/// use shopify_app::ShopifyApp;
10///
11/// let app = ShopifyApp::new();
12/// let nonce = app.new_nonce();
13/// let auth_uri = app.new_auth_uri("my-shop.myshopify.com", "http://localhost:3000/auth", &nonce);
14
15
16    /// This method generates a new nonce value as a string.
17    ///
18    /// A nonce (number used once) is a random value that is used to protect against replay attacks in authentication systems. This method uses the `TextNonce` type from the `ring` crate to generate a cryptographically secure random value and converts it into a string. The string is then modified by replacing plus signs with hyphens and forward slashes with underscores.
19    ///
20    /// # Examples
21    ///
22    /// use shopify_app::ShopifyApp;
23    ///
24    /// let app = ShopifyApp::new();
25    /// let nonce = app.new_nonce();
26
27    /// This method generates a new authorization URI for the Shopify OAuth authentication flow.
28    ///
29    /// The method takes a shop domain string `&str`, a return URI string `&str`, and a nonce string `&str` as arguments and returns a `String`. The `shop` argument should be the domain of the Shopify shop that the application is being installed on, the `return_uri` argument should be the URI that the user's browser should be redirected to after authentication, and the `nonce` argument should be a nonce value to protect against replay attacks.
30    ///
31    /// The method uses the `api_key` and `scopes` fields of the `credentials` field of the `ShopifyApp` struct, and the `access_mode` field of the struct, to construct the authorization URI using a format string. The URI is then returned.
32    ///
33    /// # Examples
34    ///
35    /// use shopify_app::ShopifyApp;
36    ///
37    /// let app = ShopifyApp::new();
38    /// let nonce = app.new_nonce();
39    /// let auth_uri = app.new_auth_uri("my-shop.myshopify.com", "http://localhost:3000/auth", &nonce);
40
41    impl ShopifyApp {
42        pub fn new_nonce() -> String {
43        TextNonce::new()
44           .into_string()
45           .replace("+", "-")
46           .replace("/", "_")
47    }
48
49    pub fn new_auth_uri(&self, shop: &str, return_uri: &str, nonce: &str) -> String {
50        format!(
51            "https://{shop}/admin/oauth/authorize?client_id={api_key}&scope={scopes}&redirect_uri={redirect_uri}&state={nonce}&grant_options[]={access_mode}",
52            shop = shop,
53            api_key = self.credentials.api_key,
54            scopes=  self.scopes.join(","),
55            redirect_uri = return_uri,
56            nonce = nonce,
57            access_mode = self.access_mode.as_string()
58        )
59    }
60}