-
Notifications
You must be signed in to change notification settings - Fork 167
/
Copy pathserver.js
245 lines (195 loc) · 6.03 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
import 'babel-polyfill';
import 'isomorphic-unfetch';
import config from 'config';
import path from 'path';
import fs from 'fs';
import express from 'express';
import bodyParser from 'body-parser';
import jwt from 'jsonwebtoken';
import cookieParser from 'cookie-parser';
import webConfig from './webConfig';
import { StaticRouter } from 'react-router';
import { InMemoryCache } from 'apollo-cache-inmemory';
import React from 'react';
import ReactDOM from 'react-dom/server';
import { ApolloProvider, getDataFromTree } from 'react-apollo';
import { ApolloClient } from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import mongoose from 'mongoose';
import cors from 'cors';
import { graphiqlExpress, graphqlExpress } from 'apollo-server-express';
import { makeExecutableSchema } from 'graphql-tools';
import nodemailer from 'nodemailer';
import hbs from 'nodemailer-express-handlebars';
import { Helmet } from 'react-helmet';
import fileUpload from 'express-fileupload';
import randomstring from 'randomstring';
import AppComponent from './src/app';
import HTML from './src/helpers/renderer';
import { typeDefs } from './src/schema';
import { resolvers } from './src/resolvers';
import User from './src/models/User';
// Connect MongoDB
mongoose.connect(config.get('dbString'), { useNewUrlParser: true }).then(() => {
console.log('Connection to DB successful');
}).catch(err => {
console.log(`Connection to DB Error: ${err}`);
});
// check env vars
require('./config')();
const app = express();
const PORT = process.env.PORT || 3000;
app.use(
cors({
origin: `${webConfig.siteURL}`,
credentials: true
})
);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser())
app.use("/", express.static("build/public"));
app.get('/user-uploads/:file', function (req, res) {
const file_name = req.params.file;
const get_file = path.resolve('./user-uploads/profile-images/' + req.params.file);
const current_files = fs.readdirSync('./user-uploads/profile-images/');
const fileExists = current_files.includes(file_name);
if (fileExists) {
res.status(200).sendFile(get_file);
} else {
res.status(404).send('No File Found!');
}
});
// JWT Middelware
app.use(async (req, res, next) => {
const token = req.cookies.token ? req.cookies.token : null;
if (token !== null) {
try {
const currentUser = await jwt.verify(token, config.get('jwtPrivateKey'));
req.currentUser = currentUser;
} catch (err) {
// console.error(err);
res.clearCookie('token');
}
}
next();
});
const schema = makeExecutableSchema({
typeDefs,
resolvers
});
// create Graphiql app
app.use('/graphiql', graphiqlExpress({
endpointURL: '/graphql'
}));
// connect schema with graphql
app.use('/graphql',
bodyParser.json(),
graphqlExpress(({ currentUser }) => ({
schema,
context: {
User,
currentUser
}
}))
);
app.get(['*/:param', '*'], (req, res) => {
const URL_Param = req.params.param ? req.params.param : null;
const client = new ApolloClient({
ssrMode: true,
// Remember that this is the interface the SSR server will use to connect to the
// API server, so we need to ensure it isn't firewalled, etc
link: createHttpLink({
uri: `${webConfig.siteURL}/graphql`,
credentials: 'same-origin',
headers: {
cookie: req.header('Cookie'),
},
}),
cache: new InMemoryCache(),
});
const context = {
URL_Param
};
// The client-side App will instead use <BrowserRouter>
const App = (
<ApolloProvider client={client}>
<StaticRouter location={req.url} context={context}>
<AppComponent />
</StaticRouter>
</ApolloProvider>
);
// Handle queries etc.. before sending raw html
getDataFromTree(App).then(() => {
const content = ReactDOM.renderToString(App);
const helmet = Helmet.renderStatic();
const initialState = client.extract();
const html = <HTML content={content} state={initialState} helmet={helmet} />;
res.status(200);
res.send(`<!doctype html>\n${ReactDOM.renderToStaticMarkup(html)}`);
res.end();
});
});
app.post('/password-reset', (req, response) => {
var mailer = nodemailer.createTransport({
host: config.get('mailServer.host'),
auth: {
user: config.get('mailServer.auth.user'),
pass: config.get('mailServer.auth.pass')
}
});
mailer.use('compile', hbs({
viewPath: 'build/public/assets/email_templates',
extName: '.hbs'
}));
mailer.sendMail({
from: config.get('mailServer.from'),
to: req.body.email,
subject: config.get('mailServer.subject'),
template: 'passwordReset',
context: {
email: req.body.email,
password: req.body.generatedPassword
}
}, function (err, res) {
if (err) {
// console.log(err)
return response.status(500).send('500 - Internal Server Error')
}
response.status(200).send('200 - The request has succeeded.')
});
});
app.use(fileUpload());
const getFileType = (fileType) => {
let ext;
if (fileType == 'image/jpeg') {
ext = '.jpg';
} else if (fileType == 'image/png') {
ext = '.png';
}
return ext;
}
app.post('/upload', function (req, res) {
if (!req.files) return res.status(400).send('No files were uploaded.');
var current_files = fs.readdirSync('./user-uploads/profile-images/');
let profilePic = req.files.selectedFile;
let file_ext = getFileType(profilePic.mimetype);
let tempFileName = randomstring.generate(21) + file_ext;
const fileExists = current_files.includes(tempFileName);
while (fileExists) {
let string = randomstring.generate(21);
tempFileName = string + file_ext;
if (!current_files.includes(tempFileName)) {
break;
}
}
let send_filePath = './user-uploads/profile-images/' + tempFileName;
profilePic.mv(send_filePath, function (err) {
if (err) return res.status(500).send(err);
const res_dataObj = {
"newFileName": tempFileName
}
res.send(res_dataObj);
});
});
app.listen(PORT, () => console.log(`App running on port ${PORT}`));