2023-04-12 01:59:14 -07:00
|
|
|
import { Service } from 'typedi';
|
2023-12-28 04:14:10 -08:00
|
|
|
import { DataSource, In, Not, Repository } from 'typeorm';
|
2023-04-12 01:59:14 -07:00
|
|
|
import { SharedCredentials } from '../entities/SharedCredentials';
|
2023-11-03 09:20:54 -07:00
|
|
|
import type { User } from '../entities/User';
|
2023-12-28 04:14:10 -08:00
|
|
|
import type { Role } from '../entities/Role';
|
2023-04-12 01:59:14 -07:00
|
|
|
|
|
|
|
@Service()
|
|
|
|
export class SharedCredentialsRepository extends Repository<SharedCredentials> {
|
|
|
|
constructor(dataSource: DataSource) {
|
|
|
|
super(SharedCredentials, dataSource.manager);
|
|
|
|
}
|
2023-11-03 09:20:54 -07:00
|
|
|
|
|
|
|
/** Get a credential if it has been shared with a user */
|
|
|
|
async findCredentialForUser(credentialsId: string, user: User) {
|
|
|
|
const sharedCredential = await this.findOne({
|
|
|
|
relations: ['credentials'],
|
|
|
|
where: {
|
|
|
|
credentialsId,
|
2023-12-19 04:52:42 -08:00
|
|
|
...(!user.hasGlobalScope('credential:read') ? { userId: user.id } : {}),
|
2023-11-03 09:20:54 -07:00
|
|
|
},
|
|
|
|
});
|
|
|
|
if (!sharedCredential) return null;
|
|
|
|
return sharedCredential.credentials;
|
|
|
|
}
|
2023-12-28 00:27:38 -08:00
|
|
|
|
|
|
|
async findByCredentialIds(credentialIds: string[]) {
|
|
|
|
return this.find({
|
|
|
|
relations: ['credentials', 'role', 'user'],
|
|
|
|
where: {
|
|
|
|
credentialsId: In(credentialIds),
|
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
2023-12-28 04:14:10 -08:00
|
|
|
|
|
|
|
async makeOwnerOfAllCredentials(user: User, role: Role) {
|
|
|
|
return this.update({ userId: Not(user.id), roleId: role.id }, { user });
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get the IDs of all credentials owned by or shared with a user.
|
|
|
|
*/
|
|
|
|
async getAccessibleCredentials(userId: string) {
|
|
|
|
const sharings = await this.find({
|
|
|
|
relations: ['role'],
|
|
|
|
where: {
|
|
|
|
userId,
|
|
|
|
role: { name: In(['owner', 'user']), scope: 'credential' },
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
return sharings.map((s) => s.credentialsId);
|
|
|
|
}
|
2023-04-12 01:59:14 -07:00
|
|
|
}
|