-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
93 lines (82 loc) · 2.41 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
const express = require("express");
const bodyParser = require('body-parser');
const JsonDB = require('node-json-db').JsonDB;
const Config = require('node-json-db/dist/lib/JsonDBConfig').Config;
const uuid = require("uuid");
const speakeasy = require("speakeasy");
const app = express();
var db = new JsonDB(new Config("myDataBase", true, false, '/'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/welcome", (req,res) => {
res.json({ message: "Welcome to the Two Factor Authentication" })
});
app.post("/", (req, res) => {
const id = uuid.v4();
try {
const path = `/user/${id}`;
// Create temporary secret until it it verified
const temp_secret = speakeasy.generateSecret();
// Create user in the database
db.push(path, { id, temp_secret });
// Send user id and base32 key to user
res.json({ id, secret: temp_secret.base32 })
} catch(e) {
console.log(e);
res.status(500).json({ message: 'Error generating secret key'})
}
})
app.post("/verify", (req,res) => {
const { userId, token } = req.body;
try {
// Retrieve user from database
const path = `/user/${userId}`;
const user = db.getData(path);
console.log({ user })
const { base32: secret } = user.temp_secret;
const verified = speakeasy.totp.verify({
secret,
encoding: 'base32',
token
});
if (verified) {
// Update user data
db.push(path, { id: userId, secret: user.temp_secret });
res.json({ verified: true })
} else {
res.json({ verified: false})
}
} catch(error) {
console.error(error);
res.status(500).json({ message: 'Error retrieving user'})
};
})
app.post("/validate", (req,res) => {
const { userId, token } = req.body;
try {
// Retrieve user from database
const path = `/user/${userId}`;
const user = db.getData(path);
console.log({ user })
const { base32: secret } = user.secret;
// Returns true if the token matches
const tokenValidates = speakeasy.totp.verify({
secret,
encoding: 'base32',
token,
window: 1
});
if (tokenValidates) {
res.json({ validated: true });
} else {
res.json({ validated: false})
}
} catch(error) {
console.error(error);
res.status(500).json({ message: 'Error retrieving user'})
};
})
const port = 5000;
app.listen(port, () => {
console.log(`App is running on PORT: ${port}.`);
});