-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
91 lines (71 loc) · 2.6 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
const express = require('express')
const session = require('express-session')
const MongoStore = require('connect-mongo')
const flash = require('connect-flash')
const markdown = require('marked')
const csrf = require('csurf')
const app = express()
const sanitizeHTML = require('sanitize-html')
const dotenv = require('dotenv')
dotenv.config()
app.use(express.urlencoded({extended: false}))
app.use(express.json())
app.use('/api', require('./router-api'))
let sessionOptions = session({
secret: "klasnd 21jaloenwq wqei2e",
store: MongoStore.create({client: require('./db')}),
resave: false,
saveUninitialized: false,
cookie: {maxAge: 1000 * 60 * 60 * 24, httpOnly: true}
})
app.use(sessionOptions)
app.use(flash())
app.use(function(req, res, next) {
// make our markdown function available from within ejs templates
res.locals.filterUserHTML = function(content) {
return sanitizeHTML(markdown.parse(content), {allowedTags: ['p', 'br', 'ul', 'ol', 'li', 'strong', 'bold', 'i', 'em', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'], allowedAttributes: {}})
}
// make all error and success flash messages available from all templates
res.locals.errors = req.flash("errors")
res.locals.success = req.flash("success")
// make current user id available on the req object
if (req.session.user) {req.visitorId = req.session.user._id} else {req.visitorId = 0}
// make user session data available from within view templates
res.locals.user = req.session.user
next()
})
const router = require('./router')
app.use(express.static('public'))
app.set('views', 'views')
app.set('view engine', 'ejs')
app.use(csrf())
app.use(function(req, res, next) {
res.locals.csrfToken = req.csrfToken()
next()
})
app.use('/', router)
app.use(function(err, req, res, next) {
if (err) {
if (err.code == "EBADCSRFTOKEN") {
req.flash('errors', "Cross site request forgery detected.")
req.session.save(() => res.redirect('/'))
} else {
res.render("404")
}
}
})
const server = require('http').createServer(app)
const io = require('socket.io')(server)
io.use(function(socket, next) {
sessionOptions(socket.request, socket.request.res, next)
})
io.on('connection', function(socket) {
if (socket.request.session.user) {
let user = socket.request.session.user
socket.emit('welcome', {username: user.username, avatar: user.avatar})
socket.on('chatMessageFromBrowser', function(data) {
socket.broadcast.emit('chatMessageFromServer', {message: sanitizeHTML(data.message, {allowedTags: [], allowedAttributes: {}}), username: user.username, avatar: user.avatar})
})
}
})
module.exports = server