This repository has been archived by the owner on Mar 7, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
204 lines (166 loc) · 4.85 KB
/
index.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
'use strict';
// Imports
const express = require('express');
const exphbs = require('express-handlebars');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const jwt = require('jsonwebtoken');
const morgan = require('morgan');
// Database
const db = require('./server/database');
// Collections
let User = require('./models/users');
let Tweet = require('./models/tweets');
// Express Settings
let app = express();
let port = process.env.PORT || 3000;
app.set('APP_SECRET', 'SUPER-SECRET-KEY');
app.use('/static', express.static(__dirname + '/client/static'));
app.set('views', 'client/views/');
// Body Parser
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Cookie Parser
app.use(cookieParser());
// View Engine Settings
let helpers = require('./client/library/helpers');
let hbs = exphbs.create({
defaultLayout: 'main',
extname: '.hbs',
helpers: helpers,
layoutsDir: 'client/views/layouts/',
partialsDir: 'client/views/common/'
});
app.engine('.hbs', hbs.engine);
app.set('view engine', '.hbs');
// Router
let routerPublic = express.Router();
let routerLoggedin = express.Router();
routerPublic.use((request, response, next) => {
let token = request.body.token || request.query.token || request.headers['x-access-token'] || request.cookies.token;
if (token) {
request.user = jwt.verify(token, app.get('APP_SECRET'));
} else {
request.user = {};
}
next();
});
routerLoggedin.use((request, response, next) => {
if (typeof request.user._id === 'undefined') {
response.redirect('/login');
} else {
next();
}
});
// Middleware
let log = (req, res, next) => {
console.log('LOGGED | Middleware - ' + new Date());
next();
};
app.use(log);
app.use(morgan('dev'));
// Routes
// Home (list tweets)
routerPublic.get('/', (request, response) => {
Tweet.find({}).sort('-createdAt').exec(function (error, documents) {
response.render('pages/home', { user: request.user, tweets: documents });
});
});
// Tweet
// Form
routerLoggedin.get('/tweet', (request, response) => {
response.render('pages/tweet', { user: request.user });
});
// Submit Form
routerLoggedin.post('/tweet', (request, response) => {
if (request.body.text !== '') {
let tweet = {
text: request.body.text,
userId: request.user._id,
createdAt: new Date()
};
Tweet.create(tweet, (error, document) => {
if (document._id) {
response.redirect('/');
}
});
} else {
response.redirect('/tweet');
}
});
// User
// Login
// Form
routerPublic.get('/login', (request, response) => {
let message = request.query.message;
response.render('user/login', { user: request.user, message: message });
});
// Submit
routerPublic.post('/login', (request, response) => {
User.findOne({ username: request.body.username }, (error, document) => {
if (error) {
throw error;
} else {
if (!document) {
let message = 'No user exists with this username.';
response.redirect('/login/?message=' + encodeURIComponent(message));
} else {
if (document.password !== request.body.password) {
let message = 'The password is incorrect.';
response.redirect('/login/?message=' + encodeURIComponent(message));
} else {
let token = jwt.sign(document.toObject(), app.get('APP_SECRET'));
response.cookie('token', token);
response.redirect('/tweet');
}
}
}
});
});
// Register
// Form
routerPublic.get('/register', (request, response) => {
let message = request.query.message;
response.render('user/register', { user: request.user, message: message });
});
// Submit
routerPublic.post('/register', (request, response) => {
if (request.body.username !== '') {
// Check user exists
User.findOne({ username: request.body.username }, (error, document) => {
if (!document) {
// User does not exists
let user = {
username: request.body.username,
password: request.body.password,
createdAt: new Date()
};
User.create(user, function (errorCreate, documentCreate) {
if (documentCreate._id) {
response.redirect('/login');
}
});
} else {
// User already exists
let message = 'The username is taken. Please enter something else.';
response.redirect('/register/?message=' + encodeURIComponent(message));
}
});
} else {
response.redirect('/register');
}
});
// Logout
routerPublic.get('/logout', (request, response) => {
response.clearCookie('token');
response.redirect('/');
});
// Apply routers
app.use(routerPublic);
app.use(routerLoggedin);
// Boot Server
let index = app.listen(3000, () => {
let host = index.address().address;
let port = index.address().port;
console.log('Server running on http://%s:%s', host, port);
});