-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
81 lines (65 loc) · 2.18 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import {fetchToken, saveToken} from '../utils/index.js';
import {MermaidChart} from '../utils/MermaidChart.js';
const MC_BASE_URL = process.env.MC_BASE_URL || "https://test.mermaidchart.com";
export default function routes(app, addon) {
const mermaidAPI = new MermaidChart({
baseURL: MC_BASE_URL,
clientID: process.env.MC_CLIENT_ID || "839d35ba-cfee-4c98-8cee-88f2d2caa0c4",
redirectURI: `${addon.config.localBaseUrl()}/callback`,
addon,
})
app.get("/", (req, res) => {
res.redirect("/atlassian-connect.json");
});
app.get("/viewer", addon.authenticate(), (req, res) => {
res.render("viewer.hbs");
});
app.get("/editor", addon.authenticate(), async (req, res) => {
let access_token, user;
try {
access_token = await fetchToken(req.context.http, req.context.userAccountId)
user = access_token ? await mermaidAPI.getUser(access_token) : undefined
} catch (e) {}
const auth = user ? {} : await mermaidAPI.getAuthorizationData()
res.render("editor.hbs", {
MC_BASE_URL: MC_BASE_URL,
mcAccessToken: user ? access_token : '',
loginURL: auth.url,
loginState: auth.state,
user: user ? JSON.stringify(user) : 'null'
});
});
app.get("/check_token", addon.checkValidToken(), async (req, res) => {
if (!req.query.state) {
return res.status(404).end();
}
const token = await mermaidAPI.getToken(req.query.state);
if (!token) {
return res.status(404).end();
}
await mermaidAPI.delToken(req.query.state);
const user = await mermaidAPI.getUser(token)
try {
await saveToken(req.context.http, req.context.userAccountId, token)
return res.json({ token, user }).end();
} catch (e) {
console.error(e)
res.status(503).end();
}
})
app.post("/logout", addon.checkValidToken(), async (req, res) => {
await saveToken(req.context.http, req.context.userAccountId, '')
res.end();
})
app.get("/callback", async (req, res) => {
let errorMessage;
try {
await mermaidAPI.handleAuthorizationResponse(req.query)
} catch (e) {
errorMessage = e.message;
}
res.render("authCallback.hbs", {
errorMessage,
})
})
}