-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathrequestOTP.ts
More file actions
112 lines (93 loc) · 3 KB
/
requestOTP.ts
File metadata and controls
112 lines (93 loc) · 3 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
import type { DataFromCollectionSlug, Payload } from 'payload'
import { APIError } from 'payload'
import type { AuthCollectionSlug, FindUserType, OTPPluginCollectionOptions } from '../types.js'
import { defaultExp, getDefaultOTPEmailHTML, getDefaultOTPEmailSubject } from '../defaults.js'
import { encrypt } from '../utilities/encrypt.js'
import { findUser } from '../utilities/findUser.js'
import { generateOTP } from '../utilities/generateOTP.js'
type BaseArgs = {
collection: AuthCollectionSlug
exp?: number
payload: Payload
}
type Args = BaseArgs & FindUserType
export const setOTP = async ({
type,
collection,
exp: expOverride,
payload,
value,
}: Args): Promise<{ otp: string; user: DataFromCollectionSlug<AuthCollectionSlug> }> => {
if (!type) {
throw new APIError('No login type specified', 400)
}
if (!value) {
throw new APIError(`No ${type} provided`, 400)
}
const otp = generateOTP()
const user = await findUser({ type, collection, payload, value })
const collectionOptions: OTPPluginCollectionOptions =
payload.config.custom.otp.collections[collection]
const exp = expOverride ?? collectionOptions?.exp ?? defaultExp
const _otpExpiration = new Date(Date.now() + exp * 1000).toISOString()
try {
const userData = await payload.db.findOne({
collection,
joins: false,
where: { id: { equals: user.id } },
})
if (!userData) {
throw new APIError(`User with ID=${user.id} was not found.`)
}
await payload.db.updateOne({
id: user.id,
collection,
data: {
...userData,
_otp: encrypt({ payload, value: otp }),
_otpExpiration,
},
select: {},
})
} catch (err) {
const errorMessage = `Error setting one-time password for ${type}: ${value}`
payload.logger.error(err, errorMessage)
throw new APIError(errorMessage)
}
if (!collectionOptions.disableEmail) {
const html =
typeof collectionOptions?.generateOTPEmailHTML === 'function'
? await collectionOptions.generateOTPEmailHTML({
collection,
otp,
user,
})
: getDefaultOTPEmailHTML({ collection, otp, user })
const subject =
typeof collectionOptions?.generateOTPEmailSubject === 'function'
? await collectionOptions.generateOTPEmailSubject({
collection,
otp,
user,
})
: getDefaultOTPEmailSubject({ collection, otp, user })
if ('email' in user) {
await payload.email.sendEmail({
from: `"${payload.email.defaultFromName}" <${payload.email.defaultFromAddress}>`,
html,
subject,
to: user.email,
})
} else {
throw new APIError(
`Attempted to send email to user with ${type}: ${value}, but user has no email specified.`,
)
}
}
if (Array.isArray(collectionOptions?.hooks?.afterSetOTP)) {
for (const hook of collectionOptions.hooks.afterSetOTP) {
await hook({ collection, otp, user })
}
}
return { otp, user }
}