-
Notifications
You must be signed in to change notification settings - Fork 70
/
group-tenant.interceptor.ts
75 lines (69 loc) · 2.18 KB
/
group-tenant.interceptor.ts
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
// Copyright (c) 2023 Sourcefuse Technologies
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
import {
inject,
/* inject, */
injectable,
Interceptor,
InvocationContext,
InvocationResult,
Provider,
ValueOrPromise,
} from '@loopback/core';
import {repository} from '@loopback/repository';
import {HttpErrors} from '@loopback/rest';
import {IAuthUserWithPermissions} from '@sourceloop/core';
import {AuthenticationBindings} from 'loopback4-authentication';
import {UserTenantServiceKey} from '../keys';
import {GroupRepository} from '../repositories';
/**
* This class will be bound to the application as an `Interceptor` during
* `boot`
*/
@injectable({tags: {key: GroupTenantInterceptor.BINDING_KEY}})
export class GroupTenantInterceptor implements Provider<Interceptor> {
static readonly BINDING_KEY = UserTenantServiceKey.GroupTenantInterceptor;
constructor(
@repository(GroupRepository) protected groupRepository: GroupRepository,
@inject(AuthenticationBindings.CURRENT_USER)
protected currentUser: IAuthUserWithPermissions,
) {}
/**
* This method is used by LoopBack context to produce an interceptor function
* for the binding.
*
* @returns An interceptor function
*/
value() {
return this.intercept.bind(this);
}
/**
* The logic to intercept an invocation
* @param invocationCtx - Invocation context
* @param next - A function to invoke next interceptor or the target method
*/
async intercept(
invocationCtx: InvocationContext,
next: () => ValueOrPromise<InvocationResult>,
) {
try {
/**
* Interceptors are applied to methods in which the groupId is a parameter within the API endpoint,
* which is why we can anticipate that groupId will be the first argument in the invocationCtx.
*/
const groupId = invocationCtx.args[0];
const groups = await this.groupRepository.find({
where: {id: groupId},
});
if (!groups.length) {
throw new HttpErrors.Forbidden('Group Access Not Allowed');
}
const result = await next();
return result;
} catch (err) {
throw new HttpErrors.Forbidden(err);
}
}
}