-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
232 lines (177 loc) · 6.04 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
require('dotenv').config()
const express = require('express');
const server = express();
const mongoose = require('mongoose');
const cors = require('cors');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const crypto = require('crypto');
const jwt = require('jsonwebtoken');
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const cookieParser = require('cookie-parser');
const { createProduct } = require('./controller/Product');
const productsRouter = require('./routes/Products');
const categoriesRouter = require('./routes/Categories');
const brandsRouter = require('./routes/Brands');
const usersRouter = require('./routes/Users');
const authRouter = require('./routes/Auth');
const cartRouter = require('./routes/Cart');
const ordersRouter = require('./routes/Order');
const { User } = require('./model/User');
const { isAuth, sanitizeUser, cookieExtractor } = require('./services/common');
const path = require('path');
const { Order } = require('./model/Order');
const { env } = require('process');
console.log(process.env)
// send mail with defined transport object
// Webhook
// TODO: we will capture actual order after deploying out server live on public URL
const endpointSecret = process.env.ENDPOINT_SECRET;
server.post('/webhook', express.raw({type: 'application/json'}), async (request, response) => {
const sig = request.headers['stripe-signature'];
let event;
try {
event = stripe.webhooks.constructEvent(request.body, sig, endpointSecret);
} catch (err) {
response.status(400).send(`Webhook Error: ${err.message}`);
return;
}
// Handle the event
switch (event.type) {
case 'payment_intent.succeeded':
const paymentIntentSucceeded = event.data.object;
const order = await Order.findById(paymentIntentSucceeded.metadata.orderId);
order.paymentStatus = 'received';
await order.save()
break;
// ... handle other event types
default:
console.log(`Unhandled event type ${event.type}`);
}
// Return a 200 response to acknowledge receipt of the event
response.send();
});
// JWT options
const opts = {};
opts.jwtFromRequest = cookieExtractor;
opts.secretOrKey = process.env.JWT_SECRET_KEY; // TODO: should not be in code;
//middlewares
server.use(express.static(path.resolve(__dirname,'build')))
server.use(cookieParser());
server.use(
session({
secret: process.env.SESSION_KEY,
resave: false, // don't save session if unmodified
saveUninitialized: false, // don't create session until something stored
})
);
server.use(passport.authenticate('session'));
server.use(
cors({
exposedHeaders: ['X-Total-Count'],
})
);
server.use(express.json()); // to parse req.body
server.use('/products', isAuth(), productsRouter.router);
// we can also use JWT token for client-only auth
server.use('/categories', isAuth(), categoriesRouter.router);
server.use('/brands', isAuth(), brandsRouter.router);
server.use('/users', isAuth(), usersRouter.router);
server.use('/auth', authRouter.router);
server.use('/cart', isAuth(), cartRouter.router);
server.use('/orders', isAuth(), ordersRouter.router);
// this line we add to make react router work in case of other routes doesnt match
server.get('*', (req, res) => res.sendFile(path.resolve('build', 'index.html')));
// Passport Strategies
passport.use(
'local',
new LocalStrategy(
{usernameField:'email'},
async function (email, password, done) {
// by default passport uses username
console.log({email,password})
try {
const user = await User.findOne({ email: email });
console.log(email, password, user);
if (!user) {
return done(null, false, { message: 'invalid credentials' }); // for safety
}
crypto.pbkdf2(
password,
user.salt,
310000,
32,
'sha256',
async function (err, hashedPassword) {
if (!crypto.timingSafeEqual(user.password, hashedPassword)) {
return done(null, false, { message: 'invalid credentials' });
}
const token = jwt.sign(sanitizeUser(user), process.env.JWT_SECRET_KEY);
done(null, {id:user.id, role:user.role, token}); // this lines sends to serializer
}
);
} catch (err) {
done(err);
}
})
);
passport.use(
'jwt',
new JwtStrategy(opts, async function (jwt_payload, done) {
console.log({ jwt_payload });
try {
const user = await User.findById(jwt_payload.id);
if (user) {
return done(null, sanitizeUser(user)); // this calls serializer
} else {
return done(null, false);
}
} catch (err) {
return done(err, false);
}
})
);
// this creates session variable req.user on being called from callbacks
passport.serializeUser(function (user, cb) {
console.log('serialize', user);
process.nextTick(function () {
return cb(null, { id: user.id, role: user.role });
});
});
// this changes session variable req.user when called from authorized request
passport.deserializeUser(function (user, cb) {
console.log('de-serialize', user);
process.nextTick(function () {
return cb(null, user);
});
});
// Payments
// This is your test secret API key.
const stripe = require("stripe")(process.env.STRIPE_SERVER_KEY);
server.post("/create-payment-intent", async (req, res) => {
const { totalAmount, orderId } = req.body;
// Create a PaymentIntent with the order amount and currency
const paymentIntent = await stripe.paymentIntents.create({
amount: totalAmount*100, // for decimal compensation
currency: "inr",
automatic_payment_methods: {
enabled: true,
},
metadata:{
orderId
}
});
res.send({
clientSecret: paymentIntent.client_secret,
});
});
main().catch((err) => console.log(err));
async function main() {
await mongoose.connect(process.env.MONGODB_URL);
console.log('database connected');
}
server.listen(process.env.PORT, () => {
console.log('server started');
});