forked from cs4241-21a/a3-persistence
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
178 lines (153 loc) · 5.63 KB
/
app.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
const express = require('express');
const passport = require('passport');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const FileStore = require('session-file-store')(session);
const mongoose = require('mongoose');
const path = require('path');
const bcrypt = require('bcrypt');
const GitHubStrategy = require('passport-github2').Strategy;
const config = require('./config');
const app = express();
const port = process.env.PORT || config.port;
const User = require('./models').User;
const Flight = require('./models').Flight;
// middleware
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(session({
name: 'sid',
secret: config.sessionSecret,
saveUninitialized: false,
resave: false,
cookie: {
httpOnly: true,
sameSite: true,
maxAge: 24 * 60 * 60 * 1000
},
store: new FileStore({logFn: function() {}})
}));
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(obj, done) {
done(null, obj);
});
passport.use(new GitHubStrategy({
clientID: config.GithubClientID,
clientSecret: config.GithubClientSecret,
callbackURL: config.GithubCallbackURL
},
function(accessToken, refreshToken, profile, done) {
User.findOrCreate({ githubId: profile.id }, function (err, user) {
return done(err, user._id);
});
}
));
mongoose.connect(config.dbConnection, { useNewUrlParser: true, useUnifiedTopology: true });
function auth(req, res, next) {
if (typeof req.session.userId !== 'undefined' && req.session.userId !== null) {
next();
} else {
res.json({code: 403, msg: "not logged in"});
}
}
app.get('/auth/github', passport.authenticate('github', { scope: [ 'profile' ] }));
app.get('/auth/github/callback',
passport.authenticate('github', { failureRedirect: '/login.html' }),
function(req, res) {
req.session.userId = req.user;
res.redirect('/');
}
);
app.get('/getUpcoming', auth, function (req, res) {
Flight.find({owner: req.session.userId}, function (err, docs) {
res.json(docs.filter((item) => new Date(item.date).valueOf() >= new Date().valueOf()));
});
});
app.get('/getPast', auth, function (req, res) {
Flight.find({owner: req.session.userId}, function (err, docs) {
res.json(docs.filter((item) => new Date(item.date).valueOf() < new Date().valueOf()));
});
});
app.get('/logout', auth, function (req, res) {
req.logout();
req.session.destroy(function(err) {
res.clearCookie('sid');
res.redirect('/login.html');
});
});
app.post('/login', function (req, res) {
User.findOne({username: req.body.username}, function(err, result) {
if (result != null) {
bcrypt.compare(req.body.password, result.password, function(err, ok) {
if (ok) {
req.session.userId = result._id;
res.json({code: 200, msg: "success"});
} else {
res.json({code: 400, msg: "invalid credentials"});
}
});
} else {
res.json({code: 400, msg: "invalid credentials"});
}
});
});
app.post('/reg', function (req, res) {
if (req.body.username === "" || req.body.password === "")
res.json({code: 401, msg: "username or password cannot be empty"});
else {
User.findOne({username: req.body.username}, function (err, result) {
if (result != null) {
res.json({code: 401, msg: "The username already exists."});
} else {
const user = {};
user.username = req.body.username;
user.password = bcrypt.hashSync(req.body.password, 10);
const newUser = new User(user);
newUser.save(function (err, docs) {
req.session.userId = docs._id;
res.json({code: 200, msg: "success"});
});
}
});
}
});
app.post('/add', auth, function (req, res) {
req.body.owner = req.session.userId;
const newFlight = new Flight(req.body);
newFlight.save().then(r => {
res.json({code: 200, msg: 'success'});
});
});
app.post('/del', auth, function (req, res) {
Flight.findOneAndRemove({'_id': req.body.id, 'owner': req.session.userId}, function (err, docs) {
res.json({code: 200, msg: 'success'});
});
});
app.post('/queryFlight', auth, function (req, res) {
Flight.findOne({'_id': req.body.id, 'owner': req.session.userId}, function (err, result) {
if (result != null) {
res.json({code: 200, msg: 'success', result});
} else {
res.json({code: 400, msg: 'The specific entry does not exist or not belong to the user.'});
}
});
});
app.post('/editFlight', auth, function (req, res) {
Flight.findOneAndUpdate({'_id': req.body.id, 'owner': req.session.userId}, req.body, function (err, result) {
if (result != null) {
res.json({code: 200, msg: 'success', result});
} else {
res.json({code: 400, msg: 'The specific entry does not exist or not belong to the user.'});
}
});
});
app.use('/', express.static(path.join(__dirname, 'public')));
app.listen(port, () => {
console.log(`Listening at ${port}`)
});