-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
incrementLoginAttempts.ts
57 lines (49 loc) · 1.34 KB
/
incrementLoginAttempts.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
import type { Payload } from '../../..'
import type { SanitizedCollectionConfig, TypeWithID } from '../../../collections/config/types'
import type { PayloadRequest } from '../../../express/types'
type Args = {
collection: SanitizedCollectionConfig
doc: TypeWithID & Record<string, unknown>
payload: Payload
req: PayloadRequest
}
export const incrementLoginAttempts = async ({
collection,
doc,
payload,
req,
}: Args): Promise<void> => {
const {
auth: { lockTime, maxLoginAttempts },
} = collection
if ('lockUntil' in doc && typeof doc.lockUntil === 'string') {
const lockUntil = new Date(doc.lockUntil).getTime()
// Expired lock, restart count at 1
if (lockUntil < Date.now()) {
await payload.update({
id: doc.id,
collection: collection.slug,
data: {
lockUntil: null,
loginAttempts: 1,
},
req,
})
}
return
}
const data: Record<string, unknown> = {
loginAttempts: Number(doc.loginAttempts) + 1,
}
// Lock the account if at max attempts and not already locked
if (typeof doc.loginAttempts === 'number' && doc.loginAttempts + 1 >= maxLoginAttempts) {
const lockUntil = new Date(Date.now() + lockTime)
data.lockUntil = lockUntil
}
await payload.update({
id: doc.id,
collection: collection.slug,
data,
req,
})
}