forked from clintonwoo/hackernews-react-graphql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
182 lines (162 loc) · 4.56 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
import dotenv from 'dotenv/config';
import express from 'express';
import cookieParser from 'cookie-parser';
import session from 'express-session';
import nextApp from 'next';
import passport from 'passport';
import LocalStrategy from 'passport-local';
import bodyParser from 'body-parser';
import {
graphqlExpress,
graphiqlExpress,
} from 'apollo-server-express';
import Schema from './data/Schema';
import {
seedCache,
} from './data/HNDataAPI';
import {
Comment,
Feed,
NewsItem,
User,
} from './data/Models';
import {
appPath,
APP_PORT,
APP_URI,
graphQLPath,
graphiQLPath,
GRAPHQL_URL,
dev,
} from './config';
// Seed the in-memory data using the HN api
const delay = dev ? /* 1000 * 60 * 1 1 minute */ 0 : 0;
seedCache(delay);
const app = nextApp({ dir: appPath, dev });
const handle = app.getRequestHandler();
app.prepare()
.then(() => {
const server = express();
/* BEGIN PASSPORT.JS AUTHENTICATION */
passport.use(new LocalStrategy(
{
usernameField: 'id',
},
async (username, password, done) => {
const user = await User.getUser(username);
// if (err) return done(err);
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
if (!(await User.validPassword(username, password))) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user);
},
));
/*
In this example, only the user ID is serialized to the session,
keeping the amount of data stored within the session small. When
subsequent requests are received, this ID is used to find the user,
which will be restored to req.user.
*/
passport.serializeUser((user, cb) => {
cb(null, user.id);
});
passport.deserializeUser(async (id, cb) => {
const user = await User.getUser(id);
cb(null, user || null);
});
server.use(cookieParser('mysecret'));
server.use(session({
secret: 'mysecret',
resave: false,
rolling: true,
saveUninitialized: false,
cookie: { maxAge: 1000 * 60 * 60 * 24 * 7 }, // Requires https: secure: false
}));
server.use(passport.initialize());
server.use(bodyParser.urlencoded({ extended: false }));
server.use(passport.session());
server.post('/login', (req, res, next) => {
req.session.returnTo = req.body.goto;
next();
}, passport.authenticate(
'local',
{
successReturnToOrRedirect: '/',
failureRedirect: '/login?how=unsuccessful',
},
));
server.post('/register', async (req, res, next) => {
if (!req.user) {
try {
await User.registerUser({
id: req.body.id,
password: req.body.password,
});
req.session.returnTo = `/user?id=${req.body.id}`;
} catch (err) {
req.session.returnTo = `/login?how=${err.code}`;
}
} else req.session.returnTo = '/login?how=user';
next();
}, passport.authenticate(
'local',
{
successReturnToOrRedirect: '/',
failureRedirect: '/login?how=unsuccessful',
},
));
server.get('/logout', (req, res) => {
req.logout();
res.redirect('/');
});
/* END PASSPORT.JS AUTHENTICATION */
/* BEGIN GRAPHQL */
server.use(graphQLPath, bodyParser.json(), graphqlExpress(
(req) => {
const userId = req.user && req.user.id;
return {
schema: Schema,
rootValue: { req },
context: {
Feed,
NewsItem,
Comment,
User,
userId,
},
debug: dev,
};
},
));
server.use(graphiQLPath, graphiqlExpress({
endpointURL: graphQLPath,
}));
/* END GRAPHQL */
/* BEGIN EXPRESS ROUTES */
// This is how to render a masked route with NextJS
// server.get('/p/:id', (req, res) => {
// const actualPage = '/post';
// const queryParams = { id: req.params.id };
// app.render(req, res, actualPage, queryParams);
// });
server.get('/news', (req, res) => {
const actualPage = '/';
app.render(req, res, actualPage);
});
server.get('*', (req, res) => handle(req, res));
/* END EXPRESS ROUTES */
server.listen(APP_PORT, (err) => {
if (err) throw err;
console.log(`> App ready on ${APP_URI}`);
console.log(`> GraphQL Ready on ${GRAPHQL_URL}`);
console.log(`Dev: ${dev}`);
});
})
.catch((ex) => {
console.error(ex.stack);
process.exit(1);
});
export default app;