-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.ts
278 lines (241 loc) · 7.68 KB
/
server.ts
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
import express from "express";
import dotenv from "dotenv";
import mongoose from "mongoose";
import cors from "cors";
const app = express();
// load environment variablesd
dotenv.config({ path: `.env` });
if (!process.env.NODE_ENV) {
console.error(`NODE_ENV is not set.\n`);
process.exit();
}
dotenv.config({ path: `.env.${process.env.NODE_ENV!.replace(" ", "")}` });
import { frontendPath } from "./config";
let PORT = process.env.SERVER_PORT;
if (process.env.NODE_ENV == 'test') PORT = "9045";
const MONGO_PREFIX = process.env.MONGO_DB_PREFIX ?? "mongodb+srv";
const MONGO_HOST = process.env.MONGO_DB_HOST ?? "cluster0.vsneo.mongodb.net";
const MONGO_URI = ((): string => {
if (process.env.NODE_ENV == 'development') return `mongodb://localhost:27017/housing-database`;
if (process.env.NODE_ENV == 'test') return `mongodb://localhost:27017/housing-database-test`;
// production cloud mongodb cluster
return `${MONGO_PREFIX}://${process.env.MONGO_DB_CLUSTER_USERNAME}:${process.env.MONGO_DB_PASSWORD}@${MONGO_HOST}/housing-database?retryWrites=true&w=majority&authSource=admin`;
})()
// setup middleware
import bodyParser from "body-parser";
let whitelisted_ips = [
frontendPath(),
...(
Object.keys(process.env)
.filter((key_: string) => key_.substring(0, 13) == "WHITELIST_IP_")
.map((key_: string) => `${process.env[key_]!}:${process.env.PORT}`)
)
]
console.log(whitelisted_ips)
app.use(express.json());
app.use(
cors({
origin: whitelisted_ips,
credentials: true,
})
);
app.use(bodyParser.urlencoded({ extended: false }));
// Passport CAS Auth
import passport from "passport";
import session from "express-session";
import mongoStoreFactory from 'connect-mongo';
import CasAuthRouter from "./Authentication/casauth";
import LocalAuthRouter from "./Authentication/localauth";
const MongoStore = mongoStoreFactory(session);
app.use(
session({
secret: process.env.SESSION_SECRET as string,
resave: false,
saveUninitialized: false,
store: new MongoStore({
mongooseConnection: mongoose.connection
})
})
);
app.use(passport.initialize());
app.use(passport.session());
app.use("/auth", CasAuthRouter);
app.use("/auth", LocalAuthRouter);
// Stripe Payment Endpoint Processing
import stripeRouter from './vendors/Stripe'
app.use("/payments", stripeRouter);
import { NotificationsAPI } from './modules/NotificationsAPI'
import { StudentModel, Student } from './GQL/entities/Student'
import { LandlordModel, Landlord } from './GQL/entities/Landlord'
import { DocumentType } from '@typegoose/typegoose'
import chalk from 'chalk'
// test webpush
app.post('/subscribe/:user_type/:id', async (req, res) => {
console.log(chalk.bgBlue(`👉 /subscribe`))
let type_: string = req.params.user_type;
if (type_ != "student" && type_ != "landlord") {
console.error(`Invalid user_type provided for subscription`);
res.json({
success: false,
error: `Invalid user type`
})
return;
}
let subscription = req.body;
let user_id = req.params.id
if (type_ == "student") {
let student_: DocumentType<Student> = await StudentModel.findById(user_id) as DocumentType<Student>;
if (student_) {
NotificationsAPI.getSingleton().addPushSubscription(student_, subscription)
res.json({ succes: true })
return;
}
else {
res.json({ success: false, error: "Problem adding subscription" })
return;
}
}
if (type_ == "landlord") {
let landlord_: DocumentType<Landlord> = await LandlordModel.findById(user_id) as DocumentType<Landlord>;
if (landlord_) {
NotificationsAPI.getSingleton().addPushSubscription(landlord_, subscription);
res.json({ success: true });
return;
}
else {
res.json({ success: false, error: "Problem adding subscription" })
return;
}
}
/*
console.log(`Subscription`, subscription);
console.log(`User id`, user_id)
let student_: DocumentType<Student> = await StudentModel.findById(user_id) as DocumentType<Student>;
console.log(student_);
if (student_) {
NotificationsAPI.getSingleton().addPushSubscription(student_, subscription);
}
*/
/*
console.log(`Subscription`)
console.log(subscription)
res.status(201).json({});
const payload = JSON.stringify({
title: `push test`
})
*/
// Send a push notification to the subscription
// webpush.sendNotification(subscription, payload)
// .catch(err => console.error(err))
});
import { awsRouter } from "./vendors/aws_s3";
app.use("/vendors/aws_s3", awsRouter);
// SendGrid
import sgMail from '@sendgrid/mail'
sgMail.setApiKey(process.env.SENDGRID_API_KEY as string)
const connectMongo = () =>
// connect to MongoDB via mongoose
new Promise((res, rej) =>
mongoose.connect(
MONGO_URI,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: true,
},
// mongoose connection callback
(err: any) => {
if (err) {
rej(err);
} else {
res(undefined);
}
}
)
);
// Twilio Router
import smsRouter from './routers/twilio_smsVerify'
app.use('/vendor/twilio', smsRouter)
import "reflect-metadata"
import { execute, subscribe } from 'graphql';
import { ApolloServer } from "apollo-server-express"
import { buildSchema } from "type-graphql";
import * as http from "http";
import {
StudentResolver,
OwnershipResolver,
LandlordResolver,
FeedbackResolver,
InstitutionResolver,
LeaseDocumentResolver,
LeaseResolver,
PropertyResolver,
FeedResolver,
StudentStatisticsResolver,
LandlordStatisticsResolver
} from "./GQL/resolvers"
import { ObjectIdScalar } from "./GQL/entities";
import { ObjectId } from 'mongodb'
import webpush from 'web-push';
import { SubscriptionServer } from 'subscriptions-transport-ws';
const StartServer = async (): Promise<{
server: http.Server;
apolloServer: ApolloServer;
}> => {
const schema = await buildSchema({
resolvers: [StudentResolver,
OwnershipResolver,
LandlordResolver,
InstitutionResolver,
PropertyResolver,
LeaseDocumentResolver,
LeaseResolver,
FeedbackResolver,
FeedResolver,
StudentStatisticsResolver,
LandlordStatisticsResolver],
emitSchemaFile: true,
validate: true,
scalarsMap: [{ type: ObjectId, scalar: ObjectIdScalar }],
});
const apolloServer = new ApolloServer({
schema,
context: ({ req, res }) => ({
getSession: () => req.session,
req, res
}),
playground:
process.env.NODE_ENV === 'production' ? false
: { settings: { 'request.credentials': "same-origin" } }
});
apolloServer.applyMiddleware({ app, cors: false });
try {
await connectMongo();
console.log(`✔ Successfully connect to MongoDB instance.`);
} catch (err) {
console.error(`❌ Error connecting to mongoose.`);
console.error(err);
process.exit(1);
}
// web-push
if (process.env.VAPID_PUBLIC != undefined && process.env.VAPID_PRIVATE != undefined) {
webpush.setVapidDetails('mailto:[email protected]',
process.env.VAPID_PUBLIC as string,
process.env.VAPID_PRIVATE as string
)
}
const server = app.listen(PORT, async () => {
console.log(`🚀 Server running on port ${PORT}`);
new SubscriptionServer({
execute,
subscribe,
schema,
}, {
server: server,
path: '/graphql',
});
});
return { server, apolloServer };
};
const server = StartServer();
export { app, connectMongo, server, MONGO_URI };