@canva/cli 0.0.1-beta.2 → 0.0.1-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +177 -109
- package/cli.js +267 -267
- package/package.json +1 -1
- package/templates/base/backend/routers/oauth.ts +393 -0
- package/templates/base/eslint.config.mjs +0 -2
- package/templates/base/package.json +22 -19
- package/templates/base/utils/backend/bearer_middleware/bearer_middleware.ts +101 -0
- package/templates/base/utils/backend/bearer_middleware/index.ts +1 -0
- package/templates/base/utils/backend/bearer_middleware/tests/bearer_middleware.tests.ts +192 -0
- package/templates/base/utils/use_add_element.ts +48 -0
- package/templates/base/utils/use_feature_support.ts +28 -0
- package/templates/common/.gitignore.template +5 -6
- package/templates/common/README.md +4 -74
- package/templates/common/conf/eslint-general.mjs +26 -0
- package/templates/common/conf/eslint-i18n.mjs +18 -3
- package/templates/dam/backend/server.ts +0 -7
- package/templates/dam/package.json +27 -27
- package/templates/dam/src/app.tsx +2 -135
- package/templates/gen_ai/README.md +1 -1
- package/templates/gen_ai/backend/routers/image.ts +3 -3
- package/templates/gen_ai/backend/server.ts +0 -7
- package/templates/gen_ai/eslint.config.mjs +0 -2
- package/templates/gen_ai/package.json +28 -28
- package/templates/gen_ai/src/api/api.ts +1 -39
- package/templates/gen_ai/src/components/footer.messages.ts +0 -5
- package/templates/gen_ai/src/components/footer.tsx +2 -16
- package/templates/gen_ai/src/components/image_grid.tsx +8 -6
- package/templates/gen_ai/src/components/index.ts +0 -1
- package/templates/gen_ai/src/context/app_context.tsx +4 -26
- package/templates/gen_ai/src/context/context.messages.ts +1 -12
- package/templates/gen_ai/utils/backend/bearer_middleware/bearer_middleware.ts +101 -0
- package/templates/gen_ai/utils/backend/bearer_middleware/index.ts +1 -0
- package/templates/gen_ai/utils/backend/bearer_middleware/tests/bearer_middleware.tests.ts +192 -0
- package/templates/hello_world/eslint.config.mjs +0 -2
- package/templates/hello_world/package.json +20 -19
- package/templates/hello_world/src/app.tsx +4 -2
- package/templates/hello_world/utils/use_add_element.ts +48 -0
- package/templates/hello_world/utils/use_feature_support.ts +28 -0
- package/templates/dam/backend/database/database.ts +0 -42
- package/templates/dam/backend/routers/auth.ts +0 -285
- package/templates/gen_ai/backend/routers/auth.ts +0 -285
- package/templates/gen_ai/src/components/logged_in_status.tsx +0 -44
- package/templates/gen_ai/src/services/auth.tsx +0 -31
- package/templates/gen_ai/src/services/index.ts +0 -1
- package/templates/gen_ai/utils/backend/jwt_middleware/index.ts +0 -1
- package/templates/gen_ai/utils/backend/jwt_middleware/jwt_middleware.ts +0 -229
- package/templates/gen_ai/utils/backend/jwt_middleware/tests/jwt_middleware.tests.ts +0 -630
|
@@ -1,285 +0,0 @@
|
|
|
1
|
-
import * as chalk from "chalk";
|
|
2
|
-
import * as crypto from "crypto";
|
|
3
|
-
import "dotenv/config";
|
|
4
|
-
import * as express from "express";
|
|
5
|
-
import * as cookieParser from "cookie-parser";
|
|
6
|
-
import * as basicAuth from "express-basic-auth";
|
|
7
|
-
import { JSONFileDatabase } from "../database/database";
|
|
8
|
-
import { getTokenFromQueryString } from "../../utils/backend/jwt_middleware/jwt_middleware";
|
|
9
|
-
import { createJwtMiddleware } from "../../utils/backend/jwt_middleware";
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* These are the hard-coded credentials for logging in to this template.
|
|
13
|
-
*/
|
|
14
|
-
const USERNAME = "username";
|
|
15
|
-
const PASSWORD = "password";
|
|
16
|
-
|
|
17
|
-
const COOKIE_EXPIRY_MS = 5 * 60 * 1000; // 5 minutes
|
|
18
|
-
|
|
19
|
-
const CANVA_BASE_URL = "https://canva.com";
|
|
20
|
-
|
|
21
|
-
interface Data {
|
|
22
|
-
users: string[];
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
* For more information on Authentication, refer to our documentation: {@link https://www.canva.dev/docs/apps/authenticating-users/#types-of-authentication}.
|
|
27
|
-
*/
|
|
28
|
-
export const createAuthRouter = () => {
|
|
29
|
-
const APP_ID = getAppId();
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* Set up a database with a "users" table. In this example code, the
|
|
33
|
-
* database is simply a JSON file.
|
|
34
|
-
*/
|
|
35
|
-
const db = new JSONFileDatabase<Data>({ users: [] });
|
|
36
|
-
|
|
37
|
-
const router = express.Router();
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
* The `cookieParser` middleware allows the routes to read and write cookies.
|
|
41
|
-
*
|
|
42
|
-
* By passing a value into the middleware, we enable the "signed cookies" feature of Express.js. The
|
|
43
|
-
* value should be static and cryptographically generated. If it's dynamic (as shown below), cookies
|
|
44
|
-
* won't persist between server restarts.
|
|
45
|
-
*
|
|
46
|
-
* TODO: Replace `crypto.randomUUID()` with a static value, loaded via an environment variable.
|
|
47
|
-
*/
|
|
48
|
-
router.use(cookieParser(crypto.randomUUID()));
|
|
49
|
-
|
|
50
|
-
/**
|
|
51
|
-
* This endpoint is hit at the start of the authentication flow. It contains a state which must
|
|
52
|
-
* be passed back to canva so that Canva can verify the response. It must also set a nonce in the
|
|
53
|
-
* user's browser cookies and send the nonce back to Canva as a url parameter.
|
|
54
|
-
*
|
|
55
|
-
* If Canva can validate the state, it will then redirect back to the chosen redirect url.
|
|
56
|
-
*/
|
|
57
|
-
router.get("/configuration/start", async (req, res) => {
|
|
58
|
-
/**
|
|
59
|
-
* Generate a unique nonce for each request. A nonce is a random, single-use value
|
|
60
|
-
* that's impossible to guess or enumerate. We recommended using a Version 4 UUID that
|
|
61
|
-
* is cryptographically secure, such as one generated by the `randomUUID` method.
|
|
62
|
-
*/
|
|
63
|
-
const nonce = crypto.randomUUID();
|
|
64
|
-
// Set the expiry time for the nonce. We recommend 5 minutes.
|
|
65
|
-
const expiry = Date.now() + COOKIE_EXPIRY_MS;
|
|
66
|
-
|
|
67
|
-
// Create a JSON string that contains the nonce and an expiry time
|
|
68
|
-
const nonceWithExpiry = JSON.stringify([nonce, expiry]);
|
|
69
|
-
|
|
70
|
-
// Set a cookie that contains the nonce and the expiry time
|
|
71
|
-
res.cookie("nonce", nonceWithExpiry, {
|
|
72
|
-
secure: true,
|
|
73
|
-
httpOnly: true,
|
|
74
|
-
maxAge: COOKIE_EXPIRY_MS,
|
|
75
|
-
signed: true,
|
|
76
|
-
});
|
|
77
|
-
|
|
78
|
-
// Create the query parameters that Canva requires
|
|
79
|
-
const params = new URLSearchParams({
|
|
80
|
-
nonce,
|
|
81
|
-
state: req?.query?.state?.toString() || "",
|
|
82
|
-
});
|
|
83
|
-
|
|
84
|
-
// Redirect to Canva with required parameters
|
|
85
|
-
res.redirect(302, `${CANVA_BASE_URL}/apps/configure/link?${params}`);
|
|
86
|
-
});
|
|
87
|
-
|
|
88
|
-
/**
|
|
89
|
-
* This endpoint renders a login page. Once the user logs in, they're
|
|
90
|
-
* redirected back to Canva, which completes the authentication flow.
|
|
91
|
-
*/
|
|
92
|
-
router.get(
|
|
93
|
-
"/redirect-url",
|
|
94
|
-
/**
|
|
95
|
-
* Use a JSON Web Token (JWT) to verify incoming requests. The JWT is
|
|
96
|
-
* extracted from the `canva_user_token` parameter.
|
|
97
|
-
*/
|
|
98
|
-
createJwtMiddleware(APP_ID, getTokenFromQueryString),
|
|
99
|
-
/**
|
|
100
|
-
* Warning: For demonstration purposes, we're using basic authentication and
|
|
101
|
-
* hard- coding a username and password. This is not a production-ready
|
|
102
|
-
* solution!
|
|
103
|
-
*/
|
|
104
|
-
basicAuth({
|
|
105
|
-
users: { [USERNAME]: PASSWORD },
|
|
106
|
-
challenge: true,
|
|
107
|
-
}),
|
|
108
|
-
async (req, res) => {
|
|
109
|
-
const failureResponse = () => {
|
|
110
|
-
const params = new URLSearchParams({
|
|
111
|
-
success: "false",
|
|
112
|
-
state: req.query.state?.toString() || "",
|
|
113
|
-
});
|
|
114
|
-
res.redirect(302, `${CANVA_BASE_URL}/apps/configured?${params}`);
|
|
115
|
-
};
|
|
116
|
-
|
|
117
|
-
// Get the nonce and expiry time stored in the cookie.
|
|
118
|
-
const cookieNonceAndExpiry = req.signedCookies.nonce;
|
|
119
|
-
|
|
120
|
-
// Get the nonce from the query parameter.
|
|
121
|
-
const queryNonce = req.query.nonce?.toString();
|
|
122
|
-
|
|
123
|
-
// After reading the cookie, clear it. This forces abandoned auth flows to be restarted.
|
|
124
|
-
res.clearCookie("nonce");
|
|
125
|
-
|
|
126
|
-
let cookieNonce = "";
|
|
127
|
-
let expiry = 0;
|
|
128
|
-
|
|
129
|
-
try {
|
|
130
|
-
[cookieNonce, expiry] = JSON.parse(cookieNonceAndExpiry);
|
|
131
|
-
} catch {
|
|
132
|
-
// If the nonce can't be parsed, assume something has been compromised and exit.
|
|
133
|
-
return failureResponse();
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
// If the nonces are empty, exit the authentication flow.
|
|
137
|
-
if (
|
|
138
|
-
isEmpty(cookieNonceAndExpiry) ||
|
|
139
|
-
isEmpty(queryNonce) ||
|
|
140
|
-
isEmpty(cookieNonce)
|
|
141
|
-
) {
|
|
142
|
-
return failureResponse();
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
/**
|
|
146
|
-
* Check that:
|
|
147
|
-
*
|
|
148
|
-
* - The nonce in the cookie and query parameter contain the same value
|
|
149
|
-
* - The nonce has not expired
|
|
150
|
-
*
|
|
151
|
-
* **Note:** We could rely on the cookie expiry, but that is vulnerable to tampering
|
|
152
|
-
* with the browser's time. This allows us to double-check based on server time.
|
|
153
|
-
*/
|
|
154
|
-
if (expiry < Date.now() || cookieNonce !== queryNonce) {
|
|
155
|
-
return failureResponse();
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
// Get the userId from JWT middleware
|
|
159
|
-
const { userId } = req.canva;
|
|
160
|
-
|
|
161
|
-
// Load the database
|
|
162
|
-
const data = await db.read();
|
|
163
|
-
|
|
164
|
-
// Add the user to the database
|
|
165
|
-
if (!data.users.includes(userId)) {
|
|
166
|
-
data.users.push(userId);
|
|
167
|
-
await db.write(data);
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
// Create query parameters for redirecting back to Canva
|
|
171
|
-
const params = new URLSearchParams({
|
|
172
|
-
success: "true",
|
|
173
|
-
state: req?.query?.state?.toString() || "",
|
|
174
|
-
});
|
|
175
|
-
|
|
176
|
-
// Redirect the user back to Canva
|
|
177
|
-
res.redirect(302, `${CANVA_BASE_URL}/apps/configured?${params}`);
|
|
178
|
-
},
|
|
179
|
-
);
|
|
180
|
-
|
|
181
|
-
/**
|
|
182
|
-
* TODO: Add this middleware to all routes that will receive requests from
|
|
183
|
-
* your app.
|
|
184
|
-
*/
|
|
185
|
-
const jwtMiddleware = createJwtMiddleware(APP_ID);
|
|
186
|
-
|
|
187
|
-
/**
|
|
188
|
-
* This endpoint is called when a user disconnects an app from their account.
|
|
189
|
-
* The app is expected to de-authenticate the user on its backend, so if the
|
|
190
|
-
* user reconnects the app, they'll need to re-authenticate.
|
|
191
|
-
*
|
|
192
|
-
* Note: The name of the endpoint is *not* configurable.
|
|
193
|
-
*
|
|
194
|
-
* Note: This endpoint is called by Canva's backend directly and must be
|
|
195
|
-
* exposed via a public URL. To test this endpoint, add a proxy URL, such as
|
|
196
|
-
* one generated by nGrok, to the 'Add authentication' section in the
|
|
197
|
-
* Developer Portal. Localhost addresses will not work to test this endpoint.
|
|
198
|
-
*/
|
|
199
|
-
router.post("/configuration/delete", jwtMiddleware, async (req, res) => {
|
|
200
|
-
// Get the userId from JWT middleware
|
|
201
|
-
const { userId } = req.canva;
|
|
202
|
-
|
|
203
|
-
// Load the database
|
|
204
|
-
const data = await db.read();
|
|
205
|
-
|
|
206
|
-
// Remove the user from the database
|
|
207
|
-
await db.write({
|
|
208
|
-
users: data.users.filter((user) => user !== userId),
|
|
209
|
-
});
|
|
210
|
-
|
|
211
|
-
// Confirm that the user was removed
|
|
212
|
-
res.send({
|
|
213
|
-
type: "SUCCESS",
|
|
214
|
-
});
|
|
215
|
-
});
|
|
216
|
-
|
|
217
|
-
/**
|
|
218
|
-
* All routes that start with /api will be protected by JWT authentication
|
|
219
|
-
*/
|
|
220
|
-
router.use("/api", jwtMiddleware);
|
|
221
|
-
|
|
222
|
-
/**
|
|
223
|
-
* This endpoint checks if a user is authenticated.
|
|
224
|
-
*/
|
|
225
|
-
router.post("/api/authentication/status", async (req, res) => {
|
|
226
|
-
// Load the database
|
|
227
|
-
const data = await db.read();
|
|
228
|
-
|
|
229
|
-
// Check if the user is authenticated
|
|
230
|
-
const isAuthenticated = data.users.includes(req.canva.userId);
|
|
231
|
-
|
|
232
|
-
// Return the authentication status
|
|
233
|
-
res.send({
|
|
234
|
-
isAuthenticated,
|
|
235
|
-
});
|
|
236
|
-
});
|
|
237
|
-
|
|
238
|
-
return router;
|
|
239
|
-
};
|
|
240
|
-
|
|
241
|
-
/**
|
|
242
|
-
* Checks if a given param is nullish or an empty string
|
|
243
|
-
*
|
|
244
|
-
* @param str The string to check
|
|
245
|
-
* @returns true if the string is nullish or empty, false otherwise
|
|
246
|
-
*/
|
|
247
|
-
function isEmpty(str?: string): boolean {
|
|
248
|
-
return str == null || str.length === 0;
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
/**
|
|
252
|
-
* Retrieves the CANVA_APP_ID from the environment variables.
|
|
253
|
-
* Throws an error if the CANVA_APP_ID environment variable is undefined or set to a default value.
|
|
254
|
-
*
|
|
255
|
-
* @returns {string} The Canva App ID
|
|
256
|
-
* @throws {Error} If CANVA_APP_ID environment variable is undefined or set to a default value
|
|
257
|
-
*/
|
|
258
|
-
function getAppId(): string {
|
|
259
|
-
// TODO: Set the CANVA_APP_ID environment variable in the project's .env file
|
|
260
|
-
const appId = process.env.CANVA_APP_ID;
|
|
261
|
-
|
|
262
|
-
if (!appId) {
|
|
263
|
-
throw new Error(
|
|
264
|
-
`The CANVA_APP_ID environment variable is undefined. Set the variable in the project's .env file.`,
|
|
265
|
-
);
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
if (appId === "YOUR_APP_ID_HERE") {
|
|
269
|
-
// eslint-disable-next-line no-console
|
|
270
|
-
console.log(
|
|
271
|
-
chalk.bgRedBright(
|
|
272
|
-
"Default 'CANVA_APP_ID' environment variable detected.",
|
|
273
|
-
),
|
|
274
|
-
);
|
|
275
|
-
// eslint-disable-next-line no-console
|
|
276
|
-
console.log(
|
|
277
|
-
"Please update the 'CANVA_APP_ID' environment variable in your project's `.env` file " +
|
|
278
|
-
`with the App ID obtained from the Canva Developer Portal: ${chalk.greenBright(
|
|
279
|
-
"https://www.canva.com/developers/apps",
|
|
280
|
-
)}\n`,
|
|
281
|
-
);
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
return appId;
|
|
285
|
-
}
|
|
@@ -1,285 +0,0 @@
|
|
|
1
|
-
import * as chalk from "chalk";
|
|
2
|
-
import * as crypto from "crypto";
|
|
3
|
-
import "dotenv/config";
|
|
4
|
-
import * as express from "express";
|
|
5
|
-
import * as cookieParser from "cookie-parser";
|
|
6
|
-
import * as basicAuth from "express-basic-auth";
|
|
7
|
-
import { JSONFileDatabase } from "../database/database";
|
|
8
|
-
import { getTokenFromQueryString } from "../../utils/backend/jwt_middleware/jwt_middleware";
|
|
9
|
-
import { createJwtMiddleware } from "../../utils/backend/jwt_middleware";
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* These are the hard-coded credentials for logging in to this template.
|
|
13
|
-
*/
|
|
14
|
-
const USERNAME = "username";
|
|
15
|
-
const PASSWORD = "password";
|
|
16
|
-
|
|
17
|
-
const COOKIE_EXPIRY_MS = 5 * 60 * 1000; // 5 minutes
|
|
18
|
-
|
|
19
|
-
const CANVA_BASE_URL = "https://canva.com";
|
|
20
|
-
|
|
21
|
-
interface Data {
|
|
22
|
-
users: string[];
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
* For more information on Authentication, refer to our documentation: {@link https://www.canva.dev/docs/apps/authenticating-users/#types-of-authentication}.
|
|
27
|
-
*/
|
|
28
|
-
export const createAuthRouter = () => {
|
|
29
|
-
const APP_ID = getAppId();
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* Set up a database with a "users" table. In this example code, the
|
|
33
|
-
* database is simply a JSON file.
|
|
34
|
-
*/
|
|
35
|
-
const db = new JSONFileDatabase<Data>({ users: [] });
|
|
36
|
-
|
|
37
|
-
const router = express.Router();
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
* The `cookieParser` middleware allows the routes to read and write cookies.
|
|
41
|
-
*
|
|
42
|
-
* By passing a value into the middleware, we enable the "signed cookies" feature of Express.js. The
|
|
43
|
-
* value should be static and cryptographically generated. If it's dynamic (as shown below), cookies
|
|
44
|
-
* won't persist between server restarts.
|
|
45
|
-
*
|
|
46
|
-
* TODO: Replace `crypto.randomUUID()` with a static value, loaded via an environment variable.
|
|
47
|
-
*/
|
|
48
|
-
router.use(cookieParser(crypto.randomUUID()));
|
|
49
|
-
|
|
50
|
-
/**
|
|
51
|
-
* This endpoint is hit at the start of the authentication flow. It contains a state which must
|
|
52
|
-
* be passed back to canva so that Canva can verify the response. It must also set a nonce in the
|
|
53
|
-
* user's browser cookies and send the nonce back to Canva as a url parameter.
|
|
54
|
-
*
|
|
55
|
-
* If Canva can validate the state, it will then redirect back to the chosen redirect url.
|
|
56
|
-
*/
|
|
57
|
-
router.get("/configuration/start", async (req, res) => {
|
|
58
|
-
/**
|
|
59
|
-
* Generate a unique nonce for each request. A nonce is a random, single-use value
|
|
60
|
-
* that's impossible to guess or enumerate. We recommended using a Version 4 UUID that
|
|
61
|
-
* is cryptographically secure, such as one generated by the `randomUUID` method.
|
|
62
|
-
*/
|
|
63
|
-
const nonce = crypto.randomUUID();
|
|
64
|
-
// Set the expiry time for the nonce. We recommend 5 minutes.
|
|
65
|
-
const expiry = Date.now() + COOKIE_EXPIRY_MS;
|
|
66
|
-
|
|
67
|
-
// Create a JSON string that contains the nonce and an expiry time
|
|
68
|
-
const nonceWithExpiry = JSON.stringify([nonce, expiry]);
|
|
69
|
-
|
|
70
|
-
// Set a cookie that contains the nonce and the expiry time
|
|
71
|
-
res.cookie("nonce", nonceWithExpiry, {
|
|
72
|
-
secure: true,
|
|
73
|
-
httpOnly: true,
|
|
74
|
-
maxAge: COOKIE_EXPIRY_MS,
|
|
75
|
-
signed: true,
|
|
76
|
-
});
|
|
77
|
-
|
|
78
|
-
// Create the query parameters that Canva requires
|
|
79
|
-
const params = new URLSearchParams({
|
|
80
|
-
nonce,
|
|
81
|
-
state: req?.query?.state?.toString() || "",
|
|
82
|
-
});
|
|
83
|
-
|
|
84
|
-
// Redirect to Canva with required parameters
|
|
85
|
-
res.redirect(302, `${CANVA_BASE_URL}/apps/configure/link?${params}`);
|
|
86
|
-
});
|
|
87
|
-
|
|
88
|
-
/**
|
|
89
|
-
* This endpoint renders a login page. Once the user logs in, they're
|
|
90
|
-
* redirected back to Canva, which completes the authentication flow.
|
|
91
|
-
*/
|
|
92
|
-
router.get(
|
|
93
|
-
"/redirect-url",
|
|
94
|
-
/**
|
|
95
|
-
* Use a JSON Web Token (JWT) to verify incoming requests. The JWT is
|
|
96
|
-
* extracted from the `canva_user_token` parameter.
|
|
97
|
-
*/
|
|
98
|
-
createJwtMiddleware(APP_ID, getTokenFromQueryString),
|
|
99
|
-
/**
|
|
100
|
-
* Warning: For demonstration purposes, we're using basic authentication and
|
|
101
|
-
* hard- coding a username and password. This is not a production-ready
|
|
102
|
-
* solution!
|
|
103
|
-
*/
|
|
104
|
-
basicAuth({
|
|
105
|
-
users: { [USERNAME]: PASSWORD },
|
|
106
|
-
challenge: true,
|
|
107
|
-
}),
|
|
108
|
-
async (req, res) => {
|
|
109
|
-
const failureResponse = () => {
|
|
110
|
-
const params = new URLSearchParams({
|
|
111
|
-
success: "false",
|
|
112
|
-
state: req.query.state?.toString() || "",
|
|
113
|
-
});
|
|
114
|
-
res.redirect(302, `${CANVA_BASE_URL}/apps/configured?${params}`);
|
|
115
|
-
};
|
|
116
|
-
|
|
117
|
-
// Get the nonce and expiry time stored in the cookie.
|
|
118
|
-
const cookieNonceAndExpiry = req.signedCookies.nonce;
|
|
119
|
-
|
|
120
|
-
// Get the nonce from the query parameter.
|
|
121
|
-
const queryNonce = req.query.nonce?.toString();
|
|
122
|
-
|
|
123
|
-
// After reading the cookie, clear it. This forces abandoned auth flows to be restarted.
|
|
124
|
-
res.clearCookie("nonce");
|
|
125
|
-
|
|
126
|
-
let cookieNonce = "";
|
|
127
|
-
let expiry = 0;
|
|
128
|
-
|
|
129
|
-
try {
|
|
130
|
-
[cookieNonce, expiry] = JSON.parse(cookieNonceAndExpiry);
|
|
131
|
-
} catch {
|
|
132
|
-
// If the nonce can't be parsed, assume something has been compromised and exit.
|
|
133
|
-
return failureResponse();
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
// If the nonces are empty, exit the authentication flow.
|
|
137
|
-
if (
|
|
138
|
-
isEmpty(cookieNonceAndExpiry) ||
|
|
139
|
-
isEmpty(queryNonce) ||
|
|
140
|
-
isEmpty(cookieNonce)
|
|
141
|
-
) {
|
|
142
|
-
return failureResponse();
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
/**
|
|
146
|
-
* Check that:
|
|
147
|
-
*
|
|
148
|
-
* - The nonce in the cookie and query parameter contain the same value
|
|
149
|
-
* - The nonce has not expired
|
|
150
|
-
*
|
|
151
|
-
* **Note:** We could rely on the cookie expiry, but that is vulnerable to tampering
|
|
152
|
-
* with the browser's time. This allows us to double-check based on server time.
|
|
153
|
-
*/
|
|
154
|
-
if (expiry < Date.now() || cookieNonce !== queryNonce) {
|
|
155
|
-
return failureResponse();
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
// Get the userId from JWT middleware
|
|
159
|
-
const { userId } = req.canva;
|
|
160
|
-
|
|
161
|
-
// Load the database
|
|
162
|
-
const data = await db.read();
|
|
163
|
-
|
|
164
|
-
// Add the user to the database
|
|
165
|
-
if (!data.users.includes(userId)) {
|
|
166
|
-
data.users.push(userId);
|
|
167
|
-
await db.write(data);
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
// Create query parameters for redirecting back to Canva
|
|
171
|
-
const params = new URLSearchParams({
|
|
172
|
-
success: "true",
|
|
173
|
-
state: req?.query?.state?.toString() || "",
|
|
174
|
-
});
|
|
175
|
-
|
|
176
|
-
// Redirect the user back to Canva
|
|
177
|
-
res.redirect(302, `${CANVA_BASE_URL}/apps/configured?${params}`);
|
|
178
|
-
},
|
|
179
|
-
);
|
|
180
|
-
|
|
181
|
-
/**
|
|
182
|
-
* TODO: Add this middleware to all routes that will receive requests from
|
|
183
|
-
* your app.
|
|
184
|
-
*/
|
|
185
|
-
const jwtMiddleware = createJwtMiddleware(APP_ID);
|
|
186
|
-
|
|
187
|
-
/**
|
|
188
|
-
* This endpoint is called when a user disconnects an app from their account.
|
|
189
|
-
* The app is expected to de-authenticate the user on its backend, so if the
|
|
190
|
-
* user reconnects the app, they'll need to re-authenticate.
|
|
191
|
-
*
|
|
192
|
-
* Note: The name of the endpoint is *not* configurable.
|
|
193
|
-
*
|
|
194
|
-
* Note: This endpoint is called by Canva's backend directly and must be
|
|
195
|
-
* exposed via a public URL. To test this endpoint, add a proxy URL, such as
|
|
196
|
-
* one generated by nGrok, to the 'Add authentication' section in the
|
|
197
|
-
* Developer Portal. Localhost addresses will not work to test this endpoint.
|
|
198
|
-
*/
|
|
199
|
-
router.post("/configuration/delete", jwtMiddleware, async (req, res) => {
|
|
200
|
-
// Get the userId from JWT middleware
|
|
201
|
-
const { userId } = req.canva;
|
|
202
|
-
|
|
203
|
-
// Load the database
|
|
204
|
-
const data = await db.read();
|
|
205
|
-
|
|
206
|
-
// Remove the user from the database
|
|
207
|
-
await db.write({
|
|
208
|
-
users: data.users.filter((user) => user !== userId),
|
|
209
|
-
});
|
|
210
|
-
|
|
211
|
-
// Confirm that the user was removed
|
|
212
|
-
res.send({
|
|
213
|
-
type: "SUCCESS",
|
|
214
|
-
});
|
|
215
|
-
});
|
|
216
|
-
|
|
217
|
-
/**
|
|
218
|
-
* All routes that start with /api will be protected by JWT authentication
|
|
219
|
-
*/
|
|
220
|
-
router.use("/api", jwtMiddleware);
|
|
221
|
-
|
|
222
|
-
/**
|
|
223
|
-
* This endpoint checks if a user is authenticated.
|
|
224
|
-
*/
|
|
225
|
-
router.post("/api/authentication/status", async (req, res) => {
|
|
226
|
-
// Load the database
|
|
227
|
-
const data = await db.read();
|
|
228
|
-
|
|
229
|
-
// Check if the user is authenticated
|
|
230
|
-
const isAuthenticated = data.users.includes(req.canva.userId);
|
|
231
|
-
|
|
232
|
-
// Return the authentication status
|
|
233
|
-
res.send({
|
|
234
|
-
isAuthenticated,
|
|
235
|
-
});
|
|
236
|
-
});
|
|
237
|
-
|
|
238
|
-
return router;
|
|
239
|
-
};
|
|
240
|
-
|
|
241
|
-
/**
|
|
242
|
-
* Checks if a given param is nullish or an empty string
|
|
243
|
-
*
|
|
244
|
-
* @param str The string to check
|
|
245
|
-
* @returns true if the string is nullish or empty, false otherwise
|
|
246
|
-
*/
|
|
247
|
-
function isEmpty(str?: string): boolean {
|
|
248
|
-
return str == null || str.length === 0;
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
/**
|
|
252
|
-
* Retrieves the CANVA_APP_ID from the environment variables.
|
|
253
|
-
* Throws an error if the CANVA_APP_ID environment variable is undefined or set to a default value.
|
|
254
|
-
*
|
|
255
|
-
* @returns {string} The Canva App ID
|
|
256
|
-
* @throws {Error} If CANVA_APP_ID environment variable is undefined or set to a default value
|
|
257
|
-
*/
|
|
258
|
-
function getAppId(): string {
|
|
259
|
-
// TODO: Set the CANVA_APP_ID environment variable in the project's .env file
|
|
260
|
-
const appId = process.env.CANVA_APP_ID;
|
|
261
|
-
|
|
262
|
-
if (!appId) {
|
|
263
|
-
throw new Error(
|
|
264
|
-
`The CANVA_APP_ID environment variable is undefined. Set the variable in the project's .env file.`,
|
|
265
|
-
);
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
if (appId === "YOUR_APP_ID_HERE") {
|
|
269
|
-
// eslint-disable-next-line no-console
|
|
270
|
-
console.log(
|
|
271
|
-
chalk.bgRedBright(
|
|
272
|
-
"Default 'CANVA_APP_ID' environment variable detected.",
|
|
273
|
-
),
|
|
274
|
-
);
|
|
275
|
-
// eslint-disable-next-line no-console
|
|
276
|
-
console.log(
|
|
277
|
-
"Please update the 'CANVA_APP_ID' environment variable in your project's `.env` file " +
|
|
278
|
-
`with the App ID obtained from the Canva Developer Portal: ${chalk.greenBright(
|
|
279
|
-
"https://www.canva.com/developers/apps",
|
|
280
|
-
)}\n`,
|
|
281
|
-
);
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
return appId;
|
|
285
|
-
}
|
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
import { Text } from "@canva/app-ui-kit";
|
|
2
|
-
import { useIntl } from "react-intl";
|
|
3
|
-
import { useAppContext } from "src/context";
|
|
4
|
-
|
|
5
|
-
export const LoggedInStatus = (): JSX.Element => {
|
|
6
|
-
const { loggedInState } = useAppContext();
|
|
7
|
-
|
|
8
|
-
const intl = useIntl();
|
|
9
|
-
|
|
10
|
-
const createAuthenticationMessage = () => {
|
|
11
|
-
switch (loggedInState) {
|
|
12
|
-
case "checking":
|
|
13
|
-
return intl.formatMessage({
|
|
14
|
-
defaultMessage: "Checking authentication status...",
|
|
15
|
-
description:
|
|
16
|
-
"A message to indicate that the app is actively checking if the user is logged in",
|
|
17
|
-
});
|
|
18
|
-
case "authenticated":
|
|
19
|
-
//@TODO: Make a call to your own backend to get the user's information.
|
|
20
|
-
return intl.formatMessage(
|
|
21
|
-
{
|
|
22
|
-
defaultMessage: "You are logged in as {name} ({email})",
|
|
23
|
-
description:
|
|
24
|
-
"A message to indicate that the user is logged in and display their name and email address",
|
|
25
|
-
},
|
|
26
|
-
{ name: "Jane Doe", email: "jane@mail.com" },
|
|
27
|
-
);
|
|
28
|
-
case "not_authenticated":
|
|
29
|
-
return "";
|
|
30
|
-
default:
|
|
31
|
-
return intl.formatMessage({
|
|
32
|
-
defaultMessage: "Unknown authentication status",
|
|
33
|
-
description:
|
|
34
|
-
"A message to indicate that it isn't currently known if the user is logged in or not",
|
|
35
|
-
});
|
|
36
|
-
}
|
|
37
|
-
};
|
|
38
|
-
|
|
39
|
-
return (
|
|
40
|
-
<Text alignment="center" size="small">
|
|
41
|
-
{createAuthenticationMessage()}
|
|
42
|
-
</Text>
|
|
43
|
-
);
|
|
44
|
-
};
|
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
import { auth } from "@canva/user";
|
|
2
|
-
import { useAppContext } from "src/context";
|
|
3
|
-
|
|
4
|
-
export const useAuth = () => {
|
|
5
|
-
const { setLoggedInState } = useAppContext();
|
|
6
|
-
|
|
7
|
-
const requestAuthentication = async () => {
|
|
8
|
-
try {
|
|
9
|
-
const response = await auth.requestAuthentication();
|
|
10
|
-
switch (response.status) {
|
|
11
|
-
case "COMPLETED":
|
|
12
|
-
setLoggedInState("authenticated");
|
|
13
|
-
break;
|
|
14
|
-
case "ABORTED":
|
|
15
|
-
setLoggedInState("not_authenticated");
|
|
16
|
-
break;
|
|
17
|
-
case "DENIED":
|
|
18
|
-
setLoggedInState("not_authenticated");
|
|
19
|
-
break;
|
|
20
|
-
default:
|
|
21
|
-
setLoggedInState("not_authenticated");
|
|
22
|
-
break;
|
|
23
|
-
}
|
|
24
|
-
} catch (e) {
|
|
25
|
-
// eslint-disable-next-line no-console
|
|
26
|
-
console.error(e);
|
|
27
|
-
}
|
|
28
|
-
};
|
|
29
|
-
|
|
30
|
-
return { requestAuthentication };
|
|
31
|
-
};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export * from "./auth";
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { createJwtMiddleware } from "./jwt_middleware";
|