All files / dal users.dal.ts

100% Statements 48/48
100% Branches 34/34
100% Functions 15/15
100% Lines 45/45

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242                          67x     5x         5x       2x         2x                   4x 4x 3x 3x       3x     4x         3x       2x 1x                     4x   4x 2x 2x 2x               4x             3x   3x 1x 1x 1x               3x 3x                   2x                       2x                                 3x               3x               4x                 4x       2x       2x               3x 3x   2x         2x         2x         2x               2x               2x                 1x                   1x      
// Data Access Layer for Users
import { eq, desc, like, or, and, ne, count, inArray } from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import * as schema from "../db/schema";
import type { User, Account, UserTenantRole } from "../db/schema";
import { sanitizeSearchInput } from "../lib/utils";
import { normalizeToE164 } from "@interioring/utils/validation/phone";
 
export type UserFilters = {
	search?: string;
};
 
export class UsersDal {
	constructor(private db: DrizzleD1Database<typeof schema>) {}
 
	async findById(id: string): Promise<User | null> {
		const result = await this.db
			.select()
			.from(schema.users)
			.where(eq(schema.users.id, id))
			.limit(1);
		return result[0] ?? null;
	}
 
	async findByEmail(email: string): Promise<User | null> {
		const result = await this.db
			.select()
			.from(schema.users)
			.where(eq(schema.users.email, email))
			.limit(1);
		return result[0] ?? null;
	}
 
	async findByPhoneNumber(
		phoneNumber: string,
		excludeUserId?: string,
	): Promise<User | null> {
		// Normalize to E.164 for consistent matching. Match against both the
		// canonical E.164 form and the legacy 10-digit form so rows written
		// before the phone-format migration still resolve.
		const e164 = normalizeToE164(phoneNumber);
		if (!e164) return null;
		const nationalDigits = e164.slice(3); // strip "+91"
		const phoneMatch = or(
			eq(schema.users.phoneNumber, e164),
			eq(schema.users.phoneNumber, nationalDigits),
		);
		const condition = excludeUserId
			? and(phoneMatch, ne(schema.users.id, excludeUserId))
			: phoneMatch;
		const result = await this.db
			.select()
			.from(schema.users)
			.where(condition)
			.limit(1);
		return result[0] ?? null;
	}
 
	async findByIds(ids: string[]): Promise<User[]> {
		if (ids.length === 0) return [];
		return this.db
			.select()
			.from(schema.users)
			.where(inArray(schema.users.id, ids));
	}
 
	async findAll(
		filters: UserFilters = {},
		offset = 0,
		limit = 50,
	): Promise<User[]> {
		let query = this.db.select().from(schema.users);
 
		if (filters.search) {
			const sanitized = sanitizeSearchInput(filters.search);
			const searchPattern = `%${sanitized}%`;
			query = query.where(
				or(
					like(schema.users.name, searchPattern),
					like(schema.users.email, searchPattern),
				),
			) as typeof query;
		}
 
		return query
			.orderBy(desc(schema.users.createdAt))
			.limit(limit)
			.offset(offset);
	}
 
	async count(filters: UserFilters = {}): Promise<number> {
		let query = this.db.select({ count: count() }).from(schema.users);
 
		if (filters.search) {
			const sanitized = sanitizeSearchInput(filters.search);
			const searchPattern = `%${sanitized}%`;
			query = query.where(
				or(
					like(schema.users.name, searchPattern),
					like(schema.users.email, searchPattern),
				),
			) as typeof query;
		}
 
		const result = await query;
		return result[0]?.count ?? 0;
	}
 
	async create(data: {
		id: string;
		name: string;
		email: string;
		emailVerified?: boolean;
		phoneNumber?: string;
	}): Promise<User> {
		const result = await this.db
			.insert(schema.users)
			.values({
				id: data.id,
				name: data.name,
				email: data.email,
				emailVerified: data.emailVerified ?? false,
				phoneNumberVerified: false,
				phoneNumber: data.phoneNumber,
				banned: false,
			})
			.returning();
		return result[0];
	}
 
	async update(
		id: string,
		data: Partial<
			Pick<
				User,
				| "name"
				| "email"
				| "emailVerified"
				| "phoneNumber"
				| "image"
				| "themePreference"
			>
		>,
	): Promise<User | null> {
		const result = await this.db
			.update(schema.users)
			.set({
				...data,
				updatedAt: new Date(),
			})
			.where(eq(schema.users.id, id))
			.returning();
		return result[0] ?? null;
	}
 
	async setBanned(
		id: string,
		banned: boolean,
		banReason?: string,
	): Promise<User | null> {
		const result = await this.db
			.update(schema.users)
			.set({
				banned,
				banReason: banned ? banReason : null,
				updatedAt: new Date(),
			})
			.where(eq(schema.users.id, id))
			.returning();
		return result[0] ?? null;
	}
 
	async delete(id: string): Promise<boolean> {
		const result = await this.db
			.delete(schema.users)
			.where(eq(schema.users.id, id))
			.returning();
		return result.length > 0;
	}
 
	// Get user with their tenant roles
	async getWithRoles(id: string): Promise<{
		user: User;
		roles: UserTenantRole[];
	} | null> {
		const user = await this.findById(id);
		if (!user) return null;
 
		const roles = await this.db
			.select()
			.from(schema.userTenantRoles)
			.where(eq(schema.userTenantRoles.userId, id));
 
		return { user, roles };
	}
 
	// Get account for password operations (Better Auth stores hashed password in accounts table)
	async getAccount(userId: string): Promise<Account | null> {
		const result = await this.db
			.select()
			.from(schema.accounts)
			.where(eq(schema.accounts.userId, userId))
			.limit(1);
		return result[0] ?? null;
	}
 
	// Update password via accounts table
	async updatePassword(
		userId: string,
		hashedPassword: string,
	): Promise<boolean> {
		const result = await this.db
			.update(schema.accounts)
			.set({
				password: hashedPassword,
				updatedAt: new Date(),
			})
			.where(eq(schema.accounts.userId, userId))
			.returning();
		return result.length > 0;
	}
 
	// Create account for Better Auth (stores password)
	async createAccount(data: {
		id: string;
		userId: string;
		hashedPassword: string;
	}): Promise<Account> {
		const result = await this.db
			.insert(schema.accounts)
			.values({
				id: data.id,
				userId: data.userId,
				accountId: data.userId,
				providerId: "credential",
				password: data.hashedPassword,
			})
			.returning();
		return result[0];
	}
}