-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
106 lines (93 loc) · 2.69 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
const express = require('express');
const mongoose = require('mongoose');
mongoose.set('strictQuery', true)
require('dotenv').config();
const UserModel = require("./models/users");
const uuid4 = require('uuid').v4;
const JWT = require('jsonwebtoken');
const authenticateToken = require('./middlewares/authorizeToken');
const otpGenerator = require('./helpers/otpGenerator');
const qrcode = require('qrcode-terminal');
const cors = require('cors');
const https = require('https')
const fs = require("fs");
mongoose.connect(process.env.MONGO_URI);
const app = express();
app.use(express.json());
app.use(cors());
app.get("/", (req, res) => {
res.send("Hello");
})
app.post("/createuser", async (req, res) => {
try {
const newUser = UserModel({
id: req.body.id,
password: req.body.password,
key: uuid4()
})
await newUser.save();
//console log the key
console.log("NEW USER CREATED", newUser);
qrcode.generate(newUser.key, { small: true },
function (qrcode) { console.log(qrcode) });
res.status(201);
res.send({ key: newUser.key });
} catch (err) {
console.log(err.message);
res.status(500);
res.send(err.message);
}
})
app.post('/login', async (req, res) => {
if (!req.body.id || !req.body.password) {
res.status(401).send("NO CREDENTIALS FOUND");
}
try {
const user = await UserModel.findOne({
id: req.body.id
})
if (!user) {
res.sendStatus(401);
return;
}
if (req.body.password !== user.password) {
res.sendStatus(401);
return;
}
const token = JWT.sign(
{
id: user.id,
key: user.key
},
process.env.JWT_KEY,
{ expiresIn: '5m' }
)
res.json({ token: token })
} catch (err) {
console.log(err.message);
res.statusCode = 500;
res.send(err.message ?? err.msg)
}
})
app.post("/verifyotp", authenticateToken, (req, res) => {
try {
const otpFromServer = otpGenerator(req.user.key);
if (otpFromServer === req.body.otp) res.sendStatus(200);
else res.sendStatus(401);
} catch (err) {
console.log(err.message);
res.status(500).send(err.message);
}
})
// Creating object of key and certificate
// for SSL
const options = {
key: fs.readFileSync("server.key"),
cert: fs.readFileSync("server.cert"),
};
// Creating https server by passing
// options and app object
https.createServer(options, app)
.listen(3000, function (req, res) {
console.log("Server started at port 3000");
});