forked from Telefonica/ogw-wad2025-workshop-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
303 lines (283 loc) · 8.8 KB
/
Copy pathindex.ts
File metadata and controls
303 lines (283 loc) · 8.8 KB
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import express from 'express'
import dotenv from 'dotenv'
import cors from 'cors'
const phoneRegex = /^\+\d{2}[0-9]{1,13}$/
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
interface CustomerUser {
id: string
isPhoneNumber: boolean
verified: boolean
password?: string
nonMobileId?: string
verificationRequestId?: string
}
interface NumberVerificationResponse {
verified: boolean
}
class InMemoryStore {
static users: CustomerUser[] = []
static accessTokens: Map<string, string> = new Map()
}
declare global {
var users: CustomerUser[]
var accessTokens: Map<string, string>
}
Object.defineProperty(global, 'users', {
get() { return InMemoryStore.users },
set(val) { InMemoryStore.users = val }
})
Object.defineProperty(global, 'accessTokens', {
get() { return InMemoryStore.accessTokens },
set(val) { InMemoryStore.accessTokens = val }
})
dotenv.config()
const api = express()
api.use(express.json())
api.use(cors())
let port: number
const backendUrl = process.env.BACKEND_URL || ''
const portMatch = backendUrl.match(/:(\d+)(?:\/)?$/)
if (portMatch) {
port = parseInt(portMatch[1], 10)
} else {
port = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000
}
const saveUser = async (user: CustomerUser) => {
global.users?.push(user)
}
const verifyNumber = async (phoneNumber: string, state: string): Promise<NumberVerificationResponse> => {
const accessToken = global.accessTokens?.get(state as string)
if (!accessToken) {
return {
verified: false,
} as NumberVerificationResponse
}
const result = await numberVerificationResult(accessToken, phoneNumber)
return {
verified: result,
} as NumberVerificationResponse
}
const numberVerificationResult = async (accessToken: string, phoneNumber: string): Promise<boolean> => {
try {
const headers = new Headers()
headers.append('Content-Type', 'application/json')
headers.append('Authorization', `Bearer ${accessToken}`)
const response = await fetch(`${process.env.API_GATEWAY_NETWORK_APIS}/camara/number-verification/v031/verify`, {
method: 'POST',
headers: headers,
body: JSON.stringify({ phoneNumber })
})
const data = await response.json()
const { devicePhoneNumberVerified } = data as { devicePhoneNumberVerified: boolean }
return devicePhoneNumberVerified ?? false
} catch (error) {
console.error('There has been a problem with your fetch operation:', error)
return false
}
}
const sendVerificationCode = async (recipient: CustomerUser, channel: "sms" | "email") => {
const to = recipient.id.startsWith('+') ? recipient.id.slice(1) : recipient.id
const headers = new Headers()
headers.append('Content-Type', 'application/json')
headers.append('Authorization', `Basic ${btoa(process.env.API_KEY + ':' + process.env.API_SECRET)}`)
fetch(`${process.env.API_GATEWAY}/v2/verify`, {
method: 'POST',
headers: headers,
body: JSON.stringify({
brand: "Mock company",
workflow: [{ channel, to }]
})
})
.then(response => {
if (!response.ok) throw new Error(`Failed to send verification code: ${response.statusText}`)
return response.json()
}).then(data => {
const { request_id } = data as { request_id: string }
saveUser({
...recipient,
verificationRequestId: request_id
} as CustomerUser)
}).catch(error => {
console.error(`Error sending verification code to ${to} via ${channel}:`, error)
})
}
const checkVerificationCode = async (user: CustomerUser, code: string): Promise<boolean> => {
const headers = new Headers()
headers.append('Content-Type', 'application/x-www-form-urlencoded')
headers.append('Authorization', `Basic ${btoa(process.env.API_KEY + ':' + process.env.API_SECRET)}`)
try {
const response = await fetch(`${process.env.API_GATEWAY}/v2/verify/${user.verificationRequestId}`, {
method: 'POST',
headers: headers,
body: JSON.stringify({ code })
})
return response.ok
} catch (error) {
return false
}
}
api.get('/callback', async (req, res) => {
const code = req.query.code
const error = req.query.error
const requestId = req.query.state as string
if (error) {
res.status(400).send(`Error: ${req.query.error_description || 'Unknown error'}`)
return
}
if (!code || !requestId) {
res.status(400).send('Bad Request: code and state are required')
return
}
const headers = new Headers()
headers.append('Content-Type', 'application/x-www-form-urlencoded')
headers.append('Authorization', `Bearer ${process.env.API_JWT}`)
headers.append('Accept', 'application/json')
const params = new URLSearchParams()
params.append('grant_type', 'authorization_code')
params.append('code', code as string)
params.append('redirect_uri', `${process.env.BACKEND_URL}/callback`)
try {
const response = await fetch(`${process.env.API_GATEWAY_OAUTH}/oauth2/token`, {
method: 'POST',
headers,
body: params.toString()
})
if (!response.ok) {
const errorText = await response.text()
console.error('Token error:', response.status, errorText)
res.status(response.status).send(errorText)
return
}
const data = await response.json()
const { access_token } = data
global.accessTokens = global.accessTokens || new Map()
global.accessTokens.set(requestId, access_token)
setTimeout(() => {
global.accessTokens.delete(requestId)
}, 2 * 60 * 60 * 1000)
res.status(201).send(`
<html lang="en">
<body>
<script>
window.opener.postMessage({ status: 'authorized', requestId: '${requestId}' }, '*');
window.close();
</script>
<p>You can close this window.</p>
</body>
</html>
`)
} catch (err) {
console.error('Unexpected fetch error', err)
res.status(500).send('Internal Server Error')
}
})
api.post('/signup', async (req, res) => {
const state = req.query.state
const { id: userId, password } = req.body
const isEmail = emailRegex.test(userId || '')
if (!userId || (isEmail && !password)) {
res.status(400).send('Bad Request: phone number or email and password are required')
return
}
global.users = global.users || []
const existingUser = global.users.find(user => user.id.toLowerCase() === userId.toLowerCase())
if (existingUser) {
res.status(409).send('Conflict: User already exists')
return
}
const newUser: CustomerUser = {
id: userId,
isPhoneNumber: phoneRegex.test(userId),
verified: false,
...(password ? { password } : {}),
}
if (isEmail) {
global.users.push(newUser)
sendVerificationCode(newUser, "email")
res.status(202).json({
verified: false,
} as NumberVerificationResponse)
return
}
const result = await verifyNumber(userId!, state as string)
const verificationResult = result as NumberVerificationResponse
if (!verificationResult.verified) {
sendVerificationCode(newUser, "sms")
}
saveUser({
...newUser,
verified: verificationResult.verified,
} as CustomerUser)
res.status(200).json(verificationResult)
})
api.post('/verify', async (req, res) => {
const { id: userId, code } = req.body
if (!userId || !code) {
res.status(400).send('Bad Request: phone number or email as id, and code are required')
return
}
if (!phoneRegex.test(userId) && !emailRegex.test(userId)) {
res.status(400).send('Bad Request: Invalid phone number or email format for id')
return
}
if (!code || !/^\d+$/.test(code)) {
res.status(400).send('Bad Request: code must be a number')
return
}
const user = global.users?.find(user => user.id === userId)
if (!user) {
res.status(404).send('Not Found: User not found')
return
}
if (user.verified) {
res.status(304).send()
return
}
user.verified = await checkVerificationCode(user, code)
await saveUser(user)
res.status(200).json({ verified: user.verified })
})
api.post('/authorize', async (req, res) => {
try {
const { phone, state } = req.body || {}
if (!phone) {
res.status(400).json({ error: "Phone number is required." })
return
}
const response = await fetch(`${process.env.API_GATEWAY_NETWORK_APIS}/v0.1/network-enablement`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.API_JWT}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
phone_number: phone,
scopes: [process.env.NV_SCOPE],
state,
})
})
if (!response.ok) {
const errorText = await response.text()
console.error('Vonage API error:', errorText)
res.status(response.status).json({ error: "Failed to initialize authentication flow." })
return
}
const data = await response.json()
if (!process.env.NV_SCOPE) {
res.status(500).json({ error: "NV_SCOPE environment variable is not set." })
return
}
const { auth_url } = data.scopes[process.env.NV_SCOPE]
res.status(200).json({ auth_url })
} catch (error) {
console.error('Unexpected error with /login:', error)
if (error instanceof Error) {
res.status(500).json({ error: error.message })
} else {
res.status(500).json({ error: 'Internal server error' })
}
}
})
api.listen(port, async () => {
console.log(`Server is running on ${process.env.BACKEND_URL}`)
})