-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
215 lines (187 loc) · 5.93 KB
/
app.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
const express = require("express");
const app = express();
const session = require("express-session");
const path = require("path");
const axios = require("axios");
const PORT = process.env.PORT || 8080;
const { AuthorizationCode, ClientCredentials } = require("simple-oauth2");
require("dotenv").config();
const postZaikioOrderRequestParams = require('./payload');
// Setup OAuth Client
const OAUTH_CLIENT_CONFIG = {
client: {
id: process.env.HUB_OAUTH_CLIENT_ID,
secret: process.env.HUB_OAUTH_CLIENT_SECRET,
},
auth: {
tokenHost: process.env.ZAIKIO_HUB_HOST,
tokenPath: "/oauth/access_token",
revokePath: "/api/v1/revoked_access_tokens",
},
};
const OAUTH_CLIENT = new AuthorizationCode(OAUTH_CLIENT_CONFIG);
app
.set("views", path.join(__dirname, "views"))
.set("view engine", "ejs")
.use(
session({
secret: process.env.SESSION_KEY,
})
)
.listen(PORT, () => {
console.log(`Zaikio node demo listening at http://localhost:${PORT}`);
});
async function getAccessToken(req, res) {
if (req.session && req.session.zai_access_token) {
let accessToken = OAUTH_CLIENT.createToken(
JSON.parse(req.session.zai_access_token)
);
try {
// Refresh token if needed
if (accessToken.expired()) {
accessToken = await accessToken.refresh();
req.session.zai_access_token = JSON.stringify(accessToken.toJSON());
}
} catch (error) {
console.log("Error refreshing access token: ", error.message);
}
axios.defaults.headers.common["Authorization"] =
"Bearer " + accessToken.token.access_token;
return true;
} else {
// Redirect to Zaikio SSO
res.redirect(
OAUTH_CLIENT.authorizeURL({
redirect_uri: process.env.HUB_OAUTH_REDIRECT_URL,
scope: "zaikio.person.r",
})
);
res.end();
return false;
}
}
app.get("/", async (req, res) => {
// Open organization dashboard if coming from zaikio
if (req.query.organization_id) {
res.redirect(`/organization?organization_id=${req.query.organization_id}`);
res.end();
return;
}
if (!(await getAccessToken(req, res))) {
return;
}
res.render("pages/index", {
currentUser: (
await axios.get(process.env.ZAIKIO_HUB_HOST + "/api/v1/person.json")
).data,
host: process.env.ZAIKIO_HUB_HOST,
});
res.end();
});
app.get("/install", async (req, res) => {
if (!(await getAccessToken(req, res))) {
return;
}
// Redirect to Zaikio SSO for organization
res.redirect(
OAUTH_CLIENT.authorizeURL({
redirect_uri: process.env.HUB_OAUTH_ORG_REDIRECT_URL,
scope: req.query.organization_id
? `Org/${req.query.organization_id}.zaikio.organization.r,Org/${req.query.organization_id}.zaikio.orders.rw,Org/${req.query.organization_id}.zaikio.jobs.rw`
: "Org.zaikio.organization.r,Org.zaikio.orders.rw,Org.zaikio.jobs.rw",
})
);
res.end();
});
app.get("/organization", async (req, res) => {
if (!(await getAccessToken(req, res))) {
return;
}
const message = req.session.message;
req.session.message = null;
res.render("pages/organization", {
message,
membership: (
await axios.get(process.env.ZAIKIO_HUB_HOST + "/api/v1/person.json")
).data.organization_memberships.find(
(m) => m.organization.id === req.query.organization_id
),
host: process.env.ZAIKIO_HUB_HOST,
});
res.end();
});
app.get("/current_person.json", async (req, res) => {
if (!(await getAccessToken(req, res))) {
return;
}
res.setHeader("Content-Type", "application/json");
res.end(
JSON.stringify(
(await axios.get(process.env.ZAIKIO_HUB_HOST + "/api/v1/person.json"))
.data
)
);
});
app.get("/oauth/callback", async (req, res) => {
try {
// Request access token from zaikio
const accessToken = await OAUTH_CLIENT.getToken({
code: req.query.code,
redirect_uri: process.env.HUB_OAUTH_REDIRECT_URL,
scope: "zaikio.person.r",
});
// Store access token in session
req.session.zai_access_token = JSON.stringify(accessToken.toJSON());
} catch (error) {
console.log("Access Token Error", error.message);
}
res.redirect("/");
});
app.get("/oauth/org-callback", async (req, res) => {
try {
// Request access token from zaikio to establish connection for the organization
const accessToken = await OAUTH_CLIENT.getToken({
code: req.query.code,
redirect_uri: process.env.HUB_OAUTH_ORG_REDIRECT_URL,
});
} catch (error) {
console.log("Access Token Error", error.message);
}
res.redirect("/");
});
app.get("/logout", (req, res) => {
req.session.destroy();
res.render("pages/logout");
});
// Parse information from the html post form
app.use(express.urlencoded({ extended: true }));
app.post("/create_zaikio_order", async (req, res) => {
if (!(await getAccessToken(req, res))) {
return;
}
const { organizationId, orderNumber, quantity } = req.body;
const referer = req.headers.referer;
const client = new ClientCredentials(OAUTH_CLIENT_CONFIG);
let accessToken;
try {
accessToken = await client.getToken({ scope: `Org/${organizationId}.zaikio.orders.rw,Org/${organizationId}.zaikio.jobs.rw` });
} catch (error) {
console.error('Access Token error', error.message);
req.session.message = { type: 'Access Token error', text: error.message};
res.redirect(referer);
}
if (accessToken) {
try {
const payload = postZaikioOrderRequestParams(Number(quantity), String(orderNumber));
const response = await axios.post(process.env.DATA_PLATFORM_HOST + "/api/v1/orders", payload,
{
headers: {"Content-Type": "application/json", "Authorization": "Bearer " + accessToken.token.access_token}
});
req.session.message = { type: '', text: `Order with ID=${response.data.id} been successfully created`};
res.redirect(referer);
} catch (error) {
req.session.message = { type: 'Request error', text: error.message};
res.redirect(referer);
}
}
});