-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
148 lines (132 loc) · 4.46 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
const express = require('express');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
const passport = require('passport');
const twitchStrategy = require('passport-twitch').Strategy;
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const moment = require('moment');
const host = process.env.HOST || 'http://localhost:8080';
const port = process.env.PORT || 3000;
const encrypt = require('./server/encryption').encrypt;
const settings = require('./server/settings');
// Set up Mongo.
const mongoose = require('mongoose');
mongoose.Promise = Promise;
require('./server/db')(mongoose);
const User = require('./server/models/user.js');
// Set up force-ssl middleware.
function isSecure(req, res, next) {
if (process.env.NODE_ENV === 'production' && !req.secure && req.get('x-forwarded-proto') !== 'https') {
return res.redirect('https://' + req.get('host'));
}
next();
}
// Setup for Login with Twitch.
const server = express();
server.use(cookieParser());
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({
extended: true
}));
server.use(session({
secret: settings.login.sessionSecret,
resave: false,
saveUninitialized: false,
store: new MongoStore(settings.mongo)
}));
server.use(isSecure);
server.use(express.static('./dist'));
server.use(passport.initialize());
server.use(passport.session());
// Set up Passport.
passport.use(new twitchStrategy({
clientID: settings.twitch.clientId,
clientSecret: settings.twitch.secret,
callbackURL: settings.login.callback,
scope: settings.twitch.scopes
}, (accessToken, refreshToken, profile, done) => {
User.findOrCreate({
id: profile.id,
}, {
id: profile.id,
username: profile.displayName,
email: profile.email,
avatar: profile._json.logo,
last_online: moment(),
access_token: encrypt(accessToken),
refresh_token: encrypt(refreshToken)
}).then((result) => {
return done(null, result);
});
}));
passport.serializeUser(function (user, done) {
// Only store the user id.
done(null, user.doc._id);
});
passport.deserializeUser(function (id, done) {
// Retrieve user by stored user id.
User.findByIdAndUpdate(id, {$set: {last_online: moment()} }, (err, user) => {
if (err) {
console.log('deserializeUser error:', err);
}
done(null, user);
});
});
server.get('/auth/twitch', passport.authenticate('twitch'));
server.get('/auth/callback', passport.authenticate('twitch', {
failureRedirect: '/'
}), (req, res) => {
res.cookie('isLoggedIn', true, {maxAge: 10800, httpOnly: false}).redirect(`${host}/#/watch`);
});
// Set up middleware.
function isAuthenticated(req, res, next) {
if (!req.isAuthenticated()) {
return res.status(401).send({
code: 401,
message: 'Not logged in'
});
}
next();
}
// Set up api routes.
const apiRoutes = express.Router();
const apiHandlers = require('./server/api.js');
apiRoutes.use(isAuthenticated);
apiRoutes.get('/me', apiHandlers.me);
apiRoutes.post('/ping', apiHandlers.ping);
apiRoutes.post('/favorite', apiHandlers.favorite);
apiRoutes.post('/unfavorite', apiHandlers.unfavorite);
apiRoutes.post('/follow', apiHandlers.follow);
apiRoutes.post('/unfollow', apiHandlers.unfollow);
server.use('/api', apiRoutes);
// Set up data routes.
const dataRoutes = express.Router();
const dataHandlers = require('./server/data.js');
dataRoutes.get('/stats', dataHandlers.stats);
dataRoutes.get('/searchGames', dataHandlers.searchGames);
dataRoutes.get('/searchStreams', dataHandlers.searchStreams);
dataRoutes.get('/userIsHosting', dataHandlers.userIsHosting);
dataRoutes.get('/getChannelsByUser', dataHandlers.getChannelsByUser);
dataRoutes.get('/getUserIdByUserName', dataHandlers.getUserIdByUserName);
dataRoutes.get('/getUserChannels', dataHandlers.getUserChannels);
dataRoutes.get('/getChannelLiveStatus', dataHandlers.getChannelLiveStatus);
dataRoutes.get('/getPopularGames', dataHandlers.getPopularGames);
dataRoutes.get('/getStreamsByGame', dataHandlers.getStreamsByGame);
server.use('/data', dataRoutes);
// Home route.
server.get('/', (req, res) => {
if (req.isAuthenticated()) {
return res.cookie('isLoggedIn', true, {maxAge: 10800, httpOnly: false}).redirect(`${host}/#/watch`);
}
return res.redirect(host);
});
server.get('/logout', (req, res) => {
req.logout();
res.clearCookie('isLoggedIn');
res.redirect('/#/?loggedOut=true');
});
// Start the server.
server.listen(port, () => {
console.log(`server operating on port ${port}`);
});