-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
284 lines (250 loc) · 9.54 KB
/
server.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
// Import required modules and dependencies
const express = require('express');
const bodyParser = require('body-parser');
const passport = require('passport');
const OAuth2Strategy = require('passport-oauth2').Strategy;
const session = require('express-session');
const next = require('next');
const path = require("path");
const hmacSHA256 = require("crypto-js/hmac-sha256");
const config = require('./config');
const Session = require("./session/session");
const SessionStorage = require("./session/session_storage");
const { getSessionFromRequest } = require('./session/sessionUtils.js');
const cookieParser = require('cookie-parser');
// Set up environment and Next.js app
const isDev = process.env.NODE_ENV !== 'production';
const nextApp = next({ dev: isDev });
const handle = nextApp.getRequestHandler(); // Next.js request handler
// Extension configuration constants from environment variables
const {
SESSION_COOKIE_NAME,
EXTENSION_BASEURL,
EXTENSION_ID,
EXTENSION_SECRET,
FP_API_DOMAIN
} = config;
// Initialize Express app
const app = express();
// Middleware setup
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Middleware to parse cookies with a secret key
app.use(cookieParser("ext.session"));
// Set up session handling with express-session
app.use(session({
secret: 'your-secret-key', // Replace with a secure secret
resave: false,
saveUninitialized: true,
}));
// Initialize Passport for authentication
app.use(passport.initialize());
app.use(passport.session());
// Serialize user to the session
passport.serializeUser((user, done) => {
done(null, user);
});
// Deserialize user from the session
passport.deserializeUser((user, done) => {
done(null, user);
});
// Function to configure and return the OAuth2 strategy
function getOAuthStrategy(companyId, applicationId) {
const callbackURL = applicationId
? `${EXTENSION_BASEURL}/fp/auth?application_id=${applicationId}`
: `${EXTENSION_BASEURL}/fp/auth`;
return new OAuth2Strategy({
authorizationURL: `${FP_API_DOMAIN}/service/panel/authentication/v1.0/company/${companyId}/oauth/authorize`,
tokenURL: `${FP_API_DOMAIN}/service/panel/authentication/v1.0/company/${companyId}/oauth/token`,
clientID: EXTENSION_ID,
clientSecret: EXTENSION_SECRET,
callbackURL,
passReqToCallback: true
},
(req, accessToken, refreshToken, token, profile, cb) => {
req.token = token;
return cb(null, { accessToken });
}
);
}
// OAuth authentication route
app.get('/fp/install', async (req, res, next) => {
try {
let companyId = parseInt(req.query.company_id);
const state = Buffer.from(JSON.stringify("abcefg")).toString('base64');
let extensionScope = [];
let session = new Session(Session.generateSessionId());
let redirectPath = req.query.redirect_path;
let sessionExpires = new Date(Date.now() + 900000); // 15 min
if (session.isNew) {
session.company_id = companyId;
session.scope = extensionScope;
session.expires = sessionExpires;
session.access_mode = 'online'; // Always generate online mode token for extension launch
session.extension_id = EXTENSION_ID;
session.redirect_path = redirectPath;
} else {
if (session.expires) {
session.expires = new Date(session.expires);
}
}
req.fdkSession = session;
const compCookieName = `${SESSION_COOKIE_NAME}_${companyId}`
res.header['x-company-id'] = companyId;
res.cookie(compCookieName, session.id, {
secure: true,
httpOnly: true,
expires: session.expires,
signed: true,
sameSite: "None"
});
session.state = state;
passport.use(getOAuthStrategy(req.query.company_id, req.query.application_id));
const authenticator = passport.authenticate('oauth2', { scope: extensionScope, state });
authenticator(req, res, next);
await SessionStorage.saveSession(session);
}
catch (error) {
console.error("Error during /fp/install route:", error.message);
res.status(500).send({ error: `Error during /fp/install route: ${error.message}` });
}
});
// OAuth callback route
app.get('/fp/auth', passport.authenticate('oauth2', { failureRedirect: '/' }), sessionMiddleware(false), async (req, res) => {
try {
if (!req.fdkSession) {
throw new Error("Can not complete oauth process as session not found");
}
const companyId = req.fdkSession.company_id
const { token } = req;
let sessionExpires = new Date(Date.now() + token.expires_in * 1000);
req.fdkSession.expires = sessionExpires;
token.access_token_validity = sessionExpires.getTime();
req.fdkSession.updateToken(token);
await SessionStorage.saveSession(req.fdkSession);
const compCookieName = `${SESSION_COOKIE_NAME}_${companyId}`
res.cookie(compCookieName, req.fdkSession.id, {
secure: true,
httpOnly: true,
expires: sessionExpires,
signed: true,
sameSite: "None"
});
res.header['x-company-id'] = companyId;
// Subscribe to a specific event
await configureWebhookSubscriber(
token.access_token,
req.query.company_id,
);
// Redirect based on company or application ID
const redirectUrl = req.query.application_id
? `${process.env.EXTENSION_BASE_URL}/company/${req.query.company_id}/application/${req.query.application_id}`
: `${process.env.EXTENSION_BASE_URL}/company/${req.query.company_id}`;
return res.redirect(301, redirectUrl);
}
catch (error) {
console.error("Error during /fp/auth route:", error.message);
res.status(500).send({ error: `Error during /fp/auth route: ${error.message}` });
}
});
app.post('/fp/uninstall', (req, res) => {
// Write your cleanup logic to be executed after the extension is uninstalled.
res.json({ success: true });
});
function verifySignature(req, res, next) {
try {
const reqSignature = req.headers['x-fp-signature'];
const { body } = req;
const calcSignature = hmacSHA256(JSON.stringify(body), EXTENSION_SECRET).toString();
if (reqSignature !== calcSignature) {
return res.status(403).json({ "error": "Invalid signature" });
}
next();
} catch (error) {
return res.status(403).json({
"error": "InvalidSignature",
"message": "The request signature we calculated does not match the signature you provided."
});
}
}
app.post('/ext/webhook', verifySignature, (req, res) => {
try {
console.log(`Webhook Event: ${JSON.stringify(req.body.event)} received`)
return res.status(200).json({ "success": true });
} catch (err) {
console.error(`Error Processing ${req.body.event} Webhook`);
return res.status(500).json({ "success": false });
}
});
function sessionMiddleware(strict) {
return async (req, res, next) => {
try {
const companyId = req.headers['x-company-id'] || req.query['company_id'];
req.fdkSession = await getSessionFromRequest(req, companyId);
if (strict && !req.fdkSession) {
return res.status(401).json({ message: 'Unauthorized' });
}
next();
} catch (error) {
next(error);
}
};
}
// Function to configure webhook subscriber
// Check here for available webhook events https://partners.fynd.com/help/docs/webhooks/overview
async function configureWebhookSubscriber(accessToken, companyId) {
try {
const requestOptions = {
method: 'POST',
headers: {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: process.env.EXTENSION_API_KEY,
webhook_url: `${process.env.EXTENSION_BASE_URL}/ext/webhook`,
association: {
company_id: companyId,
criteria: 'ALL',
},
auth_meta: {
type: 'hmac',
secret: process.env.EXTENSION_API_SECRET,
},
email_id: 'dev@gofynd.com',
events: [
{ slug: 'company/product/delete/v1' }
],
status: 'active',
provider: 'rest'
}),
};
const response = await fetch(
`${FP_API_DOMAIN}/service/platform/webhook/v2.0/company/${companyId}/subscriber`,
requestOptions
);
return response.json(); // Return subscriber config data
}
catch (error) {
console.error(`Error while fetching webhook subscriber configuration, Reason: ${error.message}`);
}
}
// Serve static files from the 'build' directory in production
if (!isDev)
app.use('/_next', express.static(path.join(__dirname, 'public/build')));
// Handle all other requests with Next.js
app.all('*', (req, res) => {
return handle(req, res);
});
// Prepare and start the server
let server;
nextApp.prepare().then(() => {
const PORT = process.env.FRONTEND_PORT || 3000;
server = app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`);
});
})
const getServerInstance = () => {
return server
}
module.exports = { app, getServerInstance };