-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathnotePublicOrUserInTeam.ts
More file actions
54 lines (45 loc) · 1.86 KB
/
notePublicOrUserInTeam.ts
File metadata and controls
54 lines (45 loc) · 1.86 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
import { isEmpty } from '@infrastructure/utils/empty.js';
import { notEmpty } from '@infrastructure/utils/empty.js';
import type { PolicyContext } from '@presentation/http/types/PolicyContext.js';
import { getRequestLogger } from '@infrastructure/logging/index.js';
/**
* Policy to check does user have permission to access note
* @param context - Context, object containing Fatify request, Fastify reply and domain services
*/
export default async function notePublicOrUserInTeam(context: PolicyContext): Promise<void> {
const { request, reply, domainServices } = context;
const logger = getRequestLogger('policies');
const { userId } = request;
/**
* If note or noteSettings not resolved, we can't check permissions
*/
if (isEmpty(request.note) || isEmpty(request.noteSettings)) {
logger.warn('Note or note settings not found');
return await reply.notAcceptable('Note not found');
};
const { isPublic } = request.noteSettings;
let memberRole;
/**
* If user is not authorized, we can't check his role
* If note is public, we don't need to check for the role
*/
if (notEmpty(userId) && isPublic === false) {
memberRole = await domainServices.noteSettingsService.getUserRoleByUserIdAndNoteId(userId, request.note.id);
}
/**
* If note is public, everyone can access it
* If note is private, only team member can access it
*/
if (isPublic === false) {
/** If user is unathorized we return 401 unauthorized */
if (isEmpty(userId)) {
logger.warn('Unauthorized user trying to access private note');
return await reply.unauthorized();
/** If user is authorized, but is not in the team, we return 403 forbidden */
} else if (isEmpty(memberRole)) {
logger.warn('User not in team for private note');
return await reply.forbidden();
}
}
logger.debug('Note access check completed successfully');
}