-
Notifications
You must be signed in to change notification settings - Fork 0
/
storageHelpers.ts
86 lines (73 loc) · 2.73 KB
/
storageHelpers.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
import {CreatedTokens, Pkce, RetrievedTokens, TokenStorage} from "klaviyo-api";
import {PrismaClient} from "@prisma/client";
const crypto = require('node:crypto');
class PrismaTokenStorage implements TokenStorage {
readonly algorithm = 'aes-256-cbc'; //Using AES encryption
readonly splitKey = ":"
constructor(readonly prismaConnection: PrismaClient, readonly key: string) {
}
async retrieve(customerIdentifier: string): Promise<RetrievedTokens> {
const result = await this.prismaConnection.customerTokens.findUnique({where: {customerIdentifier}})
if (result) {
const parts = result.refreshToken.split(this.splitKey)
const iv = Buffer.from(parts[1], 'hex')
const decipher = crypto.createDecipheriv(this.algorithm, Buffer.from(this.key, 'hex'), iv)
const refreshToken = decipher.update(parts[0], 'hex', 'utf8') + decipher.final('utf8'); //deciphered text
return {accessToken: result.accessToken, refreshToken: refreshToken, expiresAt: result.expiresAt}
} else {
throw Error("Token Not Found")
}
}
async save(customerIdentifier: string, tokens: CreatedTokens): Promise<void> {
const iv = crypto.randomBytes(16)
const cipher = crypto.createCipheriv(this.algorithm, Buffer.from(this.key, 'hex'), iv)
const cipherText = cipher.update(tokens.refreshToken, 'utf8', 'hex') + cipher.final('hex');
const tokenAndIv = `${cipherText}${this.splitKey}${iv.toString('hex')}`
await this.prismaConnection.customerTokens.upsert({
where: {
customerIdentifier
},
update: {
accessToken: tokens.accessToken,
refreshToken: tokenAndIv,
expiresAt: tokens.expiresAt,
},
create: {
accessToken: tokens.accessToken,
refreshToken: tokens.refreshToken,
expiresAt: tokens.expiresAt,
customerIdentifier
}
})
}
}
class PrismPkceStorage implements Pkce.CodeStorage {
constructor(readonly prismaConnection: PrismaClient) {
}
async remove(customerIdentifier: string): Promise<void> {
await this.prismaConnection.customerPkceCodes.delete({where: {customerIdentifier}})
}
async retrieve(customerIdentifier: string): Promise<string> {
const result = await this.prismaConnection.customerPkceCodes.findUnique({where: {customerIdentifier}})
if (result) {
return result.codeVerifier
} else {
throw Error("Codes not Found")
}
}
async save(customerIdentifier: string, codeVerifier: string): Promise<void> {
await this.prismaConnection.customerPkceCodes.upsert({
where: {
customerIdentifier
},
update: {
codeVerifier
},
create: {
codeVerifier,
customerIdentifier
}
})
}
}
export {PrismPkceStorage, PrismaTokenStorage}