-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.js
65 lines (58 loc) · 1.31 KB
/
api.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
const path = require('path');
const auth = require('./auth');
const _ = require('lodash');
module.exports = {
showHtml,
helloWorld,
checkLoggedIn,
login,
logout,
message
}
function showHtml(htmlFile) {
return (req, res) => {
res.sendFile(path.join(__dirname, htmlFile));
}
}
function helloWorld(req, res) {
res.json({'hello': 'world'});
}
function checkLoggedIn(req, res, next) {
console.log(req.tokenStatus);
if (req.tokenStatus) {
res.writeHead(302, {
'Location': '/success'
})
.send();
} else {
next();
}
}
function login(req, res) {
const { username, password } = req.body;
if (!username || !password) {
res.status(400);
}
const token = auth.generateAccessToken(username);
res.writeHead(302, {
'Set-Cookie': `token=${token}; HttpOnly`,
'Access-Control-Allow-Credentials': 'true',
'Location': '/success'
})
.send();
}
function logout(req, res) {
auth.removeToken(req, res);
res.writeHead(302, {
'Location': '/login'
})
.send();
}
function message(req, res) {
const data = req.body;
if (_.isEmpty(data)) {
res.status(400).json({'error': 'Did not get any message!'})
} else {
res.json({'received': data});
}
}