-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
69 lines (59 loc) · 1.78 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
const server = require('server');
const jwt = require('jsonwebtoken');
const config = require('./config');
const { get, post, error } = server.router;
const {
render, json, status,
} = server.reply;
const auth = async ctx => new Promise((resolve, reject) => {
const token = ctx.headers.authorization || ctx.query.token;
if (!token) {
reject(new Error('Unauthorized'));
return;
}
jwt.verify(token, config.jwtSecret, (err, decoded) => {
ctx.user = (err || !decoded) ? null : decoded.user;
if (err || !decoded) {
console.log(err);
reject(err.message);
}
resolve();
});
});
server(
config.serverConfig,
[
error(ctx => status(500).send(ctx.error.message)),
// serve index.html from the public dir
get('/', () => render('public/index')),
get('/protected', auth, async ctx => json({
message: 'hello! thanks for the token',
user: ctx.user, // stored in the token and pulled out in the auth middleware
})),
post('/login', async (ctx) => {
console.log(ctx.req.body);
// replace with some calls to a real user system
if (!(ctx.req.body.email === 'admin@admin.com' && ctx.req.body.password === 'admin')) {
return status(401).send({
error: 'Could not log in.',
});
}
// fake profile that would come from a db or something
const profile = {
user: {
id: 123,
email: 'admin@admin.com',
first_name: 'Admin',
last_name: 'Account',
},
};
// We are sending the profile inside the token
const token = jwt.sign(profile, config.jwtSecret, config.jwtOptions);
return json({
token,
});
}),
],
).then((ctx) => {
console.log(`Server launched on http://localhost:${ctx.options.port}/`);
});