Files
directus/api/src/controllers/users.ts
Rijk van Zanten 32dd709778 Insights 2.0 (#14096)
* query function added to list

* dashboard reading query, adding to object

* typecasting of filter vals needed still

* numbers accepting strings too

* json-to-graphql-query => devD

* fixed unneeded return in list index.ts

* stitching and calling but not actually calling

* calls on panel change

* query object += new panel before dashboard save

* uuid generated in app not api

* fixed panel ids in query

* fixed the tests I just wrote

* passing the query data down!

* list showing data

* objDiff test moved to test

* metric bug fixes + data

* dashboard logic

* time series conversion started

* timeseries GQL query almost there

* query querying

* chart loading

* aggregate handling improved

* error handling for aggregate+filter errors

* removed query on empty queryObj

* maybe more error handling

* more error handling working

* improvements to erorr handling

* stitchGQL() error return type corrected

* added string fields to COUNT

* pushing up but needs work

* not an endless recursion

* its not pretty but it works.

* throws an error

* system collections supported

* refactor to solve some errors

* loading correct

* metric function fixed

* data loading but not blocking rendering

* removed redundant code.

* relational fields

* deep nesting relations

* options.precision has a default

* relational fields fix. (thanks azri)

* the limit

* limit and time series

* range has a default

* datat to workspace

* v-if

* panels loading

* workspaces dont get data anymore

* package.json

* requested changes

* loading

* get groups util

* timeseries => script setup

* list => script setup

* metric => script setup

* label => script setup

* declare optional props

* loadingPanels: only loading spinner on loading panels

* remove unneeded parseDate!!

* applyDataToPanels tests

* -.only

* remove unneeded steps

* processQuery tests

* tests

* removed unused var

* jest.config and some queryCaller tests

* one more test

* query tests

* typo

* clean up

* fix some but not all bugs

* bugs from merge fixed

* Start cleaning up 🧹

* Refactor custom input type

* Small tweaks in list index

* Cleanup imports

* Require Query object to be returned from query prop

* Tweak return statement

* Fix imports

* Cleanup metric watch effect

* Tweaks tweaks tweaks

* Don't rely on options, simplify fetch logic

* Add paths to validation errors

* [WIP] Start handling things in the store

* Rework query fetching logic into store

* Clean up data passing

* Use composition setup for insights store

* Remove outdated

* Fix missing return

* Allow batch updating in REST API

Allows sending an array of partial items to the endpoints, updating all to their own values

* Add batch update to graphql

* Start integrating edits

* Readd clear

* Add deletion

* Add duplication

* Finish create flow

* Resolve cache refresh on panel config

* Prevent warnings about component name

* Improve loading state

* Finalize dashboard overhaul

* Add auto-refresh sidebar detail

* Add efficient panel reloading

* Set/remove errors on succeeded requests

* Move options rendering to shared

* Fix wrong imports, render options in app

* Selectively reload panels with changed variables

* Ensure newly added panels don't lose data

* Only refresh panel if data query changed

* Never use empty filter object in metric query

* Add default value support to variable panel

* Centralize no-data state

* Only reload data on var change when query is altered

* Fix build

* Fix time series order

* Remove unused utils

* Remove no-longer-used logic

* Mark batch update result as non-nullable in GraphQL schema

* Interim flows fix

* Skip parsing undefined keys

* Refresh insights dashboard when discarding changes

* Don't submit primary key when updating batch

* Handle null prop field better

* Tweak panel padding

Co-authored-by: jaycammarano <jay.cammarano@gmail.com>
Co-authored-by: Azri Kahar <42867097+azrikahar@users.noreply.github.com>
Co-authored-by: ian <licitdev@gmail.com>
2022-06-27 15:26:42 -04:00

485 lines
12 KiB
TypeScript

import express from 'express';
import Joi from 'joi';
import { InvalidCredentialsException, ForbiddenException, InvalidPayloadException } from '../exceptions';
import { respond } from '../middleware/respond';
import useCollection from '../middleware/use-collection';
import { validateBatch } from '../middleware/validate-batch';
import { AuthenticationService, MetaService, UsersService, RolesService, TFAService } from '../services';
import { PrimaryKey } from '../types';
import asyncHandler from '../utils/async-handler';
import { Role } from '@directus/shared/types';
const router = express.Router();
router.use(useCollection('directus_users'));
router.post(
'/',
asyncHandler(async (req, res, next) => {
const service = new UsersService({
accountability: req.accountability,
schema: req.schema,
});
const savedKeys: PrimaryKey[] = [];
if (Array.isArray(req.body)) {
const keys = await service.createMany(req.body);
savedKeys.push(...keys);
} else {
const key = await service.createOne(req.body);
savedKeys.push(key);
}
try {
if (Array.isArray(req.body)) {
const items = await service.readMany(savedKeys, req.sanitizedQuery);
res.locals.payload = { data: items };
} else {
const item = await service.readOne(savedKeys[0], req.sanitizedQuery);
res.locals.payload = { data: item };
}
} catch (error: any) {
if (error instanceof ForbiddenException) {
return next();
}
throw error;
}
return next();
}),
respond
);
const readHandler = asyncHandler(async (req, res, next) => {
const service = new UsersService({
accountability: req.accountability,
schema: req.schema,
});
const metaService = new MetaService({
accountability: req.accountability,
schema: req.schema,
});
const item = await service.readByQuery(req.sanitizedQuery);
const meta = await metaService.getMetaForQuery('directus_users', req.sanitizedQuery);
res.locals.payload = { data: item || null, meta };
return next();
});
router.get('/', validateBatch('read'), readHandler, respond);
router.search('/', validateBatch('read'), readHandler, respond);
router.get(
'/me',
asyncHandler(async (req, res, next) => {
if (req.accountability?.share_scope) {
const user = {
share: req.accountability?.share,
role: {
id: req.accountability.role,
admin_access: false,
app_access: false,
},
};
res.locals.payload = { data: user };
return next();
}
if (!req.accountability?.user) {
throw new InvalidCredentialsException();
}
const service = new UsersService({
accountability: req.accountability,
schema: req.schema,
});
try {
const item = await service.readOne(req.accountability.user, req.sanitizedQuery);
res.locals.payload = { data: item || null };
} catch (error: any) {
if (error instanceof ForbiddenException) {
res.locals.payload = { data: { id: req.accountability.user } };
return next();
}
throw error;
}
return next();
}),
respond
);
router.get(
'/:pk',
asyncHandler(async (req, res, next) => {
if (req.path.endsWith('me')) return next();
const service = new UsersService({
accountability: req.accountability,
schema: req.schema,
});
const items = await service.readOne(req.params.pk, req.sanitizedQuery);
res.locals.payload = { data: items || null };
return next();
}),
respond
);
router.patch(
'/me',
asyncHandler(async (req, res, next) => {
if (!req.accountability?.user) {
throw new InvalidCredentialsException();
}
const service = new UsersService({
accountability: req.accountability,
schema: req.schema,
});
const primaryKey = await service.updateOne(req.accountability.user, req.body);
const item = await service.readOne(primaryKey, req.sanitizedQuery);
res.locals.payload = { data: item || null };
return next();
}),
respond
);
router.patch(
'/me/track/page',
asyncHandler(async (req, _res, next) => {
if (!req.accountability?.user) {
throw new InvalidCredentialsException();
}
if (!req.body.last_page) {
throw new InvalidPayloadException(`"last_page" key is required.`);
}
const service = new UsersService({ schema: req.schema });
await service.updateOne(req.accountability.user, { last_page: req.body.last_page });
return next();
}),
respond
);
router.patch(
'/',
validateBatch('update'),
asyncHandler(async (req, res, next) => {
const service = new UsersService({
accountability: req.accountability,
schema: req.schema,
});
let keys: PrimaryKey[] = [];
if (Array.isArray(req.body)) {
keys = await service.updateBatch(req.body);
} else if (req.body.keys) {
keys = await service.updateMany(req.body.keys, req.body.data);
} else {
keys = await service.updateByQuery(req.body.query, req.body.data);
}
try {
const result = await service.readMany(keys, req.sanitizedQuery);
res.locals.payload = { data: result };
} catch (error: any) {
if (error instanceof ForbiddenException) {
return next();
}
throw error;
}
return next();
}),
respond
);
router.patch(
'/:pk',
asyncHandler(async (req, res, next) => {
const service = new UsersService({
accountability: req.accountability,
schema: req.schema,
});
const primaryKey = await service.updateOne(req.params.pk, req.body);
try {
const item = await service.readOne(primaryKey, req.sanitizedQuery);
res.locals.payload = { data: item || null };
} catch (error: any) {
if (error instanceof ForbiddenException) {
return next();
}
throw error;
}
return next();
}),
respond
);
router.delete(
'/',
validateBatch('delete'),
asyncHandler(async (req, _res, next) => {
const service = new UsersService({
accountability: req.accountability,
schema: req.schema,
});
if (Array.isArray(req.body)) {
await service.deleteMany(req.body);
} else if (req.body.keys) {
await service.deleteMany(req.body.keys);
} else {
await service.deleteByQuery(req.body.query);
}
return next();
}),
respond
);
router.delete(
'/:pk',
asyncHandler(async (req, _res, next) => {
const service = new UsersService({
accountability: req.accountability,
schema: req.schema,
});
await service.deleteOne(req.params.pk);
return next();
}),
respond
);
const inviteSchema = Joi.object({
email: Joi.alternatives(Joi.string().email(), Joi.array().items(Joi.string().email())).required(),
role: Joi.string().uuid({ version: 'uuidv4' }).required(),
invite_url: Joi.string().uri(),
});
router.post(
'/invite',
asyncHandler(async (req, _res, next) => {
const { error } = inviteSchema.validate(req.body);
if (error) throw new InvalidPayloadException(error.message);
const service = new UsersService({
accountability: req.accountability,
schema: req.schema,
});
await service.inviteUser(req.body.email, req.body.role, req.body.invite_url || null);
return next();
}),
respond
);
const acceptInviteSchema = Joi.object({
token: Joi.string().required(),
password: Joi.string().required(),
});
router.post(
'/invite/accept',
asyncHandler(async (req, _res, next) => {
const { error } = acceptInviteSchema.validate(req.body);
if (error) throw new InvalidPayloadException(error.message);
const service = new UsersService({
accountability: req.accountability,
schema: req.schema,
});
await service.acceptInvite(req.body.token, req.body.password);
return next();
}),
respond
);
router.post(
'/me/tfa/generate/',
asyncHandler(async (req, res, next) => {
if (!req.accountability?.user) {
throw new InvalidCredentialsException();
}
if (!req.body.password) {
throw new InvalidPayloadException(`"password" is required`);
}
const service = new TFAService({
accountability: req.accountability,
schema: req.schema,
});
const authService = new AuthenticationService({
accountability: req.accountability,
schema: req.schema,
});
await authService.verifyPassword(req.accountability.user, req.body.password);
const { url, secret } = await service.generateTFA(req.accountability.user);
res.locals.payload = { data: { secret, otpauth_url: url } };
return next();
}),
respond
);
router.post(
'/me/tfa/enable/',
asyncHandler(async (req, _res, next) => {
if (!req.accountability?.user) {
throw new InvalidCredentialsException();
}
if (!req.body.secret) {
throw new InvalidPayloadException(`"secret" is required`);
}
if (!req.body.otp) {
throw new InvalidPayloadException(`"otp" is required`);
}
// Override permissions only when enforce TFA is enabled in role
if (req.accountability.role) {
const rolesService = new RolesService({
schema: req.schema,
});
const role = (await rolesService.readOne(req.accountability.role)) as Role;
if (role && role.enforce_tfa) {
const existingPermission = await req.accountability.permissions?.find(
(p) => p.collection === 'directus_users' && p.action === 'update'
);
if (existingPermission) {
existingPermission.fields = ['tfa_secret'];
existingPermission.permissions = { id: { _eq: req.accountability.user } };
existingPermission.presets = null;
existingPermission.validation = null;
} else {
(req.accountability.permissions || (req.accountability.permissions = [])).push({
action: 'update',
collection: 'directus_users',
fields: ['tfa_secret'],
permissions: { id: { _eq: req.accountability.user } },
presets: null,
role: req.accountability.role,
validation: null,
});
}
}
}
const service = new TFAService({
accountability: req.accountability,
schema: req.schema,
});
await service.enableTFA(req.accountability.user, req.body.otp, req.body.secret);
return next();
}),
respond
);
router.post(
'/me/tfa/disable',
asyncHandler(async (req, _res, next) => {
if (!req.accountability?.user) {
throw new InvalidCredentialsException();
}
if (!req.body.otp) {
throw new InvalidPayloadException(`"otp" is required`);
}
// Override permissions only when enforce TFA is enabled in role
if (req.accountability.role) {
const rolesService = new RolesService({
schema: req.schema,
});
const role = (await rolesService.readOne(req.accountability.role)) as Role;
if (role && role.enforce_tfa) {
const existingPermission = await req.accountability.permissions?.find(
(p) => p.collection === 'directus_users' && p.action === 'update'
);
if (existingPermission) {
existingPermission.fields = ['tfa_secret'];
existingPermission.permissions = { id: { _eq: req.accountability.user } };
existingPermission.presets = null;
existingPermission.validation = null;
} else {
(req.accountability.permissions || (req.accountability.permissions = [])).push({
action: 'update',
collection: 'directus_users',
fields: ['tfa_secret'],
permissions: { id: { _eq: req.accountability.user } },
presets: null,
role: req.accountability.role,
validation: null,
});
}
}
}
const service = new TFAService({
accountability: req.accountability,
schema: req.schema,
});
const otpValid = await service.verifyOTP(req.accountability.user, req.body.otp);
if (otpValid === false) {
throw new InvalidPayloadException(`"otp" is invalid`);
}
await service.disableTFA(req.accountability.user);
return next();
}),
respond
);
router.post(
'/:pk/tfa/disable',
asyncHandler(async (req, _res, next) => {
if (!req.accountability?.user) {
throw new InvalidCredentialsException();
}
if (!req.accountability.admin || !req.params.pk) {
throw new ForbiddenException();
}
const service = new TFAService({
accountability: req.accountability,
schema: req.schema,
});
await service.disableTFA(req.params.pk);
return next();
}),
respond
);
export default router;