-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathserver.js
153 lines (136 loc) · 4.68 KB
/
server.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const cookieParser = require('cookie-parser');
const accountSid = process.env.ACCOUNT_SID;
const authToken = process.env.AUTH_TOKEN;
const client = require('twilio')(accountSid, authToken);
const crypto = require('crypto');
const smsKey = process.env.SMS_SECRET_KEY;
const twilioNum = process.env.TWILIO_PHONE_NUMBER;
const jwt = require('jsonwebtoken');
const JWT_AUTH_TOKEN = process.env.JWT_AUTH_TOKEN;
const JWT_REFRESH_TOKEN = process.env.JWT_REFRESH_TOKEN;
let refreshTokens = [];
const app = express();
app.use(express.json());
app.use(cors({ origin: 'http://localhost:3000', credentials: true }));
app.use(cookieParser());
app.post('/sendOTP', (req, res) => {
const phone = req.body.phone;
const otp = Math.floor(100000 + Math.random() * 900000);
const ttl = 2 * 60 * 1000;
const expires = Date.now() + ttl;
const data = `${phone}.${otp}.${expires}`;
const hash = crypto.createHmac('sha256', smsKey).update(data).digest('hex');
const fullHash = `${hash}.${expires}`;
client.messages
.create({
body: `Your One Time Login Password For CFM is ${otp}`,
from: twilioNum,
to: phone
})
.then((messages) => console.log(messages))
.catch((err) => console.error(err));
// res.status(200).send({ phone, hash: fullHash, otp }); // this bypass otp via api only for development instead hitting twilio api all the time
res.status(200).send({ phone, hash: fullHash }); // Use this way in Production
});
app.post('/verifyOTP', (req, res) => {
const phone = req.body.phone;
const hash = req.body.hash;
const otp = req.body.otp;
let [ hashValue, expires ] = hash.split('.');
let now = Date.now();
if (now > parseInt(expires)) {
return res.status(504).send({ msg: 'Timeout. Please try again' });
}
let data = `${phone}.${otp}.${expires}`;
let newCalculatedHash = crypto.createHmac('sha256', smsKey).update(data).digest('hex');
if (newCalculatedHash === hashValue) {
console.log('user confirmed');
const accessToken = jwt.sign({ data: phone }, JWT_AUTH_TOKEN, { expiresIn: '30s' });
const refreshToken = jwt.sign({ data: phone }, JWT_REFRESH_TOKEN, { expiresIn: '1y' });
refreshTokens.push(refreshToken);
res
.status(202)
.cookie('accessToken', accessToken, {
expires: new Date(new Date().getTime() + 30 * 1000),
sameSite: 'strict',
httpOnly: true
})
.cookie('refreshToken', refreshToken, {
expires: new Date(new Date().getTime() + 31557600000),
sameSite: 'strict',
httpOnly: true
})
.cookie('authSession', true, { expires: new Date(new Date().getTime() + 30 * 1000), sameSite: 'strict' })
.cookie('refreshTokenID', true, {
expires: new Date(new Date().getTime() + 31557600000),
sameSite: 'strict'
})
.send({ msg: 'Device verified' });
} else {
console.log('not authenticated');
return res.status(400).send({ verification: false, msg: 'Incorrect OTP' });
}
});
app.post('/home', authenticateUser, (req, res) => {
console.log('home private route');
res.status(202).send('Private Protected Route - Home');
});
async function authenticateUser(req, res, next) {
const accessToken = req.cookies.accessToken;
jwt.verify(accessToken, JWT_AUTH_TOKEN, async (err, phone) => {
if (phone) {
req.phone = phone;
next();
} else if (err.message === 'TokenExpiredError') {
return res.status(403).send({
success: false,
msg: 'Access token expired'
});
} else {
console.log(err);
return res.status(403).send({ err, msg: 'User not authenticated' });
}
});
}
app.post('/refresh', (req, res) => {
const refreshToken = req.cookies.refreshToken;
if (!refreshToken) return res.status(403).send({ message: 'Refresh token not found, login again' });
if (!refreshTokens.includes(refreshToken))
return res.status(403).send({ message: 'Refresh token blocked, login again' });
jwt.verify(refreshToken, JWT_REFRESH_TOKEN, (err, phone) => {
if (!err) {
const accessToken = jwt.sign({ data: phone }, JWT_AUTH_TOKEN, {
expiresIn: '30s'
});
return res
.status(200)
.cookie('accessToken', accessToken, {
expires: new Date(new Date().getTime() + 30 * 1000),
sameSite: 'strict',
httpOnly: true
})
.cookie('authSession', true, {
expires: new Date(new Date().getTime() + 30 * 1000),
sameSite: 'strict'
})
.send({ previousSessionExpired: true, success: true });
} else {
return res.status(403).send({
success: false,
msg: 'Invalid refresh token'
});
}
});
});
app.get('/logout', (req, res) => {
res
.clearCookie('refreshToken')
.clearCookie('accessToken')
.clearCookie('authSession')
.clearCookie('refreshTokenID')
.send('logout');
});
app.listen(process.env.PORT || 8888);