-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.ts
185 lines (167 loc) · 6.32 KB
/
auth.ts
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
// Copyright 2021-2024 Prosopo (UK) Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { ApiParams, ProcaptchaOutput, ProcaptchaOutputSchema } from '@prosopo/types'
import { Connection } from 'mongoose'
import { NextFunction, Request, Response } from 'express'
import { ProcaptchaResponse } from '@prosopo/types'
import { ProsopoServer } from '@prosopo/server'
import { UserInterface } from '../models/user.js'
import { at } from '@prosopo/util'
import { blake2b } from '@noble/hashes/blake2b'
import { randomAsHex } from '@polkadot/util-crypto'
import { u8aToHex } from '@polkadot/util'
import { z } from 'zod'
import jwt from 'jsonwebtoken'
const SubscribeBodySpec = ProcaptchaResponse.merge(
z.object({
email: z.string().email(),
password: z.string(),
})
)
function hashPassword(password: string): string {
return u8aToHex(blake2b(password))
}
const verify = async (
prosopoServer: ProsopoServer,
verifyType: string,
verifyEndpoint: string,
data: ProcaptchaOutput
) => {
if (verifyType === 'api') {
// verify using the API endpoint
console.log('verifying using the API endpoint')
const response = await fetch(verifyEndpoint, {
method: 'POST',
body: JSON.stringify(data),
})
return (await response.json()).verified
} else {
// verify using the TypeScript library
console.log('verifying using the TypeScript library')
return await prosopoServer.isVerified(data)
}
}
const signup = async (
mongoose: Connection,
prosopoServer: ProsopoServer,
verifyEndpoint: string,
verifyType: string,
req: Request,
res: Response,
next: NextFunction
) => {
try {
const User = mongoose.model<UserInterface>('User')
// checks if email exists
const dbUser = await User.findOne({
email: req.body.email,
})
const payload = SubscribeBodySpec.parse(req.body)
await prosopoServer.isReady()
if (dbUser) {
return res.status(409).json({ message: 'email already exists' })
}
console.log('payload', payload)
// get the contents of the procaptcha-response JSON data
const data = ProcaptchaOutputSchema.parse(payload[ApiParams.procaptchaResponse])
console.log('sending data', data)
const verified = await verify(prosopoServer, verifyType, verifyEndpoint, data)
if (verified) {
// salt
const salt = randomAsHex(32)
// !!!DUMMY CODE!!! - Do not use in production. Use bcrypt or similar for password hashing.
const passwordHash = hashPassword(`${req.body.password}${salt}`)
if (passwordHash) {
return User.create({
email: req.body.email,
name: req.body.name,
password: passwordHash,
salt: salt,
})
.then(() => {
res.status(200).json({ message: 'user created' })
})
.catch((err) => {
console.log(err)
res.status(502).json({ message: 'error while creating the user' })
})
}
} else {
res.status(401).json({ message: 'user has not completed a captcha' })
}
} catch (err) {
console.error('error', err)
res.status(500).json({ message: (err as Error).message || 'internal server error' })
}
}
const login = async (
mongoose: Connection,
prosopoServer: ProsopoServer,
verifyEndpoint: string,
verifyType: string,
req: Request,
res: Response
) => {
const User = mongoose.model<UserInterface>('User')
await prosopoServer.isReady()
// checks if email exists
await User.findOne({
email: req.body.email,
})
.then(async (dbUser) => {
if (!dbUser) {
res.status(404).json({ message: 'user not found' })
} else {
const payload = SubscribeBodySpec.parse(req.body)
const data = ProcaptchaOutputSchema.parse(payload[ApiParams.procaptchaResponse])
const verified = await verify(prosopoServer, verifyType, verifyEndpoint, data)
if (verified) {
// password hash
// !!!DUMMY CODE!!! - Do not use in production. Use bcrypt or similar for password hashing.
const passwordHash = hashPassword(`${req.body.password}${dbUser.salt}`)
if (passwordHash !== dbUser.password) {
// password doesnt match
res.status(401).json({ message: 'invalid credentials' })
} else {
// password match
const token = jwt.sign({ email: req.body.email }, 'secret', { expiresIn: '1h' })
res.status(200).json({ message: 'user logged in', token: token })
}
}
}
})
.catch((err) => {
console.error('error', err)
res.status(500).json({ message: err.message || 'internal server error' })
})
}
const isAuth = (req: Request, res: Response) => {
const authHeader = req.get('Authorization') || ''
if (!authHeader) {
res.status(401).json({ message: 'not authenticated' })
}
const token = at(authHeader.split(' '), 1)
let decodedToken
try {
decodedToken = jwt.verify(token, 'secret')
} catch (err) {
res.status(500).json({ message: (err as Error).message || 'could not decode the token' })
}
if (!decodedToken) {
res.status(401).json({ message: 'unauthorized' })
} else {
res.status(200).json({ message: 'here is your resource' })
}
}
export { signup, login, isAuth }