-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
87 lines (69 loc) · 2.34 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
const express = require('express')
const expressSession = require('express-session')
const bodyParser = require('body-parser')
const signup = require('./signup')
const login = require('./login')
const {knex} = require('./db-connection')
const saveMessage = (userId, message) =>
knex('messages')
.insert({
text: message.replace(/</g, '<').replace(/>/g, '>'),
user_id: userId,
})
const app = express()
app.use(bodyParser.urlencoded({extended: true}))
app.use(expressSession({
secret: 'cotirube',
}))
app.all('/signup', signup)
app.get('/login', login.loginFormRender)
app.post('/login', login.loginFormSubmit)
app.get('/logout', login.renderLogout)
const renderMessages = (req, res) => {
console.log('session', req.session)
if (req.session.user) {
knex('messages')
.join('users', 'messages.user_id', '=', 'users.id')
.orderBy('timestamp', 'desc')
.then(messages =>
res.send(`
<h1>${req.session.user.name} Vitaj!</h1>
<a href="/logout" >odhlas sa</a>
<h1>Zatiaľ napíš čo sťeš</h1>
<h2>Ale nemusíš napísať ňišt</h2>
<form method="post">
<input name="message" placeholder="Správa"/>
<input type="submit"/>
<ul>
${messages
.map(message => `<li>${message.timestamp} [${message.name}]: ${message.text}</li>`)
.join('')}
</ul>
</form>
`))} else {
res.send(`
<h1>Nazdar neni si prihlaseny!/prihlasena!</h1>
<a href="/login" >Prihlas sa</a>
<div>alebo sa</div>
<a href="/signup">zaregistruj</a>.
`)
}
}
app.get('/', renderMessages)
app.post('/', (req, res) => {
knex('users')
.where({name: req.session.user.name})
.first()
.then(user => {
if (!user) {
knex('users')
.insert({name: req.body.userName})
.then(id => { saveMessage(id, req.body.message)})
.then(() => { res.redirect(302, '/')})
} else
saveMessage(user.id, req.body.message)
.then(() => res.redirect(302, '/'))
})
})
app.listen(8080, '0.0.0.0')
console.log('listeing on http://localhost:8080')