-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
388 lines (352 loc) · 9.37 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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
//import all required modules
const express = require("express");
const mongoose = require("mongoose"); //for mongodb database
const cors = require('cors');
const axios = require('axios');
const multer = require('multer');
const FormData = require('form-data');
const fs = require('fs');
var qs = require('qs');
const pdf = require('pdf-page-counter');
//creating app
const app = express();
//middlewares
app.use(express.urlencoded({ extended: true}));
app.use(express.json());
app.use(cors({origin: '*'}));
//DB Config
const db = require("./config/keys").mongoURI;
// Connect to MongoDB
mongoose
.connect(db, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
})
.then(() => console.log("MongoDB Connected"))
.catch((err) => console.log(err));
//upload functionalities
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads')
},
filename: function (req, file, cb) {
cb(null, file.originalname.replace(".pdf","") + '-' + Date.now()+ ".pdf")
}
})
var upload = multer({ storage: storage }).single('file')
// express route where we receive files from the client
// passing multer middleware
app.post('/files', (req, res) => {
// all other values passed from the client, like name, etc..
upload(req, res, function (err) {
if (err instanceof multer.MulterError) {
return res.status(500).json(err)
}
return res.sendStatus(200)
}
);
});
//models
const User = require("./models/User");
//const pdfContract = require("./models/pdfContract");
//require editing functions
const reorderPage = require('./OperationReorder.js');
const deletePage = require('./OperationDelete.js');
const splitFile = require('./OperationSplit.js');
const mergeFile = require('./OperationMerge')
//require all editing functions
const clientID = require('./config/signApi').clientID
const clientSecret = require('./config/signApi').clientSecret
const redirectUrl = require('./config/signApi').redirectURL
//findUser
const findUser = async (email, password) => {
let user = await User.findOne({email, password})
if(user){
return user
}else{
return null
}
}
//register user
const registerUser = async (email, password) => {
let alreadyUser = await User.findOne({email})
if(alreadyUser){
return null
}else{
const newUser = await new User({
email,
password,
});
return await newUser.save()
}
}
//find all users
const findAllUsers = async () => {
return await User.find({},{email:1})
}
// Routes
//login
app.post('/login', async (req,res)=>{
let {email, password} = req.body;
let user = await findUser(email.trim(), password)
if(user === null){
res.json({
success: false,
msg: "Account not found. Please enter correct credentials.",
token: null,
email:null
});
}else{
res.json({
success: true,
msg: "login successful",
token: "loginToken",
email: email,
});
}
})
//register
app.post('/register', async (req,res)=>{
let {email, password} = req.body;
let user = await registerUser(email.trim(), password)
if (user == null){
res.json({
success: false,
msg: "Email already exists. Please use different user name.",
token: null,
email:null
});
}else{
res.json({
success: true,
msg: "login successful",
token: "loginToken",
email: email,
});
}
});
const getNumPages = (filePath) => {
let dataBuffer = fs.readFileSync(filePath);
let totalPages = 0
totalPages = pdf(dataBuffer)
.then((data) => (
Promise.resolve(data.numpages)
))
return totalPages
}
//contracts
app.post('/contracts', async (req,res) => {
//let email = req.body;
let contracts = fs.readdirSync("./uploads");
res.send(
contracts
)
});
//reorder
app.post('/editcontract/reorderDelete', async(req,res) => {
let {selectedFiles, SP, EP, id} = req.body;
let fileName = selectedFiles;
let num_pages = await getNumPages(`./uploads/${fileName}`);
if(SP > num_pages){
res.json({
success: false,
msg:'Starting page cannot be greater than total no of pages',
})
}else if(EP > num_pages){
res.json({
success: false,
msg:'Ending page cannot be greater than total no. of pages',
})
}
if(id === 0){
let status = await deletePage(fileName, Number(SP), Number(EP))
if(status){
res.json({
success: true,
fileName: fileName,
})
}else{
res.json({
success: false,
msg:'Cannot reorder specified pages.',
})
}
}else if(id === 1){
let status = await reorderPage(fileName, Number(SP), Number(EP));
if(status){
res.json({
success: true,
fileName: fileName,
})
}else{
res.json({
success: false,
msg:'Cannot reorder specified pages.',
})
}
}else{
let status = await splitFile(fileName, Number(SP), Number(EP));
if(status.success){
res.json({
success: true,
fileName: status.savedFiles,
})
}else{
res.json({
success: false,
msg:'Cannot split file. Try again later.',
})
}
}
}
);
//sign api redirection
app.post('/signauth/redirect', async (req,res) => {
let {contract, email, code, state, api_access_point } = req.body;
//NOW SEND POST REQ TO TOKEN ENDPOINT
if (code !== null && code !== undefined) {
contract = state.split("__")[0]
email = state.split("__")[1]
var data = qs.stringify({
'code': code,
'client_id': clientID,
'client_secret': clientSecret,
'redirect_uri': redirectUrl,
'grant_type': 'authorization_code',
});
var config = {
method: 'post',
url: "https://api.adobesign.com/oauth/token",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data : data
};
let fetchedData = await axios(config)
.then(function (response) {
return (JSON.stringify(response.data));
})
.catch(function (error) {
res.json({
success: false,
msg: error
})
});
let access_token = JSON.parse(fetchedData).access_token
//let refresh_token = JSON.parse(fetchedData).refresh_token
if(access_token == undefined || access_token==null){
res.json({
success: false,
msg: 'Could not generate access token.'
})
}
data = new FormData();
try {
data.append('File', fs.createReadStream(`./uploads/${contract}`));
} catch (error) {
res.json({
success: false,
msg: "The created contract file was deleted due to free tier server usage."
})
}
config = {
method: 'post',
url: `${api_access_point}api/rest/v6/transientDocuments`,
headers: {
'Authorization': `Bearer ${access_token}`,
...data.getHeaders()
},
data : data
};
axios(config)
.then(function (response) {
let transientDocumentId = response.data.transientDocumentId;
var newData = JSON.stringify({"fileInfos":[{"transientDocumentId":`${transientDocumentId}`}],"name":`${contract}`,"participantSetsInfo":[{"memberInfos":[{"email":`${email}`}],"order":1,"role":"SIGNER"}],"signatureType":"ESIGN","state":"IN_PROCESS"});
var newConfig = {
method: 'post',
url: `${api_access_point}api/rest/v6/agreements`,
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${access_token}`
},
data : newData
};
axios(newConfig)
.then(() => {
res.json({
success: true,
msg: "Successful"
})
}).catch(e =>{
console.log(e)
res.json({
success: false,
msg: "Error occured while creating signing url."
})
})
})
.catch(e => {
console.log(e);
res.json({
success: false,
msg: "Error occured while creating agreement. Please try again."
})
})
}else{
let url = `https://secure.na1.adobesign.com/public/oauth?redirect_uri=${redirectUrl}&response_type=code&client_id=${clientID}&scope=user_login:self+agreement_read:self+agreement_write:self+agreement_send:self&state=${contract}__${email}`;
res.json({
success: true,
data: url,
});
}
})
//find all the other members present
app.post('/findusers', async (req,res) => {
let email = req.body.email;
let candidates = await findAllUsers()
let candidateNames=[];
candidates.forEach((candidate)=>{
if(candidate.email !== email) candidateNames.push(candidate.email)
})
res.send(
candidateNames
)
})
//create draft route
app.post('/mergefiles', async (req, res) => {
let {selectedFiles, mergedFileName} = req.body;
if(fs.existsSync(`uploads/${mergedFileName}.pdf`)){
res.json({
success: false,
msg: "File with same name already exists",
})
}else{
let stat = await mergeFile(selectedFiles, mergedFileName);
if(stat.success){
res.json({
success: true,
fileName: `${mergedFileName}.pdf`
})
}else{
res.json({
success: false,
msg: stat.msg
})
}}
});
// PDF LOCATION
app.get('/viewpdf/:pdfLocation', (req,res)=>{
var tempFile=`./uploads/${req.params.pdfLocation}`;
fs.readFile(tempFile, function (err,data){
res.contentType("application/pdf");
res.send(data);
})
});
//port
//eslint-disable-next-line
const PORT = process.env.PORT || 8080;
//start server
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`);
});