Files
directus/api/src/services/activity.ts
Rijk van Zanten dbf35a1736 Add ability to share items with people outside the platform (#10663)
* Add directus_shares

* Don't check for usage limit on refresh

* Add all endpoints to the shares controller

* Move route `/auth/shared` to `/shared/auth`

* Add password protection

* Add `share` action in permissions

* Add `shares/:pk/info`

* Start on shared-view

* Add basic styling for full shared view

* Fixed migrations

* Add inline style for shared view

* Allow title override

* Finish /info endpoint for shares

* Add basic UUID validation to share/info endpont

* Add UUID validation to other routes

* Add not found state

* Cleanup /extract/finish share login endpoint

* Cleanup auth

* Added `share_start` and `share_end`

* Add share sidebar details.

* Allow share permissions configuration

* Hide the `new_share` button for unauthorized users

* Fix uses_left displayed value

* Show expired / upcoming shares

* Improved expired/upcoming styling

* Fixed share login query

* Fix check-ip and get-permissions middlewares behaviour when role is null

* Simplify cache key

* Fix typescript linting issues

* Handle app auth flow for shared page

* Fixed /users/me response

* Show when user is authenticated

* Try showing item drawer in shared page

* Improved shared card styling

* Add shares permissions and change share card styling

* Pull in schema/permissions on share

* Create getPermissionForShare file

* Change getPermissionsForShare signature

* Render form + item on share after auth

* Finalize public front end

* Handle fake o2m field in applyQuery

* [WIP]

* New translations en-US.yaml (Bulgarian) (#10585)

* smaller label height (#10587)

* Update to the latest Material Icons (#10573)

The icons are based on https://fonts.google.com/icons

* New translations en-US.yaml (Arabic) (#10593)

* New translations en-US.yaml (Arabic) (#10594)

* New translations en-US.yaml (Portuguese, Brazilian) (#10604)

* New translations en-US.yaml (French) (#10605)

* New translations en-US.yaml (Italian) (#10613)

* fix M2A list not updating (#10617)

* Fix filters

* Add admin filter on m2o role selection

* Add admin filter on m2o role selection

* Add o2m permissions traversing

* Finish relational tree permissions generation

* Handle implicit a2o relation

* Update implicit relation regex

* Fix regex

* Fix implicitRelation unnesting for new regex

* Fix implicitRelation length check

* Rename m2a to a2o internally

* Add auto-gen permissions for a2o

* [WIP] Improve share UX

* Add ctx menu options

* Add share dialog

* Add email notifications

* Tweak endpoint

* Tweak file interface disabled state

* Add nicer invalid state to password input

* Dont return info for expired/upcoming shares

* Tweak disabled state for relational interfaces

* Fix share button for non admin roles

* Show/hide edit/delete based on permissions to shares

* Fix imports of mutationtype

* Resolve (my own) suggestions

* Fix migration for ms sql

* Resolve last suggestion

Co-authored-by: Oreilles <oreilles.github@nitoref.io>
Co-authored-by: Oreilles <33065839+oreilles@users.noreply.github.com>
Co-authored-by: Ben Haynes <ben@rngr.org>
Co-authored-by: Thien Nguyen <72242664+tatthien@users.noreply.github.com>
Co-authored-by: Azri Kahar <42867097+azrikahar@users.noreply.github.com>
2021-12-23 18:51:59 -05:00

110 lines
3.8 KiB
TypeScript

import { AbstractServiceOptions, PrimaryKey, Item, Action } from '../types';
import { ItemsService } from './items';
import { MutationOptions } from '../types';
import { NotificationsService } from './notifications';
import { UsersService } from './users';
import { AuthorizationService } from './authorization';
import { Accountability } from '@directus/shared/types';
import { getPermissions } from '../utils/get-permissions';
import { ForbiddenException } from '../exceptions/forbidden';
import logger from '../logger';
import { userName } from '../utils/user-name';
import { uniq } from 'lodash';
import env from '../env';
import validateUUID from 'uuid-validate';
export class ActivityService extends ItemsService {
notificationsService: NotificationsService;
usersService: UsersService;
constructor(options: AbstractServiceOptions) {
super('directus_activity', options);
this.notificationsService = new NotificationsService({ schema: this.schema });
this.usersService = new UsersService({ schema: this.schema });
}
async createOne(data: Partial<Item>, opts?: MutationOptions): Promise<PrimaryKey> {
if (data.action === Action.COMMENT && typeof data.comment === 'string') {
const usersRegExp = new RegExp(/@[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}/gi);
const mentions = uniq(data.comment.match(usersRegExp) ?? []);
const sender = await this.usersService.readOne(this.accountability!.user!, {
fields: ['id', 'first_name', 'last_name', 'email'],
});
for (const mention of mentions) {
const userID = mention.substring(1);
const user = await this.usersService.readOne(userID, {
fields: ['id', 'first_name', 'last_name', 'email', 'role.id', 'role.admin_access', 'role.app_access'],
});
const accountability: Accountability = {
user: userID,
role: user.role?.id ?? null,
admin: user.role?.admin_access ?? null,
app: user.role?.app_access ?? null,
};
accountability.permissions = await getPermissions(accountability, this.schema);
const authorizationService = new AuthorizationService({ schema: this.schema, accountability });
const usersService = new UsersService({ schema: this.schema, accountability });
try {
await authorizationService.checkAccess('read', data.collection, data.item);
const templateData = await usersService.readByQuery({
fields: ['id', 'first_name', 'last_name', 'email'],
filter: { id: { _in: mentions.map((mention) => mention.substring(1)) } },
});
const userPreviews = templateData.reduce((acc, user) => {
acc[user.id] = `<em>${userName(user)}</em>`;
return acc;
}, {} as Record<string, string>);
let comment = data.comment;
for (const mention of mentions) {
const uuid = mention.substring(1);
// We only match on UUIDs in the first place. This is just an extra sanity check
if (validateUUID(uuid) === false) continue;
comment = comment.replace(new RegExp(mention, 'gm'), userPreviews[uuid] ?? '@Unknown User');
}
comment = `> ${comment.replace(/\n+/gm, '\n> ')}`;
const message = `
Hello ${userName(user)},
${userName(sender)} has mentioned you in a comment:
${comment}
<a href="${env.PUBLIC_URL}/admin/content/${data.collection}/${data.item}">Click here to view.</a>
`;
await this.notificationsService.createOne({
recipient: userID,
sender: sender.id,
subject: `You were mentioned in ${data.collection}`,
message,
collection: data.collection,
item: data.item,
});
} catch (err: any) {
if (err instanceof ForbiddenException) {
logger.warn(`User ${userID} doesn't have proper permissions to receive notification for this item.`);
} else {
throw err;
}
}
}
}
return super.createOne(data, opts);
}
}