forked from Xeio/IdleCodeRedeemer
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuserManager.ts
More file actions
180 lines (161 loc) · 6.09 KB
/
userManager.ts
File metadata and controls
180 lines (161 loc) · 6.09 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
import { eq, sql } from 'drizzle-orm';
import { db } from './db';
import { users } from './schema/index';
import { encrypt, decrypt, isEncrypted } from '../utils/crypto';
import logger from '../utils/logger';
export interface UserCredentials {
discordId: string;
userId: string;
userHash: string;
server?: string;
instanceId?: string;
autoRedeem?: boolean;
dmOnCode?: boolean;
dmOnSuccess?: boolean;
dmOnFailure?: boolean;
}
export interface NotificationPreferences {
dmOnCode: boolean;
dmOnSuccess: boolean;
dmOnFailure: boolean;
}
function decryptField(value: string): string {
return isEncrypted(value) ? decrypt(value) : value;
}
function rowToCredentials(user: typeof users.$inferSelect): UserCredentials {
return {
discordId: user.discordId,
userId: decryptField(user.userId),
userHash: decryptField(user.userHash),
server: user.server ?? undefined,
instanceId: user.instanceId ?? undefined,
autoRedeem: user.autoRedeem ?? true,
dmOnCode: user.dmOnCode ?? false,
dmOnSuccess: user.dmOnSuccess ?? true,
dmOnFailure: user.dmOnFailure ?? false,
};
}
class UserManager {
async saveCredentials(credentials: UserCredentials): Promise<void> {
const { discordId, userId, userHash, server, instanceId } = credentials;
if (!userId || !userHash) {
throw new Error('userId and userHash must not be empty');
}
const encryptedUserId = encrypt(userId);
const encryptedUserHash = encrypt(userHash);
db.insert(users)
.values({
discordId,
userId: encryptedUserId,
userHash: encryptedUserHash,
server: server ?? null,
instanceId: instanceId ?? null,
})
.onConflictDoUpdate({
target: users.discordId,
set: {
userId: encryptedUserId,
userHash: encryptedUserHash,
server: server ?? null,
instanceId: instanceId ?? null,
updatedAt: sql`CURRENT_TIMESTAMP`,
},
})
.run();
}
async getCredentials(discordId: string): Promise<UserCredentials | null> {
const user = db.select().from(users).where(eq(users.discordId, discordId)).get();
return user ? rowToCredentials(user) : null;
}
async deleteCredentials(discordId: string): Promise<void> {
db.delete(users).where(eq(users.discordId, discordId)).run();
}
async hasCredentials(discordId: string): Promise<boolean> {
const user = db.select({ discordId: users.discordId }).from(users).where(eq(users.discordId, discordId)).get();
return user !== undefined;
}
async getUserCount(): Promise<number> {
const result = db.select({ count: sql<number>`COUNT(*)` }).from(users).get();
return result?.count ?? 0;
}
async updateServer(discordId: string, server: string): Promise<void> {
db.update(users)
.set({ server, updatedAt: sql`CURRENT_TIMESTAMP` })
.where(eq(users.discordId, discordId))
.run();
}
async updateInstanceId(discordId: string, instanceId: string): Promise<void> {
db.update(users)
.set({ instanceId, updatedAt: sql`CURRENT_TIMESTAMP` })
.where(eq(users.discordId, discordId))
.run();
}
async setAutoRedeem(discordId: string, enabled: boolean): Promise<void> {
db.update(users)
.set({ autoRedeem: enabled, updatedAt: sql`CURRENT_TIMESTAMP` })
.where(eq(users.discordId, discordId))
.run();
}
async getAllUsersWithAutoRedeem(): Promise<UserCredentials[]> {
const rows = db.select().from(users).where(eq(users.autoRedeem, true)).orderBy(sql`${users.createdAt} DESC`).all();
return rows.map(rowToCredentials);
}
/**
* Returns only the Discord IDs of users who have opted into code-detection DMs.
*/
async getDiscordIdsWithDmOnCode(): Promise<string[]> {
const rows = db.select({ discordId: users.discordId }).from(users).where(eq(users.dmOnCode, true)).all();
return rows.map((r) => r.discordId);
}
/**
* Update notification preferences for a user.
*
* Note: this is a silent no-op when `discordId` does not exist in the
* database. The `/notifications` command guards against this by requiring
* `getCredentials` to succeed first. Direct callers must do the same.
*/
async setNotificationPreferences(discordId: string, prefs: Partial<NotificationPreferences>): Promise<boolean> {
const update: Partial<{ dmOnCode: boolean; dmOnSuccess: boolean; dmOnFailure: boolean }> = {};
if (prefs.dmOnCode !== undefined) update.dmOnCode = prefs.dmOnCode;
if (prefs.dmOnSuccess !== undefined) update.dmOnSuccess = prefs.dmOnSuccess;
if (prefs.dmOnFailure !== undefined) update.dmOnFailure = prefs.dmOnFailure;
if (Object.keys(update).length === 0) return false;
const rows = db.update(users)
.set({ ...update, updatedAt: sql`CURRENT_TIMESTAMP` })
.where(eq(users.discordId, discordId))
.returning({ discordId: users.discordId })
.all();
return rows.length > 0;
}
async getAllUsers(): Promise<UserCredentials[]> {
const rows = db.select().from(users).orderBy(sql`${users.createdAt} DESC`).all();
return rows.map(rowToCredentials);
}
/**
* One-time migration: re-encrypts any rows whose userId/userHash were stored
* as plaintext before encryption was introduced. Safe to call on every startup.
*/
async migratePlaintextCredentials(): Promise<void> {
const rows = db.select().from(users).all();
let migrated = 0;
for (const row of rows) {
const userIdNeedsEncryption = !isEncrypted(row.userId);
const userHashNeedsEncryption = !isEncrypted(row.userHash);
if (userIdNeedsEncryption || userHashNeedsEncryption) {
db.update(users)
.set({
userId: userIdNeedsEncryption ? encrypt(row.userId) : row.userId,
userHash: userHashNeedsEncryption ? encrypt(row.userHash) : row.userHash,
updatedAt: sql`CURRENT_TIMESTAMP`,
})
.where(eq(users.discordId, row.discordId))
.run();
migrated++;
}
}
if (migrated > 0) {
logger.info(`[USER MANAGER] Migrated ${migrated} plaintext credential row(s) to encrypted storage`);
}
}
}
export const userManager = new UserManager();