|
| 1 | +require("dotenv").config(); |
| 2 | +const axios = require("axios"); |
| 3 | +const express = require("express"); |
| 4 | +const path = require("path"); |
| 5 | +const cors = require("cors"); |
| 6 | +const cookieParser = require("cookie-parser"); |
| 7 | +const { v4: uuidv4 } = require("uuid"); |
| 8 | + |
| 9 | +const app = express(); |
| 10 | + |
| 11 | +// Enable CORS and assume the allowed origin is the redirect URI. |
| 12 | +// i.e., this assumes that your client shares the same domain as the server. |
| 13 | +app.use( |
| 14 | + cors({ |
| 15 | + origin: "http://localhost:3000", |
| 16 | + }) |
| 17 | +); |
| 18 | + |
| 19 | +// Enable storage of data in cookies. |
| 20 | +// Signed cookies are signed by the COOKIE-SECRET environment variable. |
| 21 | +app.use(cookieParser(process.env.COOKIE_SECRET)); |
| 22 | + |
| 23 | +// Serve files in the ./static folder. |
| 24 | +app.use(express.static("static")); |
| 25 | + |
| 26 | +// Send static index.html page to the client. |
| 27 | +// This page includes a button to authenticatate with Asana. |
| 28 | +app.get("/", (req, res) => { |
| 29 | + res.sendFile(path.join(__dirname, "/static/index.html")); |
| 30 | +}); |
| 31 | + |
| 32 | +// When the user clicks on the "Authenticate with Asana" button (from index.html), |
| 33 | +// it redirects them to the user authorization endpoint. |
| 34 | +// Docs: https://developers.asana.com/docs/oauth#user-authorization-endpoint |
| 35 | +app.get("/authenticate", (req, res) => { |
| 36 | + // Generate a `state` value and store it |
| 37 | + // Docs: https://developers.asana.com/docs/oauth#response |
| 38 | + let generatedState = uuidv4(); |
| 39 | + |
| 40 | + // Expiration of 5 minutes |
| 41 | + res.cookie("state", generatedState, { |
| 42 | + maxAge: 1000 * 60 * 5, |
| 43 | + signed: true, |
| 44 | + }); |
| 45 | + |
| 46 | + res.redirect( |
| 47 | + `https://app.asana.com/-/oauth_authorize?response_type=code&client_id=${process.env.CLIENT_ID}&redirect_uri=${process.env.REDIRECT_URI}&state=${generatedState}` |
| 48 | + ); |
| 49 | +}); |
| 50 | + |
| 51 | +// Redirect the user here upon successful or failed authentications. |
| 52 | +// This endpoint on your server must be accessible via the redirect URL that you provided in the developer console. |
| 53 | +// Docs: https://developers.asana.com/docs/oauth#register-an-application |
| 54 | +app.get("/oauth-callback", (req, res) => { |
| 55 | + // Prevent CSRF attacks by validating the 'state' parameter. |
| 56 | + // Docs: https://developers.asana.com/docs/oauth#user-authorization-endpoint |
| 57 | + if (req.query.state !== req.signedCookies.state) { |
| 58 | + res.status(422).send("The 'state' parameter does not match."); |
| 59 | + return; |
| 60 | + } |
| 61 | + |
| 62 | + console.log( |
| 63 | + "***** Code (to be exchanged for a token) and state from the user authorization response:\n" |
| 64 | + ); |
| 65 | + console.log(`code: ${req.query.code}`); |
| 66 | + console.log(`state: ${req.query.state}\n`); |
| 67 | + |
| 68 | + // Body of the POST request to the token exchange endpoint. |
| 69 | + const body = { |
| 70 | + grant_type: "authorization_code", |
| 71 | + client_id: process.env.CLIENT_ID, |
| 72 | + client_secret: process.env.CLIENT_SECRET, |
| 73 | + redirect_uri: process.env.REDIRECT_URI, |
| 74 | + code: req.query.code, |
| 75 | + }; |
| 76 | + |
| 77 | + // Set Axios to serialize the body to urlencoded format. |
| 78 | + const config = { |
| 79 | + headers: { |
| 80 | + "content-type": "application/x-www-form-urlencoded", |
| 81 | + }, |
| 82 | + }; |
| 83 | + |
| 84 | + // Make the request to the token exchange endpoint. |
| 85 | + // Docs: https://developers.asana.com/docs/oauth#token-exchange-endpoint |
| 86 | + axios |
| 87 | + .post("https://app.asana.com/-/oauth_token", body, config) |
| 88 | + .then((res) => { |
| 89 | + console.log("***** Response from the token exchange request:\n"); |
| 90 | + console.log(res.data); |
| 91 | + return res.data; |
| 92 | + }) |
| 93 | + .then((data) => { |
| 94 | + // Store tokens in cookies. |
| 95 | + // In a production app, you should store this data somewhere secure and durable instead (e.g., a database). |
| 96 | + res.cookie("access_token", data.access_token, { maxAge: 60 * 60 * 1000 }); |
| 97 | + res.cookie("refresh_token", data.refresh_token, { |
| 98 | + // Prevent client-side scripts from accessing this data. |
| 99 | + httpOnly: true, |
| 100 | + secure: true, |
| 101 | + }); |
| 102 | + |
| 103 | + // Redirect to the main page with the access token loaded into a URL query param. |
| 104 | + res.redirect(`/?access_token=${data.access_token}`); |
| 105 | + }) |
| 106 | + .catch((err) => { |
| 107 | + console.log(err.message); |
| 108 | + }); |
| 109 | +}); |
| 110 | + |
| 111 | +app.get("/get-me", (req, res) => { |
| 112 | + // This assumes that the access token exists and has NOT expired. |
| 113 | + if (req.cookies.access_token) { |
| 114 | + const config = { |
| 115 | + headers: { |
| 116 | + Authorization: "Bearer " + req.cookies.access_token, |
| 117 | + }, |
| 118 | + }; |
| 119 | + |
| 120 | + // Below, we are making a request to GET /users/me (docs: https://developers.asana.com/reference/getuser) |
| 121 | + // |
| 122 | + // If the request returns a 401 Unauthorized status, you should refresh your access token (not shown). |
| 123 | + // You can do so by making another request to the token exchange endpoint, this time passing in |
| 124 | + // a 'refresh_token' parameter (whose value is the actual refresh token), and also setting |
| 125 | + // 'grant_type' to 'refresh_token' (instead of 'authorization_code'). |
| 126 | + // |
| 127 | + // Docs: https://developers.asana.com/docs/oauth#token-exchange-endpoint |
| 128 | + // |
| 129 | + // If using Axios, you can implement a refresh token mechanism with interceptors (docs: https://axios-http.com/docs/interceptors). |
| 130 | + axios |
| 131 | + .get("https://app.asana.com/api/1.0/users/me?opt_pretty=true", config) |
| 132 | + .then((res) => res.data) |
| 133 | + .then((userInfo) => { |
| 134 | + console.log("***** Response from GET /users/me:\n"); |
| 135 | + console.log(JSON.stringify(userInfo, null, 2)); |
| 136 | + |
| 137 | + // Send back a JSON response from GET /users/me as JSON (viewable in the browser). |
| 138 | + res.json(userInfo); |
| 139 | + }); |
| 140 | + } else { |
| 141 | + res.redirect("/"); |
| 142 | + } |
| 143 | +}); |
| 144 | + |
| 145 | +// Start server on port 3000. |
| 146 | +app.listen(3000, () => |
| 147 | + console.log("Server started -> http://localhost:3000\n") |
| 148 | +); |
0 commit comments