-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
482 lines (401 loc) · 14.8 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
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const cors = require('cors');
const CookiePraser = require('cookie-parser')
const jwt = require('jsonwebtoken');
// ===============================================================================================
// ASSIGN DATA MODEL
const Repository = require('./models/repositoriesModel');
const RepositoryData = require('./models/repositoriesDataModel');
const Account = require('./models/accountModel')
const Registrants = require('./models/registrantsModel')
const VisitorsQueue = require('./models/VisitorsQueueModel')
// ===============================================================================================
// ASIGN DOTENV
require("dotenv").config();
// ASIGN EXPRESS JSON
app.use(express.json())
// ASIGN EXPRESS URLENCODED
app.use(express.urlencoded({extended: false}))
// OAUTH API CORS
app.use(cors({
methods: ['GET', 'POST', 'PUT', 'DELETE']
}));
// COOKIES MIDDLEWARE
app.use(CookiePraser());
// ===========================================================//
// CLOUDINARY //
// import {v2 as cloudinary} from 'cloudinary';
// cloudinary.config({
// cloud_name: process.env.CLOUD_NAME_CLOUDINARY,
// api_key: process.env.API_KEY_CLOUDINARY,
// api_secret: process.env.API_SECRET_CLOUDINARY
// });
// ===========================================================//
// VAR INIT
const PORT = process.env.PORT;
const mongodbAPI = process.env.MONGODB_API;
const TOKEN = process.env.ASTHABOOKS
// MAIN ROUTE
app.get('/', (req, res) => {
res.send('Asthabooks API')
})
// Mailer
const nodeMailer = require('nodemailer')
// Mail format
const html = (username, token) => {
const link_verification = 'https://asthabooks.vercel.app/auth/confirmation/gate/'+username+'/'+token
//const link_verification = 'http://localhost:8000/account/verify/'+username+'/'+token;
return `
<body style="display: flex; height: 100vh; font-family: Arial, sans-serif;">
<div class="container" style="margin: auto; max-width: 100vw;">
<div class="header" style="background-color: #0b0b27;
height: 200px;
display: flex;
background-color: #0b0b27;
text-align: center;
padding: 20px;
width: 100%;">
<img src="https://res.cloudinary.com/dggk9y0yt/image/upload/f_auto,q_auto/v1/Asthabooks/Logo/bgip7borld66pvk6uktu" alt="Logo" style="height: 100px; width: auto; margin: auto;">
</div>
<div class="content" style="
padding-top: 50px;
padding-left: 20px;
margin: 20px;
height: 400px;">
<h1>Terima Kasih Telah Mendaftar</h1>
<p>Silakan klik tombol di bawah ini untuk memverifikasi akun Anda.</p>
<a href=${link_verification}>
<button style="
background-color: #4CAF50;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
border: 0;
border-radius: 6px;
cursor: pointer;"
>Verifikasi Akun</button>
</a>
</div>
<div class="footer" style="
background-color: #0b0b27;
color: white;
width: 100%;
text-align: center;
padding: 20px;
width: 100%;">
© Asthabooks 2023
</div>
</div>
</body>
`;
};
async function sendEmail (username, token, email){
console.log("pengiriman dimulai", Date())
const transporter = nodeMailer.createTransport({
service: 'gmail',
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
user : process.env.USERNAME_MAIL,
pass: process.env.PASS
},
tls: {
// do not fail on invalid certs
rejectUnauthorized: false,
},
});
try {
const info = await transporter.sendMail({
from: "Asthabooks <[email protected]>",
to: email,
subject: 'Account Verification',
html: html(username, token),
})
if (info){
console.log("pengiriman email berhasil dijalankan pada", Date(), info);
}
return info
} catch (error) {
console.error("Terjadi kesalahan saat mengirim email:", error);
return error
}
}
// COOKIES
const maxAge = 7 * 24 * 60 * 60 * 1000;
app.get('/set-cookies', (req, res) => {
// res.setHeader('Set-Cookie', 'newUser=true');
res.cookie('newUser', false);
res.cookie('isEmployee', true, {maxAge: 1000 * 60 * 60 * 24 * 7});
})
app.get('/read-cookies', (req, res) => {
const cookies = req.cookies;
console.log(cookies)
res.json(cookies);
})
// ===============================================================================================
// REPOSITORY ROUTER
// ===============================================================================================
// Get Latest
app.get('/component/update-latest/:token', async (req, res) => {
try {
const { token } = req.params;
if (token !== TOKEN) {
return res.status(403).json({ message: 'Unauthorized access' });
}
const repositories = await Repository.find({})
.sort({ updatedAt: -1 }) // Mengurutkan data berdasarkan updatedAt secara descending
.limit(10); // Mengambil hanya 10 data teratas
res.status(200).json(repositories);
} catch (error) {
res.status(500).json({ message: error.message });
}
});
// Get Rank
app.get('/component/rank/:token', async (req, res) => {
try {
const { token } = req.params;
if (token !== TOKEN) {
return res.status(403).json({ message: 'Unauthorized access' });
}
const repositories = await Repository.find({})
.sort({ viewcount: 1 }) // Mengurutkan data berdasarkan updatedAt secara descending
.limit(3); // Mengambil hanya 10 data teratas
res.status(200).json(repositories);
} catch (error) {
res.status(500).json({ message: error.message });
}
});
// GET ALL DATA
app.get('/repositories', async (req,res) => {
try {
const repositories = await Repository.find({});
res.status(200).json(repositories)
} catch (error) {
res.status(500).json({message: error.message})
}
});
// GET SELECTED DATA
app.get('/repository/:id', async (req,res) => {
try {
const {id} = req.params;
const repository = await Repository.findById(id);
res.status(200).json(repository)
} catch (error) {
res.status(500).json({message: error.message})
}
});
// UPDATE A DATA
app.put('/repository/:id', async (req, res) => {
try {
const {id} = req.params;
const repository = await Repository.findByIdAndUpdate(id, req.body);
// UPDATE RESPONSES
const newrepository = await Repository.findById(id);
res.status(200).json(newrepository);
} catch (error) {
res.status(500).json({message: error.message})
}
})
// POST A DATA
app.post('/repository', async (req, res) => {
console.log(req.body);
try{
const repository = await Repository.create(req.body);
res.status(200).json(repository);
} catch (error) {
console.log(error.message);
res.status(500).json({message: error.message})
}
})
// DELETE A DATA
app.delete('/repository/:id', async (req, res) => {
try {
const {id} = req.params;
const repository = await Repository.findByIdAndDelete(id);
if (!repository) {
return res.status(404).json({ message: `Cannot find any data with ID : ${id}`})
}
res.status(200).json(repository)
} catch (error) {
res.status(500).json({message: error.message})
}
})
// REPO VIEW COUNTER
app.post('/repository/visit', async (req,res) => {
try {
const { id } = req.body;
await VisitorsQueue.create(req.body);
const AllQueueData = await VisitorsQueue.find({});
await VisitorsQueue.deleteMany({});
// Iterasi melalui setiap objek dalam AllQueueData
for (let i = 0; i < AllQueueData.length; i++) {
const repository = await Repository.findById(AllQueueData[i].id);
await repository.incrementViewCount();
}
const updatedRepository = await Repository.findById(id);
return res.status(200).json({ curretVisitor: updatedRepository.viewcount})
} catch (error) {
res.status(500).json({message: error.message})
}
})
// ===============================================================================================
// ACCOUNT API ROUTER
// ===============================================================================================
// POST A REGISTRANTS DATA
app.post('/account/regist', async (req, res) => {
try{
// Membuat objek baru dengan data dari req.body
const registrantData = {...req.body};
const isExistInQueue = await Registrants.findOne({ email: registrantData.email });
const isExistInData = await Account.findOne({ email: registrantData.email });
if ((!isExistInQueue)&&(!isExistInData)){
// Membuat string acak sepanjang 30 karakter
const tempToken = Array.from({length: 60}, () => Math.floor(Math.random() * 36).toString(36)).join('');
registrantData.temptoken = tempToken
let registfeedback = await sendEmail(registrantData.username, registrantData.temptoken, registrantData.email)
const registrants = await Registrants.create(registrantData);
res.status(200).json({
action: "success",
messageId: registfeedback.messageId
});
} else {
res.status(400).json({ action: 'email already exist'});
console.log('emailnya udah ada masbro')
}
} catch (error) {
console.log(error.message);
res.status(500).json({message: error.message})
}
})
// LOGIN FUNCTION
app.post('/account/login', async (req, res) => {
const { email, password } = req.body;
try {
const token = await Account.login(email, password);
console.log("ini tokennya : ", token)
res.status(200).json({ asthaID : token});
}
catch (error){
// console.log(error.message);
res.status(400).json({"error" : error.message});
}
});
app.get('/account/UserValidation', async (req, res) => {
const cookies = req.cookies;
})
// GET ACCOUNT DATA
app.post('/account/info', async (req , res) => {
const { token ,asthaID } = req.body;
console.log("ini asthaID : ", asthaID)
const account = await Account.findOne({ token: asthaID })
try {
if(account){
const accountInfo = {
status : true,
username : account.username,
email : account.email,
avatar : account.avatar,
role : account.role,
message : "success",
}
res.status(200).json(accountInfo);
} else {
res.status(200).json({
status : false,
message : "Account not found"
});
}
}
catch (error){
res.status(400).json({
status : false,
message : error.message,
});
}
})
// DELETE ACCOUNT (DEBUGGING PURPOSE ONLY)
app.delete('/deleteAccount', async (req, res) => {
const { email } = req.body;
//console.log(email)
try {
const registrant = await Registrants.findOneAndDelete({ email });
if (!registrant) {
return res.status(404).json({ message: 'Akun dengan email tersebut tidak ditemukan.' });
}
res.status(200).json({ message: 'Akun berhasil dihapus.' });
} catch (err) {
res.status(500).json({ message: 'Terjadi kesalahan saat menghapus akun.', error: err.message });
}
});
// EMAIL VERIFICATION
app.get('/account/verify/:email/:temptoken', async (req, res) => {
const {email,temptoken} = req.params;
try {
// Jika akun ditemukan,
let keyEmail = email.toString();
console.log(email)
console.log(temptoken)
const isAccount = await Registrants.findOne({ email: keyEmail });
if (isAccount){
if (isAccount.temptoken == temptoken){
//Mencari token kosong
let token_availability = false
let token = ''
while(!token_availability){
const tokenTemp = Array.from({length: 60}, () => Math.floor(Math.random() * 36).toString(36)).join('');
const isToken = await Account.findOne({ token: tokenTemp });
if (!isToken) {
token_availability = true
token = tokenTemp
}
}
const newaccount = {
username: isAccount.username,
password: isAccount.password,
token : token,
email : isAccount.email,
role : isAccount.role
}
const createAcc = await Account.create(newaccount);
const deleteRegist = await Registrants.findByIdAndDelete(isAccount.id);
console.log("berhasil dipindahkan")
res.status(200).json({ action: "success" });
} else {
return res.json({ action: "failed", message : "Token tidak sesuai" });
}
} else {
return res.json({ action: "failed", message : "Data tidak ditemukan" });
}
} catch (error) {
console.error(error);
return res.status(500).json({action: "failed", message: 'Terjadi kesalahan pada server' });
}
});
// ===============================================================================================
// MONGODB CONNECTION
mongoose.connect(mongodbAPI)
.then(() => {
console.log('connected to mongodb')
app.listen(PORT, () => {
console.log('Node API app is running on port',PORT)
})
}).catch((error) => {
console.log(error)
})
// Email sending test
// app.get('/debug/email', async (req, res) => {
// try {
// let feedback = await sendEmail('developer', 'abcd', '[email protected]');
// res.status(200).json({ action: feedback });
// } catch (error){
// res.status(500).json({ action: "debug email failed" });
// }
// });