|
| 1 | +const express = require("express"); |
| 2 | +const handlebars = require("handlebars"); |
| 3 | + |
| 4 | +const app = express(); |
| 5 | +const PORT = process.env.PORT || 3000; |
| 6 | + |
| 7 | +const authenticatedTemplateSource = ` |
| 8 | +<div> |
| 9 | + <p>Authenticated: Yes</p> |
| 10 | + <p>Display Name: {{displayName}}</p> |
| 11 | + <p><a href="/handler/account-settings" style="text-decoration: underline;">Account Settings</a></p> |
| 12 | + <p><a href="/protected" style="text-decoration: underline;">Go to protected page</a></p> |
| 13 | + <p><a href="/handler/sign-out" style="text-decoration: underline;">Sign Out</a></p> |
| 14 | +</div> |
| 15 | +`; |
| 16 | + |
| 17 | +const unauthenticatedTemplateSource = ` |
| 18 | +<div> |
| 19 | + <p>Authenticated: No</p> |
| 20 | + <p><a href="/protected" style="text-decoration: underline;">Go to protected page</a></p> |
| 21 | + <p><a href="/handler/sign-in" style="text-decoration: underline;">Sign In</a></p> |
| 22 | +</div> |
| 23 | +`; |
| 24 | + |
| 25 | +const authenticatedTemplate = handlebars.compile(authenticatedTemplateSource); |
| 26 | +const unauthenticatedTemplate = handlebars.compile( |
| 27 | + unauthenticatedTemplateSource |
| 28 | +); |
| 29 | + |
| 30 | +app.get("/", (req, res) => { |
| 31 | + const authenticated = !!req.headers["x-stack-authenticated"]; |
| 32 | + const displayName = req.headers["x-stack-user-display-name"] || ""; |
| 33 | + |
| 34 | + let html; |
| 35 | + if (authenticated) { |
| 36 | + html = authenticatedTemplate({ displayName }); |
| 37 | + } else { |
| 38 | + html = unauthenticatedTemplate(); |
| 39 | + } |
| 40 | + |
| 41 | + res.send(html); |
| 42 | +}); |
| 43 | + |
| 44 | +app.get("/protected", (req, res) => { |
| 45 | + const protectedTemplate = handlebars.compile( |
| 46 | + "<p>This is a protected page, only authenticated users can access it</p>" |
| 47 | + ); |
| 48 | + res.send(protectedTemplate()); |
| 49 | +}); |
| 50 | + |
| 51 | +app.listen(PORT, () => { |
| 52 | + console.log(`Server is running on http://localhost:${PORT}`); |
| 53 | +}); |
0 commit comments