[CORL-523] Document GraphQL mutations for managing accounts (#2544)

* Create preliminary endpoint for updating user names via API

CORL-523

* Create preliminary endpoint for updating user emails via API

CORL-523

* Create preliminary endpoint for deleting users via the API

CORL-523

* Hook up the delete, update email, and update user name endpoints

CORL-523

* Update readme to include preliminary GDPR endpoint instructions

CORL-523

* Uncomment limiters on updateEmail endpoint

My mistake leaving these commented while testing, should not have been committed.

CORL-523

* Run DocToc on the README to generate table of contents

CORL-523

* feat: enhanced documentation on account management edges

* fix: prevent double delete of user account

* fix: swapped order of params

* Update README.md

* Update README.md

* fix: remove unknown field title

* fix: remove unknown field title on story
This commit is contained in:
Nick Funk
2019-09-10 07:16:40 -06:00
committed by Vinh
parent e86e9d2c68
commit f9e1bf144e
7 changed files with 530 additions and 211 deletions
+232 -4
View File
@@ -21,10 +21,18 @@ Preview Coral easily by running Coral via a Heroku App:
- [Source](#source)
- [Embed On Your Site](#embed-on-your-site)
- [Single Sign On](#single-sign-on)
- [SSO Login Prompts](#sso-login-prompts)
- [External Integrations](#external-integrations)
- [Login Prompts](#login-prompts)
- [Development](#development)
- [Email](#email)
- [Design Language System (UI Components)](#design-language-system-ui-components)
- [GraphQL API](#graphql-api)
- [Making your first request](#making-your-first-request)
- [Understanding the response](#understanding-the-response)
- [Authorizing a request](#authorizing-a-request)
- [Bearer Token](#bearer-token)
- [Cookie](#cookie)
- [Persisted Queries](#persisted-queries)
- [Configuration](#configuration)
- [License](#license)
@@ -246,7 +254,27 @@ embed.login("{{ SSO_TOKEN }}");
embed.logout();
```
#### SSO Login Prompts
#### External Integrations
You can integrate directly with the Coral GraphQL API in order to facilitate
account updates for your users when using Coral SSO. The relevant mutations are
as follows:
- `updateUserUsername` lets you update a given user with a new username using
an admin token.
- `updateUserEmail` lets you update a given user with a new email address
using an admin token.
- `deleteUser` lets you delete a given account using an admin token.
Note that even with an admin token, you may not delete yourself via
this method, and instead must use the `requestAccountDeletion`
mutation instead. This differs from the `requestAccountDeletion` as
it does the operation immediately instead of scheduling it as
`requestAccountDeletion` does.
- `requestUserCommentsDownload` lets you retrieve a given account's comments download. This mutation will provide you with a `archiveURL` that can be used to download a ZIP file containing the user's comment export.
If you're unsure on how to call GraphQL API's, refer to the section here on [Making your first GraphQL request](#making-your-first-request).
#### Login Prompts
In order to handle login prompts (e.g. a user clicks on the sign in button) you can listen to the `loginPrompt` event.
@@ -364,6 +392,207 @@ npm run docz -- dev
After compilation has finished you can access docz at http://localhost:3030/.
## GraphQL API
Our API is generally served via GraphQL at `/api/graphql` on your Coral installation. If you're running Coral locally, this would be https://localhost:8080/api/graphql.
You can enable the GraphiQL interface at https://localhost:3000/graphiql (Note the port number here is not 8080, this is because this route is directly served by the server, and not the webpack development server) when running in development to access a GraphQL playground to use with documentation provided in the sidebar on what edges are available to you. You can do this by setting `ENABLE_GRAPHIQL=true`. **(🚨 Note 🚨) we do not recommend using this in production environments as it disables many safety features used by the application**.
### Making your first request
To learn a bit about how to interact with Coral, we'll query for comments on a
page of Coral.
The GraphQL endpoint we have can be used with any HTTP client available, but our
examples below will use the common `curl` tool:
```sh
curl --request POST \
--url "http://localhost:8080/api/graphql" \
--header "content-type: application/json" \
--data '{"query":"query GetComments($url: String!) {story(url: $url) { id metadata { title } url comments { nodes { id body author { id username } } } } }","variables":{"url":"http://localhost:8080/"},"operationName":"GetComments"}'
```
When you unpack that, it's really quite simple. We're executing a `POST` request
to the `/api/graphql` route of the local Talk server with the GraphQL
request we want to make. It's composed of the `query`, `variables`, and
`operationName`.
```graphql
query GetComments($url: String!) {
story(url: $url) {
metadata {
title
}
url
comments {
nodes {
body
author {
username
}
}
}
}
}
```
We are grabbing the asset with the specified `$url`, and grabbing it's title and the comments under it.
We can then also specify our variables to the query being executed (in this
case, the url for the page where we have comments on our local install of Coral):
```json
{
"url": "http://localhost:8080/"
}
```
It's also sometimes common to have multiple queries within a query, which is
where the `operationName` comes into play, where we simply specify the named
query that we want to execute (in this case, `GetComments`).
To get a deeper understanding of GraphQL queries, read up on
[GraphQL Queries and Mutations](http://graphql.org/learn/queries/).
### Understanding the response
Once you completed the above GraphQL query with `curl`, you'll get a response
sort of like this:
```json
{
"data": {
"story": {
"metadata": {
"title": "Coral 5.0 Embed Stream"
},
"url": "http://localhost:8080/",
"comments": {
"nodes": [
{
"body": "First comment!",
"author": {
"username": "wyatt.johnson"
}
}
]
}
}
}
}
```
All of the parameters you requested should be available under the `data`
property. Any errors that you get would appear in a `errors` array at the top
level, like this:
```json
{
"errors": [
{
"message": "The specified story URL does not exist in the permitted domains list.",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": ["story"],
"extensions": {
"code": "STORY_URL_NOT_PERMITTED",
"id": "e255e860-d3ab-11e9-acdf-b9e9700f06fa",
"type": "INVALID_REQUEST_ERROR",
"message": "The specified story URL does not exist in the permitted domains list."
}
}
],
"data": {
"story": null
}
}
```
You should know that any property that is marked with a `!` is considered
required, and non-nullable, which means you can always guarantee on it being
there in your request if there were no errors.
### Authorizing a request
Some queries you may notice seem to return an error of
`USER_NOT_ENTITLED`. It's likely the case that you are making a request to a
route that requires authorization. You can perform authorization a few ways in
Talk.
Essentially, you need to get access to a JWT token that you can use to authorize
your requests.
```sh
curl --request POST \
--url http://localhost:3000/api/auth/local \
--header 'content-type: application/json' \
--data '{ "email": "${EMAIL}", "password": "${PASSWORD}"}'
```
Which returns a response similar to:
```json
{
"token": "${TOKEN}"
}
```
Where `${EMAIL}` is the email address of an admin user, and `${PASSWORD}` is the password for that admin user. This will generate a short term token (valid for 90 days). To generate a long lived access token (or Personal Access Token), you have to exchange the token generated above to create a new long lived token:
```sh
curl --request POST \
--url "http://localhost:3000/api/graphql" \
--header 'authorization: Bearer ${TOKEN}' \
--header 'content-type: application/json' \
--data '{"query":"mutation CreateAccessToken { createToken(input: { clientMutationId: \"\", name: \"My PAT\" }) { signedToken }}","operationName":"CreateAccessToken"}'
```
Which returns a response similar to:
```json
{
"data": {
"createToken": {
"signedToken": "${TOKEN}"
}
}
}
```
Where `${TOKEN}` in the request being from the previous set of login steps and returning a new `signedToken` as `${TOKEN}` which can be used instead of the previous `${TOKEN}` value in the below examples.
Once you have your access token, you can substitute it as `${TOKEN}` in your
`curl` request as follows:
#### Bearer Token
```sh
curl --request POST \
--url "http://localhost:8080/api/graphql" \
--header "content-type: application/json" \
--header "Authorization: Bearer ${TOKEN}" \
--data '{"query":"query GetComments($url: String!) {story(url: $url) { id metadata { title } url comments { nodes { id body author { id username } } } } }","variables":{"url":"http://localhost:8080/"},"operationName":"GetComments"}'
```
#### Cookie
```sh
curl --request POST \
--url "http://localhost:8080/api/graphql" \
--header "content-type: application/json" \
--cookie "authorization=${TOKEN}"
--data '{"query":"query GetComments($url: String!) {story(url: $url) { id metadata { title } url comments { nodes { id body author { id username } } } } }","variables":{"url":"http://localhost:8080/"},"operationName":"GetComments"}'
```
### Persisted Queries
You might see an error like `RAW_QUERY_NOT_AUTHORIZED`. This means that you attempted to use either no token, or a token from a user without admin privileges. In Coral, we whitelist the GraphQL mutations and queries that are performed by the applications for security reasons meaning that only admin users can make arbitrary queries against the GraphQL API.
## Configuration
The following environment variables can be set to configure the Coral Server. You
@@ -403,8 +632,7 @@ the variables in a `.env` file in the root of the project in a simple
(Default `false`)
- `LOCALE` - Specify the default locale to use for all requests without a locale
specified. (Default `en-US`)
- `ENABLE_GRAPHIQL` - When `true`, it will enable the `/graphiql` even in
production, use with care. (Default `false`)
- `ENABLE_GRAPHIQL` - When `true`, it will enable the GraphiQL interface at `/graphiql`. **(🚨 Note 🚨) we do not recommend using this in production environments as it disables many safety features used by the application**. (Default `false`)
- `CONCURRENCY` - The number of worker nodes to spawn to handle web traffic,
this should be tied to the number of CPU's available. (Default
`os.cpus().length`)
+28 -206
View File
@@ -1,13 +1,9 @@
import { DateTime } from "luxon";
import { Collection, Db } from "mongodb";
import { Db } from "mongodb";
import { CommentAction } from "coral-server/models/action/comment";
import { createCollection } from "coral-server/models/helpers";
import { Story } from "coral-server/models/story";
import { Tenant } from "coral-server/models/tenant";
import { User } from "coral-server/models/user";
import { retrieveUserScheduledForDeletion } from "coral-server/models/user";
import { MailerQueue } from "coral-server/queue/tasks/mailer";
import TenantCache from "coral-server/services/tenant/cache";
import { deleteUser } from "coral-server/services/users/delete";
import {
ScheduledJob,
@@ -15,17 +11,6 @@ import {
ScheduledJobGroup,
} from "./scheduled";
const BATCH_SIZE = 500;
// TODO: extract this out to a separate file so it can be re-used elsewhere
const collections = {
users: createCollection<User>("users"),
comments: createCollection<Comment>("comments"),
stories: createCollection<Story>("stories"),
tenants: createCollection<Tenant>("tenants"),
commentActions: createCollection<CommentAction>("commentActions"),
};
interface Options {
mongo: Db;
mailerQueue: MailerQueue;
@@ -58,25 +43,13 @@ const deleteScheduledAccounts: ScheduledJobCommand<Options> = async ({
while (true) {
const now = new Date();
const rescheduledDeletionDate = DateTime.fromJSDate(now)
.plus({ hours: 1 })
.toJSDate();
const { value: user } = await collections.users(mongo).findOneAndUpdate(
const user = await retrieveUserScheduledForDeletion(
mongo,
tenant.id,
{
tenantID: tenant.id,
scheduledDeletionDate: { $lte: now },
hours: 1,
},
{
$set: {
scheduledDeletionDate: rescheduledDeletionDate,
},
},
{
// We want to get back the user with
// modified scheduledDeletionDate
returnOriginal: false,
}
now
);
if (!user) {
log.debug("no more users were scheduled for deletion");
@@ -85,177 +58,26 @@ const deleteScheduledAccounts: ScheduledJobCommand<Options> = async ({
log.info({ userID: user.id }, "deleting user");
await deleteUser(mongo, mailerQueue, user.id, user.tenantID, now);
await deleteUser(mongo, user.id, tenant.id, now);
// If the user has an email, then send them a confirmation that their account
// was deleted.
if (user.email) {
await mailerQueue.add({
tenantID: tenant.id,
message: {
to: user.email,
},
template: {
name: "account-notification/delete-request-completed",
context: {
organizationContactEmail: tenant.organization.contactEmail,
organizationName: tenant.organization.name,
organizationURL: tenant.organization.url,
},
},
});
}
}
}
};
async function executeBulkOperations<T>(
collection: Collection<T>,
operations: any[]
) {
// TODO: (wyattjoh) fix types here to support actual types when upstream changes applied
const bulk: any = collection.initializeUnorderedBulkOp();
for (const operation of operations) {
bulk.raw(operation);
}
await bulk.execute();
}
interface Batch {
comments: any[];
stories: any[];
}
async function deleteUserActionCounts(
mongo: Db,
userID: string,
tenantID: string
) {
const batch: Batch = {
comments: [],
stories: [],
};
async function processBatch() {
await executeBulkOperations<Comment>(
collections.comments(mongo),
batch.comments
);
batch.comments = [];
await executeBulkOperations<Story>(
collections.stories(mongo),
batch.stories
);
batch.stories = [];
}
const cursor = collections
.commentActions(mongo)
.find({ tenantID, userID, actionType: "REACTION" });
while (await cursor.hasNext()) {
const action = await cursor.next();
if (!action) {
continue;
}
batch.comments.push({
updateOne: {
filter: { tenantID, id: action.commentID },
update: {
$inc: {
"revisions.$[revisions].actionCounts.REACTION": -1,
"actionCounts.REACTION": -1,
},
},
arrayFilters: [{ "revisions.id": action.commentRevisionID }],
},
});
batch.stories.push({
updateOne: {
filter: { tenantID, id: action.storyID },
update: {
$inc: {
"commentCounts.action.REACTION": -1,
},
},
},
});
if (
batch.comments.length >= BATCH_SIZE ||
batch.stories.length >= BATCH_SIZE
) {
await processBatch();
}
}
if (batch.comments.length > 0 || batch.stories.length > 0) {
await processBatch();
}
await collections.commentActions(mongo).deleteMany({
tenantID,
userID,
actionType: "REACTION",
});
}
async function deleteUserComments(
mongo: Db,
authorID: string,
tenantID: string
) {
await collections.comments(mongo).updateMany(
{ tenantID, authorID },
{
$set: {
authorID: null,
revisions: [],
tags: [],
deleted: true,
},
}
);
}
async function deleteUser(
mongo: Db,
mailer: MailerQueue,
userID: string,
tenantID: string,
now: Date
) {
const user = await collections.users(mongo).findOne({ id: userID, tenantID });
if (!user) {
throw new Error("could not find user by ID");
}
const tenant = await collections.tenants(mongo).findOne({ id: tenantID });
if (!tenant) {
throw new Error("could not find tenant by ID");
}
// Delete the user's action counts.
await deleteUserActionCounts(mongo, userID, tenantID);
// Delete the user's comments.
await deleteUserComments(mongo, userID, tenantID);
// Mark the user as deleted.
await collections.users(mongo).updateOne(
{ tenantID, id: userID },
{
$set: {
profiles: [],
deletedAt: now,
},
$unset: {
email: "",
},
}
);
// If the user has an email, then send them a confirmation that their account
// was deleted.
if (user.email) {
await mailer.add({
tenantID,
message: {
to: user.email,
},
template: {
name: "account-notification/delete-request-completed",
context: {
organizationContactEmail: tenant.organization.contactEmail,
organizationName: tenant.organization.name,
organizationURL: tenant.organization.url,
},
},
});
}
}
@@ -28,12 +28,14 @@ import {
updateUsernameByID,
} from "coral-server/services/users";
import { invite } from "coral-server/services/users/auth/invite";
import { deleteUser } from "coral-server/services/users/delete";
import {
GQLBanUserInput,
GQLCancelAccountDeletionInput,
GQLCreateTokenInput,
GQLDeactivateTokenInput,
GQLDeleteUserAccountInput,
GQLIgnoreUserInput,
GQLInviteUsersInput,
GQLRemoveUserBanInput,
@@ -135,6 +137,15 @@ export const Users = (ctx: TenantContext) => ({
),
{ "input.password": [ERROR_CODES.PASSWORD_INCORRECT] }
),
deleteAccount: async (
input: GQLDeleteUserAccountInput
): Promise<Readonly<User> | null> => {
if (input.userID === ctx.user!.id) {
throw new Error("cannot delete self immediately");
}
return deleteUser(ctx.mongo, input.userID, ctx.tenant.id, ctx.now);
},
cancelAccountDeletion: async (
input: GQLCancelAccountDeletionInput
): Promise<Readonly<User> | null> =>
@@ -209,4 +209,8 @@ export const Mutation: Required<GQLMutationTypeResolver<void>> = {
user: await ctx.mutators.Users.cancelAccountDeletion(input),
clientMutationId: input.clientMutationId,
}),
deleteUserAccount: async (source, { input }, ctx) => ({
user: await ctx.mutators.Users.deleteAccount(input),
clientMutationId: input.clientMutationId,
}),
};
@@ -4363,6 +4363,34 @@ type RequestAccountDeletionPayload {
clientMutationId: String!
}
##################
# deleteUserAccount
##################
input DeleteUserAccountInput {
"""
userID is the ID of the User being deleted.
"""
userID: ID!
"""
clientMutationId is required for Relay support.
"""
clientMutationId: String!
}
type DeleteUserAccountPayload {
"""
user is the User that was deleted.
"""
user: User
"""
clientMutationId is required for Relay support.
"""
clientMutationId: String!
}
##################
# cancelAccountDeletion
##################
@@ -5052,13 +5080,20 @@ type Mutation {
input: RequestAccountDeletionInput!
): RequestAccountDeletionPayload! @auth
"""
deleteUserAccount will delete the target user now.
"""
deleteUserAccount(input: DeleteUserAccountInput!): DeleteUserAccountPayload!
@auth(roles: [ADMIN])
"""
cancelAccountDeletion allows the current logged in User to cancel the
request to delete their account
"""
cancelAccountDeletion(
input: CancelAccountDeletionInput!
): CancelAccountDeletionPayload! @auth(permit: [SUSPENDED, BANNED, PENDING_DELETION])
): CancelAccountDeletionPayload!
@auth(permit: [SUSPENDED, BANNED, PENDING_DELETION])
"""
createToken allows an administrator to create a Token based on the current
+39
View File
@@ -1,4 +1,5 @@
import bcrypt from "bcryptjs";
import { DateTime, DurationObject } from "luxon";
import { Db, MongoError } from "mongodb";
import uuid from "uuid";
@@ -2136,3 +2137,41 @@ export async function pullUserNotificationDigests(
return result.value || null;
}
/**
* retrieveUserScheduledForDeletion will return a user that is scheduled for
* deletion as well as create a reschedule date in the future.
*
* @param mongo the database to pull scheduled users to delete from
* @param tenantID the tenant ID to pull users that have been scheduled for
* deletion on
* @param now the current time
*/
export async function retrieveUserScheduledForDeletion(
mongo: Db,
tenantID: string,
rescheduledDuration: DurationObject,
now: Date
) {
const rescheduledDeletionDate = DateTime.fromJSDate(now)
.plus(rescheduledDuration)
.toJSDate();
const result = await collection(mongo).findOneAndUpdate(
{
tenantID,
scheduledDeletionDate: { $lte: now },
},
{
$set: {
scheduledDeletionDate: rescheduledDeletionDate,
},
},
{
// We want to get back the user with
// modified scheduledDeletionDate
returnOriginal: false,
}
);
return result.value || null;
}
+180
View File
@@ -0,0 +1,180 @@
import { Collection, Db } from "mongodb";
import { CommentAction } from "coral-server/models/action/comment";
import { createCollection } from "coral-server/models/helpers";
import { Story } from "coral-server/models/story";
import { Tenant } from "coral-server/models/tenant";
import { User } from "coral-server/models/user";
const BATCH_SIZE = 500;
// TODO: extract this out to a separate file so it can be re-used elsewhere
const collections = {
users: createCollection<User>("users"),
comments: createCollection<Comment>("comments"),
stories: createCollection<Story>("stories"),
tenants: createCollection<Tenant>("tenants"),
commentActions: createCollection<CommentAction>("commentActions"),
};
async function executeBulkOperations<T>(
collection: Collection<T>,
operations: any[]
) {
// TODO: (wyattjoh) fix types here to support actual types when upstream changes applied
const bulk: any = collection.initializeUnorderedBulkOp();
for (const operation of operations) {
bulk.raw(operation);
}
await bulk.execute();
}
interface Batch {
comments: any[];
stories: any[];
}
async function deleteUserActionCounts(
mongo: Db,
userID: string,
tenantID: string
) {
const batch: Batch = {
comments: [],
stories: [],
};
async function processBatch() {
await executeBulkOperations<Comment>(
collections.comments(mongo),
batch.comments
);
batch.comments = [];
await executeBulkOperations<Story>(
collections.stories(mongo),
batch.stories
);
batch.stories = [];
}
const cursor = collections
.commentActions(mongo)
.find({ tenantID, userID, actionType: "REACTION" });
while (await cursor.hasNext()) {
const action = await cursor.next();
if (!action) {
continue;
}
batch.comments.push({
updateOne: {
filter: { tenantID, id: action.commentID },
update: {
$inc: {
"revisions.$[revisions].actionCounts.REACTION": -1,
"actionCounts.REACTION": -1,
},
},
arrayFilters: [{ "revisions.id": action.commentRevisionID }],
},
});
batch.stories.push({
updateOne: {
filter: { tenantID, id: action.storyID },
update: {
$inc: {
"commentCounts.action.REACTION": -1,
},
},
},
});
if (
batch.comments.length >= BATCH_SIZE ||
batch.stories.length >= BATCH_SIZE
) {
await processBatch();
}
}
if (batch.comments.length > 0 || batch.stories.length > 0) {
await processBatch();
}
await collections.commentActions(mongo).deleteMany({
tenantID,
userID,
actionType: "REACTION",
});
}
async function deleteUserComments(
mongo: Db,
authorID: string,
tenantID: string
) {
await collections.comments(mongo).updateMany(
{ tenantID, authorID },
{
$set: {
authorID: null,
revisions: [],
tags: [],
deleted: true,
},
}
);
}
export async function deleteUser(
mongo: Db,
userID: string,
tenantID: string,
now: Date
) {
const user = await collections.users(mongo).findOne({ id: userID, tenantID });
if (!user) {
throw new Error("could not find user by ID");
}
// Check to see if the user was already deleted.
if (user.deletedAt) {
throw new Error("user was already deleted");
}
const tenant = await collections.tenants(mongo).findOne({ id: tenantID });
if (!tenant) {
throw new Error("could not find tenant by ID");
}
// Delete the user's action counts.
await deleteUserActionCounts(mongo, userID, tenantID);
// Delete the user's comments.
await deleteUserComments(mongo, userID, tenantID);
// Mark the user as deleted.
const result = await collections.users(mongo).findOneAndUpdate(
{ tenantID, id: userID },
{
$set: {
profiles: [],
deletedAt: now,
},
$unset: {
email: "",
},
},
{
// False to return the updated document instead of the original
// document.
returnOriginal: false,
}
);
return result.value || null;
}