-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
419 lines (391 loc) · 12.6 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
const express = require("express");
const app = express();
const cors = require("cors");
const nodemailer = require('nodemailer')
const cookieParser = require('cookie-parser')
const jwt = require('jsonwebtoken');
require('dotenv').config();
const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb');
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
const port = process.env.PORT || 5000;
// middlewares
app.use(
cors({
origin:["http://localhost:5173","https://picotask-rush.web.app","https://picotask-rush.firebaseapp.com"],
credentials:true,
}));
app.use(express.json());
app.use(cookieParser())
// send email
const sendEmail = (emailAddress, emailData) => {
const transporter = nodemailer.createTransport({
service: 'gmail',
host: 'smtp.gmail.com',
port: 587,
secure: false,
auth: {
user: process.env.TRANSPORTER_EMAIL,
pass: process.env.TRANSPORTER_PASS,
},
})
// verify connection
transporter.verify(function (error, success) {
if (error) {
console.log(error)
} else {
console.log('Server is ready to take our messages')
}
})
const mailBody = {
from: `"picoTask" <${process.env.TRANSPORTER_EMAIL}>`,
to: emailAddress,
subject: emailData.subject,
html: emailData.message,
}
transporter.sendMail(mailBody, (error, info) => {
if (error) {
console.log(error)
} else {
console.log('Email Sent: ' + info.response)
}
})
}
// mongodb codes
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@cluster0.43teffq.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0`;
// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
}
});
const cookieOptions = {
httpOnly:true,
sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'strict',
secure: process.env.NODE_ENV === 'production'? true : false,
}
async function run() {
try {
// Connect the client to the server (optional starting in v4.7)
// await client.connect();
// collections
const userCollection = client.db("picoTaskDB").collection("users");
const taskCollection = client.db("picoTaskDB").collection("tasks");
const submissionCollection = client.db("picoTaskDB").collection("submission");
const paymentCollection = client.db("picoTaskDB").collection("payments");
const withdrawCollection = client.db("picoTaskDB").collection("withdraw");
const notificationCollection = client.db("picoTaskDB").collection("notification");
// jwt related API
app.post("/jwt", async(req,res)=>{
const user = req.body;
const token = jwt.sign(user,process.env.ACCESS_TOKEN_SECRET,{
expiresIn:"1h"});
res
.cookie('token', token,cookieOptions)
.send({ success: true })
})
// middlewares
const verifyToken = (req,res,next)=>{
// console.log("inside verifytoken",req.headers.authorization);
if(!req.headers.authorization){
return res.status(401).send({message:"Unauthorized Access"});
}
const token = req.headers.authorization.split(" ")[1];
jwt.verify(token,process.env.ACCESS_TOKEN_SECRET,(err,decoded)=>{
if(err){
return res.status(400).send({message:"Invalid token"});
}
req.decoded = decoded;
next();
})
}
// check if user is admin or not
const verifyAdmin = async(req,res,next)=>{
const email = req.decoded.email;
const query = {email:email};
const user = await userCollection.findOne(query);
const isAdmin = user?.role ==="admin";
if(!isAdmin){
return res.status(403).send({message:"Forbidden Admin Access"});
}
next();
}
// check if user is creator or not
const verifyCreator = async(req,res,next)=>{
const email = req.decoded.email;
const query = {email:email};
const user = await userCollection.findOne(query);
const isCreator = user?.role ==="taskCreator";
if(!isCreator){
return res.status(403).send({message:"Forbidden Creator Access"});
}
next();
}
// task related api
// get all submitted tasks
app.get("/submission", async(req,res)=>{
const result = await submissionCollection.find().toArray();
res.send(result);
})
// get all tasks
app.get("/tasks", async(req,res)=>{
const result = await taskCollection.find().toArray();
res.send(result);
})
// delete task
app.delete("/tasks/:id", verifyToken,verifyAdmin, async(req,res)=>{
const id =req.params.id;
const query = {_id: new ObjectId(id)};
const result = await taskCollection.deleteOne(query);
res.send(result);
})
app.post("/submission", async(req,res)=>{
const submittedTask = req.body;
// console.log(submittedTask);
const result = await submissionCollection.insertOne(submittedTask);
// send email to worker
sendEmail(submittedTask?.user, {
subject: 'Submission Successful!',
message: `You've successfully submitted a task through picoTask.`,
})
// send email to creator
sendEmail(submittedTask?.creatorEmail, {
subject: 'Your task has submitted!',
message: `Get ready to welcome ${submittedTask?.creatorEmail}.`,
})
res.send(result);
})
app.post("/tasks",verifyToken, async(req,res)=>{
const task = req.body;
const result = await taskCollection.insertOne(task);
res.send(result);
})
// get specific task for submission
app.get("/tasks/:id", async(req,res)=>{
const id = req.params.id;
const query = {_id: new ObjectId(id)};
const result = await taskCollection.findOne(query);
res.send(result);
})
// update task information
app.put("/tasks/:id", verifyToken,verifyCreator, async(req,res)=>{
const id = req.params.id;
const filter = {_id: new ObjectId(id)};
const options = {upsert : true};
const updatedInfo = req.body;
const updated = {
$set:{
title : updatedInfo.title,
quantity: updatedInfo.quantity,
details: updatedInfo.details,
}
}
const result = await taskCollection.updateOne(filter,updated,options);
res.send(result);
})
// create payment intent
app.post('/create-payment-intent', verifyToken, async (req, res) => {
const {price} = req.body;
const amount = parseFloat(price*100);
if (!price || amount < 1) return
// generate clientSecret
const { client_secret } = await stripe.paymentIntents.create({
amount: amount,
currency: 'usd',
automatic_payment_methods: {
enabled: true,
},
})
// send client secret as response
res.send({ clientSecret: client_secret })
})
// get all payments
app.get("/payment",verifyToken,verifyCreator, async(req,res)=>{
const result = await paymentCollection.find().toArray();
res.send(result);
})
// Save a payment data in db
app.post('/payment', verifyToken, verifyCreator, async (req, res) => {
const paymentData = req.body
const result = await paymentCollection.insertOne(paymentData)
res.send(result)
})
// user related api
// get all users
app.get("/users", async(req,res)=>{
const result = await userCollection.find().toArray();
res.send(result);
})
// get specific user
app.get('/users/:email', async (req, res) => {
const email = req.params.email
const result = await userCollection.findOne({ email })
res.send(result)
})
// verifyadminorNot
app.get("/users/admin/:email", verifyToken, async(req,res)=>{
const email = req.params.email;
if(email !==req.decoded.email){
return res.status(403).send({message:"Forbidden Access"});
}
const query = {email:email};
const user = await userCollection.findOne(query);
let admin =false;
if(user){
admin = user?.role==="admin";
}
res.send({admin});
})
// delete user
app.delete("/users/:id", verifyToken,verifyAdmin, async(req,res)=>{
const id =req.params.id;
const query = {_id: new ObjectId(id)};
const result = await userCollection.deleteOne(query);
res.send(result);
})
//update a user role
app.patch('/users/update/:email', verifyToken,verifyAdmin, async (req, res) => {
const email = req.params.email;
const user = req.body;
const query = { email };
const updateDoc = {
$set: { ...user, timestamp: Date.now() },
}
const result = await userCollection.updateOne(query, updateDoc)
res.send(result)
})
// post all users
app.put('/users', async (req, res) => {
const user = req.body;
console.log(user);
const query = { email: user?.email };
// check if user already exists in db
const isExist = await userCollection.findOne(query)
if (isExist) {
if (user.status === 'Requested') {
// if existing user try to change his role
const result = await userCollection.updateOne(query, {
$set: { status: user?.status },
})
return res.send(result)
} else {
// if existing user login again
return res.send(isExist)
}
}
// save user for the first time
const options = { upsert: true }
const updateDoc = {
$set: {
...user,
timestamp: Date.now(),
},
}
const result = await userCollection.updateOne(query, updateDoc, options)
// welcome message to email
sendEmail(user?.email, {
subject: 'Welcome to PicoTask Rush website!',
message: `Hope you will find a lot of resources which you find`,
})
res.send(result)
})
// notificaiton related API
app.get("/notification", async(req,res)=>{
let query={};
if(req.query?.email){
query={email:req.query.email}
}
const result = await notificationCollection.find(query).toArray();
res.send(result);
})
// Admin Statistics
app.get('/admin-stat', async (req, res) => {
const coinDetails = await submissionCollection
.find(
{},
{
projection: {
payable:1,
},
}
)
.toArray()
const totalUsers = await userCollection.countDocuments()
const totalPayments = await paymentCollection.countDocuments()
const totalCoins = coinDetails.reduce(
(sum, payAmount) => sum + parseFloat(payAmount.payable),
0
)
res.send({
totalUsers,
totalCoins,
totalPayments,
})
})
// Task creator Statistics
app.get('/creator-statistics', async (req, res) => {
const coinDetails = await submissionCollection
.find(
{},
{
projection: {
payable:1,
},
}
)
.toArray()
const totalUsers = await userCollection.countDocuments()
const totalPayments = await paymentCollection.countDocuments()
const totalCoins = coinDetails.reduce(
(sum, payAmount) => sum + parseFloat(payAmount.payable),
0
)
res.send({
totalUsers,
totalCoins,
totalPayments,
})
})
// Worker Statistics
app.get('/worker-stat',async (req, res) => {
const coinDetails = await submissionCollection
.find(
{},
{
projection: {
payable:1,
},
}
)
.toArray()
const totalSubmission = await submissionCollection.countDocuments()
const totalCoins = coinDetails.reduce(
(sum, payAmount) => sum + parseFloat(payAmount.payable),
0
)
res.send({
totalCoins,
totalSubmission,
})
})
app.post("/notification",async(req,res)=>{
const notificationData = req.body;
const result = await notificationCollection.insertOne(notificationData);
res.send(result);
})
// Send a ping to confirm a successful connection
// await client.db("admin").command({ ping: 1 });
console.log("Pinged your deployment. You successfully connected to MongoDB!");
} finally {
// Ensures that the client will close when you finish/error
// await client.close();
}
}
run().catch(console.dir);
app.get("/",(req,res)=>{
res.send("PicoTask Rush server is Running")
})
app.listen(port,()=>{
console.log(`PicoTash Rush Running on Port:${port}`);
})