-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathuserService.ts
More file actions
205 lines (181 loc) · 5.58 KB
/
userService.ts
File metadata and controls
205 lines (181 loc) · 5.58 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
import { UserProfile } from '@prisma/client'
import supertokensNode from 'supertokens-node'
import { RESPONSE_MESSAGES } from 'constants/index'
import prisma from 'prisma-local/clientInstance'
import crypto from 'crypto'
import config from 'config/index'
import { TriggerLogActionType } from 'services/triggerService'
export async function fetchUserProfileFromId (id: string): Promise<UserProfile> {
const userProfile = await prisma.userProfile.findUnique({ where: { id } })
if (userProfile === null) throw new Error(RESPONSE_MESSAGES.NO_USER_FOUND_404.message)
return userProfile
}
export interface SupertokensUser {
id: string
timeJoined: number
email: string
}
export interface UserWithSupertokens {
userProfile: UserProfile
stUser?: SupertokensUser
}
export async function fetchUserWithSupertokens (userId: string): Promise<UserWithSupertokens> {
const userProfile = await fetchUserProfileFromId(userId)
const stUser = await supertokensNode.getUser(userProfile.id)
return {
userProfile,
stUser: stUser === undefined
? undefined
: {
id: stUser.id,
timeJoined: stUser.timeJoined,
email: stUser?.emails[0]
}
}
}
export async function fetchAllUsersWithSupertokens (): Promise<UserWithSupertokens[]> {
const ret: UserWithSupertokens[] = []
const userProfiles = await fetchAllUsers()
await Promise.all(userProfiles.map(async (userProfile) => {
const stUser = await supertokensNode.getUser(userProfile.id)
ret.push({
userProfile,
stUser: stUser === undefined
? undefined
: {
id: stUser.id,
timeJoined: stUser.timeJoined,
email: stUser?.emails[0]
}
})
}))
return ret
}
export async function updateLastSentVerificationEmailAt (id: string): Promise<void> {
await prisma.userProfile.update({
where: { id },
data: {
lastSentVerificationEmailAt: new Date()
}
})
}
function getUserSeedHash (userId: string): Buffer {
const secretKey = process.env.MASTER_SECRET_KEY as string
return crypto.createHash('sha256').update(secretKey + userId).digest()
}
export function getUserPrivateKey (userId: string): crypto.KeyObject {
const seed = getUserSeedHash(userId)
const prefixPrivateEd25519 = Buffer.from('302e020100300506032b657004220420', 'hex')
const der = new Uint8Array(prefixPrivateEd25519.length + seed.length)
der.set(prefixPrivateEd25519 instanceof Uint8Array ? prefixPrivateEd25519 : new Uint8Array(prefixPrivateEd25519))
der.set(seed instanceof Uint8Array ? seed : new Uint8Array(seed), prefixPrivateEd25519.length)
const derBuf = Buffer.from(der)
return crypto.createPrivateKey({ key: derBuf, format: 'der', type: 'pkcs8' })
}
export async function getUserPublicKeyHex (id: string): Promise<string> {
let userPublicKey = (
await prisma.userProfile.findUniqueOrThrow({ where: { id }, select: { publicKey: true } })
).publicKey
if (userPublicKey === '') {
const privateKey = getUserPrivateKey(id)
const publicKey = crypto.createPublicKey(privateKey).export({
type: 'spki',
format: 'der'
}).toString('hex')
await prisma.userProfile.update({
where: {
id
},
data: {
publicKey
}
})
userPublicKey = publicKey
}
return userPublicKey
}
export async function fetchAllUsers (): Promise<UserProfile[]> {
return await prisma.userProfile.findMany()
}
export async function fetchUsersForAddress (addressString: string): Promise<UserProfile[]> {
return await prisma.userProfile.findMany({
where: {
addresses: {
some: {
address: {
address: addressString
}
}
}
}
})
}
export async function isUserAdmin (id: string): Promise<boolean> {
const user = await prisma.userProfile.findFirst({
where: {
id
}
})
return user?.isAdmin === true
}
export const exportedForTesting = {
getUserSeedHash
}
export async function updatePreferredCurrency (id: string, preferredCurrencyId: number): Promise<void> {
await prisma.userProfile.update({
where: { id },
data: {
preferredCurrencyId
}
})
}
export async function updatePreferredTimezone (id: string, preferredTimezone: string): Promise<void> {
await prisma.userProfile.update({
where: { id },
data: {
preferredTimezone
}
})
}
export async function updateCsvRowCollapsing (id: string, csvRowCollapsing: boolean): Promise<void> {
await prisma.userProfile.update({
where: { id },
data: {
csvRowCollapsing
}
})
}
export async function userRemainingProTime (id: string): Promise<number | null> {
const today = new Date()
const proUntil = (await prisma.userProfile.findUniqueOrThrow({
where: { id },
select: {
proUntil: true
}
})).proUntil
if (proUntil === null) {
return null
}
return proUntil.getTime() - today.getTime()
}
export function isUserPro (proUntil?: Date | null): boolean {
if (proUntil == null) return false
return new Date(proUntil).getTime() > Date.now()
}
export function getUserTriggerCreditsLimit (
user: UserProfile,
actionType: TriggerLogActionType
): number {
const { proSettings } = config
const isPro = isUserPro(user.proUntil)
if (actionType === 'SendEmail') {
return isPro ? proSettings.proDailyEmailLimit : proSettings.standardDailyEmailLimit
}
return isPro ? proSettings.proDailyPostLimit : proSettings.standardDailyPostLimit
}
export function getUserRemainingTriggerCreditsLimit (
user: UserProfile,
actionType: TriggerLogActionType
): number {
return actionType === 'SendEmail' ? user.emailCredits : user.postCredits
}