forked from Yara724/api
Fixed users not being able to view their files
This commit is contained in:
52
src/helpers/user-access-resolver.ts
Normal file
52
src/helpers/user-access-resolver.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import { Types } from "mongoose";
|
||||
import { buildUserLookupByPhone } from "./iran-mobile";
|
||||
import { UserDbService } from "src/users/entities/db-service/user.db.service";
|
||||
import { collectUserIdVariants } from "./party-access-queries";
|
||||
|
||||
/** All Mongo user ids that may represent the same person (JWT sub + phone aliases). */
|
||||
export async function resolveLinkedUserIdStrings(
|
||||
userDbService: UserDbService,
|
||||
actor: { sub?: string; username?: string },
|
||||
): Promise<string[]> {
|
||||
const ids = new Set<string>();
|
||||
if (actor?.sub) ids.add(String(actor.sub));
|
||||
|
||||
if (actor?.username?.trim()) {
|
||||
const rows = await userDbService.findAllByPhone(actor.username);
|
||||
for (const row of rows) {
|
||||
const id = (row as { _id?: unknown })._id;
|
||||
if (id != null) ids.add(String(id));
|
||||
}
|
||||
}
|
||||
|
||||
return [...ids];
|
||||
}
|
||||
|
||||
export async function resolveLinkedUserIdVariants(
|
||||
userDbService: UserDbService,
|
||||
actor: { sub?: string; username?: string },
|
||||
): Promise<unknown[]> {
|
||||
const strings = await resolveLinkedUserIdStrings(userDbService, actor);
|
||||
return collectUserIdVariants(...strings);
|
||||
}
|
||||
|
||||
export function ownerUserIdMatchesActor(
|
||||
ownerUserId: unknown,
|
||||
linkedUserIdStrings: string[],
|
||||
): boolean {
|
||||
if (ownerUserId == null || linkedUserIdStrings.length === 0) return false;
|
||||
const owner = String(ownerUserId);
|
||||
return linkedUserIdStrings.some((id) => id === owner);
|
||||
}
|
||||
|
||||
export function buildOwnerUserIdAccessFilter(
|
||||
linkedUserIdVariants: unknown[],
|
||||
): Record<string, unknown> | null {
|
||||
if (!linkedUserIdVariants.length) return null;
|
||||
if (linkedUserIdVariants.length === 1) {
|
||||
return { "owner.userId": linkedUserIdVariants[0] };
|
||||
}
|
||||
return {
|
||||
$or: linkedUserIdVariants.map((id) => ({ "owner.userId": id })),
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user