diff --git a/.travis.yml b/.travis.yml index f6fdffebf..70481b06a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,10 @@ dist: xenial -language: generic +language: node_js +node_js: lts/* +cache: + yarn: false + npm: false + addons: apt: packages: @@ -7,11 +12,11 @@ addons: snaps: - docker firefox: "latest-esr" - + install: - yarn global add wait-on # Install Codecov - - yarn install + - yarn install --frozen-lockfile - cp backend/.env.template backend/.env before_script: diff --git a/backend/package.json b/backend/package.json index fdc59f1dd..77417453f 100644 --- a/backend/package.json +++ b/backend/package.json @@ -37,8 +37,8 @@ ] }, "dependencies": { - "@hapi/joi": "^17.1.0", - "@sentry/node": "^5.13.1", + "@hapi/joi": "^17.1.1", + "@sentry/node": "^5.14.2", "apollo-cache-inmemory": "~1.6.5", "apollo-client": "~2.6.8", "apollo-link-context": "~1.0.19", @@ -50,7 +50,7 @@ "cheerio": "~1.0.0-rc.3", "cors": "~2.8.5", "cross-env": "~7.0.2", - "date-fns": "2.10.0", + "date-fns": "2.11.0", "debug": "~4.1.1", "dotenv": "~8.2.0", "express": "^4.17.1", @@ -61,7 +61,7 @@ "graphql-middleware": "~4.0.2", "graphql-middleware-sentry": "^3.2.1", "graphql-redis-subscriptions": "^2.2.1", - "graphql-shield": "~7.0.14", + "graphql-shield": "~7.2.0", "graphql-tag": "~2.10.3", "helmet": "~3.21.3", "ioredis": "^4.16.0", @@ -70,7 +70,7 @@ "lodash": "~4.17.14", "merge-graphql-schemas": "^1.7.6", "metascraper": "^5.11.6", - "metascraper-audio": "^5.11.1", + "metascraper-audio": "^5.11.6", "metascraper-author": "^5.11.6", "metascraper-clearbit-logo": "^5.3.0", "metascraper-date": "^5.11.6", @@ -80,15 +80,15 @@ "metascraper-lang-detector": "^4.10.2", "metascraper-logo": "^5.11.6", "metascraper-publisher": "^5.11.6", - "metascraper-soundcloud": "^5.11.5", + "metascraper-soundcloud": "^5.11.6", "metascraper-title": "^5.11.6", "metascraper-url": "^5.11.6", - "metascraper-video": "^5.11.1", + "metascraper-video": "^5.11.6", "metascraper-youtube": "^5.11.6", "migrate": "^1.6.2", "minimatch": "^3.0.4", - "mustache": "^4.0.0", - "neo4j-driver": "^4.0.1", + "mustache": "^4.0.1", + "neo4j-driver": "^4.0.2", "neo4j-graphql-js": "^2.11.5", "neode": "^0.3.7", "node-fetch": "~2.6.0", @@ -122,7 +122,7 @@ "eslint-config-prettier": "~6.10.0", "eslint-config-standard": "~14.1.0", "eslint-plugin-import": "~2.20.1", - "eslint-plugin-jest": "~23.8.1", + "eslint-plugin-jest": "~23.8.2", "eslint-plugin-node": "~11.0.0", "eslint-plugin-prettier": "~3.1.2", "eslint-plugin-promise": "~4.2.1", diff --git a/backend/src/activitypub/ActivityPub.js b/backend/src/activitypub/ActivityPub.js index 1794c2d3b..c4ad7f4b3 100644 --- a/backend/src/activitypub/ActivityPub.js +++ b/backend/src/activitypub/ActivityPub.js @@ -7,7 +7,7 @@ import request from 'request' import NitroDataSource from './NitroDataSource' import router from './routes' import Collections from './Collections' -import uuid from 'uuid/v4' +import { v4 as uuid } from 'uuid' import CONFIG from '../config' const debug = require('debug')('ea') diff --git a/backend/src/db/factories.js b/backend/src/db/factories.js index 159a71a62..010ef67ad 100644 --- a/backend/src/db/factories.js +++ b/backend/src/db/factories.js @@ -4,9 +4,16 @@ import slugify from 'slug' import { hashSync } from 'bcryptjs' import { Factory } from 'rosie' import { getDriver, getNeode } from './neo4j' +import CONFIG from '../config/index.js' const neode = getNeode() +const uniqueImageUrl = imageUrl => { + const newUrl = new URL(imageUrl, CONFIG.CLIENT_URI) + newUrl.search = `random=${uuid()}` + return newUrl.toString() +} + export const cleanDatabase = async (options = {}) => { const { driver = getDriver() } = options const session = driver.session() @@ -39,14 +46,23 @@ Factory.define('badge') return neode.create('Badge', buildObject) }) -Factory.define('userWithoutEmailAddress') +Factory.define('image') + .attr('url', faker.image.unsplash.imageUrl) + .attr('aspectRatio', 1) + .attr('alt', faker.lorem.sentence) + .after((buildObject, options) => { + const { url: imageUrl } = buildObject + if (imageUrl) buildObject.url = uniqueImageUrl(imageUrl) + return neode.create('Image', buildObject) + }) + +Factory.define('basicUser') .option('password', '1234') .attrs({ id: uuid, name: faker.name.findName, password: '1234', role: 'user', - avatar: faker.internet.avatar, about: faker.lorem.paragraph, termsAndConditionsAgreedVersion: '0.0.1', termsAndConditionsAgreedAt: '2019-08-01T10:47:19.212Z', @@ -60,19 +76,29 @@ Factory.define('userWithoutEmailAddress') .attr('encryptedPassword', ['password'], password => { return hashSync(password, 10) }) + +Factory.define('userWithoutEmailAddress') + .extend('basicUser') .after(async (buildObject, options) => { return neode.create('User', buildObject) }) Factory.define('user') - .extend('userWithoutEmailAddress') + .extend('basicUser') .option('email', faker.internet.exampleEmail) + .option('avatar', () => + Factory.build('image', { + url: faker.internet.avatar(), + }), + ) .after(async (buildObject, options) => { - const [user, email] = await Promise.all([ - buildObject, + const [user, email, avatar] = await Promise.all([ + neode.create('User', buildObject), neode.create('EmailAddress', { email: options.email }), + options.avatar, ]) await Promise.all([user.relateTo(email, 'primaryEmail'), email.relateTo(user, 'belongsTo')]) + if (avatar) await user.relateTo(avatar, 'avatar') return user }) @@ -93,11 +119,11 @@ Factory.define('post') return Factory.build('user') }) .option('pinnedBy', null) + .option('image', () => Factory.build('image')) .attrs({ id: uuid, title: faker.lorem.sentence, content: faker.lorem.paragraphs, - image: faker.image.unsplash.imageUrl, visibility: 'public', deleted: false, imageBlurred: false, @@ -117,9 +143,10 @@ Factory.define('post') return language || 'en' }) .after(async (buildObject, options) => { - const [post, author, categories, tags] = await Promise.all([ + const [post, author, image, categories, tags] = await Promise.all([ neode.create('Post', buildObject), options.author, + options.image, options.categories, options.tags, ]) @@ -128,6 +155,7 @@ Factory.define('post') Promise.all(categories.map(c => c.relateTo(post, 'post'))), Promise.all(tags.map(t => t.relateTo(post, 'post'))), ]) + if (image) await post.relateTo(image, 'image') if (buildObject.pinned) { const pinnedBy = await (options.pinnedBy || Factory.build('user', { role: 'admin' })) await pinnedBy.relateTo(post, 'pinned') diff --git a/backend/src/db/migrations/20200125010142-refactor_all_images_to_separate_type.js b/backend/src/db/migrations/20200125010142-refactor_all_images_to_separate_type.js new file mode 100644 index 000000000..634a0552e --- /dev/null +++ b/backend/src/db/migrations/20200125010142-refactor_all_images_to_separate_type.js @@ -0,0 +1,101 @@ +/* eslint-disable no-console */ +import { getDriver } from '../../db/neo4j' + +export const description = ` + Refactor all our image properties on posts and users to a dedicated type + "Image" which contains metadata and image file urls. +` + +const printSummaries = summaries => { + console.log('=========================================') + summaries.forEach(stat => { + console.log(stat.query.text) + console.log(JSON.stringify(stat.counters, null, 2)) + }) + console.log('=========================================') +} + +export async function up() { + const driver = getDriver() + const session = driver.session() + const writeTxResultPromise = session.writeTransaction(async txc => { + const runs = await Promise.all( + [ + ` + MATCH (post:Post) + WHERE post.image IS NOT NULL + CREATE (post)-[:HERO_IMAGE]->(image:Image) + SET + image.url = post.image, + image.sensitive = post.imageBlurred, + image.aspectRatio = post.imageAspectRatio + REMOVE + post.image, + post.imageBlurred, + post.imageAspectRatio + `, + ` + MATCH (user:User) + WHERE user.avatar IS NOT NULL + CREATE (user)-[:AVATAR_IMAGE]->(avatar:Image) + SET avatar.url = user.avatar + REMOVE user.avatar + `, + ` + MATCH (user:User) + WHERE user.coverImg IS NOT NULL + CREATE (user)-[:COVER_IMAGE]->(coverImage:Image) + SET coverImage.url = user.coverImg + REMOVE user.coverImg + `, + ].map(s => txc.run(s)), + ) + return runs.map(({ summary }) => summary) + }) + + try { + const stats = await writeTxResultPromise + console.log('Created image nodes from all user avatars and post images.') + printSummaries(stats) + } finally { + session.close() + } +} + +export async function down() { + const driver = getDriver() + const session = driver.session() + const writeTxResultPromise = session.writeTransaction(async txc => { + const runs = await Promise.all( + [ + ` + MATCH (post)-[:HERO_IMAGE]->(image:Image) + SET + post.image = image.url, + post.imageBlurred = image.sensitive, + post.imageAspectRatio = image.aspectRatio + DETACH DELETE image + `, + ` + MATCH(user)-[:AVATAR_IMAGE]->(avatar:Image) + SET user.avatar = avatar.url + DETACH DELETE avatar + `, + ` + MATCH(user)-[:COVER_IMAGE]->(coverImage:Image) + SET user.coverImg = coverImage.url + DETACH DELETE coverImage + `, + ].map(s => txc.run(s)), + ) + return runs.map(({ summary }) => summary) + }) + + try { + const stats = await writeTxResultPromise + console.log('UNDO: Split images from users and posts.') + printSummaries(stats) + } finally { + session.close() + } +} diff --git a/backend/src/db/migrations/20200213230248-add_unique_index_to_image_url.js b/backend/src/db/migrations/20200213230248-add_unique_index_to_image_url.js new file mode 100644 index 000000000..60d67432f --- /dev/null +++ b/backend/src/db/migrations/20200213230248-add_unique_index_to_image_url.js @@ -0,0 +1,53 @@ +import { getDriver } from '../../db/neo4j' + +export const description = ` + We introduced a new node label 'Image' and we need a primary key for it. Best + would probably be the 'url' property which should be unique and would also + prevent us from overwriting existing images. +` + +export async function up(next) { + const driver = getDriver() + const session = driver.session() + const transaction = session.beginTransaction() + + try { + // Implement your migration here. + await transaction.run(` + CREATE CONSTRAINT ON ( image:Image ) ASSERT image.url IS UNIQUE + `) + await transaction.commit() + next() + } catch (error) { + // eslint-disable-next-line no-console + console.log(error) + await transaction.rollback() + // eslint-disable-next-line no-console + console.log('rolled back') + } finally { + session.close() + } +} + +export async function down(next) { + const driver = getDriver() + const session = driver.session() + const transaction = session.beginTransaction() + + try { + // Implement your migration here. + await transaction.run(` + DROP CONSTRAINT ON ( image:Image ) ASSERT image.url IS UNIQUE + `) + await transaction.commit() + next() + } catch (error) { + // eslint-disable-next-line no-console + console.log(error) + await transaction.rollback() + // eslint-disable-next-line no-console + console.log('rolled back') + } finally { + session.close() + } +} diff --git a/backend/src/db/seed.js b/backend/src/db/seed.js index d1e430629..953f80b55 100644 --- a/backend/src/db/seed.js +++ b/backend/src/db/seed.js @@ -389,13 +389,15 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl'] { id: 'p0', language: sample(languages), - image: faker.image.unsplash.food(300, 169), - imageBlurred: true, - imageAspectRatio: 300 / 169, }, { categoryIds: ['cat16'], author: peterLustig, + image: Factory.build('image', { + url: faker.image.unsplash.food(300, 169), + sensitive: true, + aspectRatio: 300 / 169, + }), }, ), Factory.build( @@ -403,12 +405,14 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl'] { id: 'p1', language: sample(languages), - image: faker.image.unsplash.technology(300, 1500), - imageAspectRatio: 300 / 1500, }, { categoryIds: ['cat1'], author: bobDerBaumeister, + image: Factory.build('image', { + url: faker.image.unsplash.technology(300, 1500), + aspectRatio: 300 / 1500, + }), }, ), Factory.build( @@ -449,12 +453,14 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl'] { id: 'p6', language: sample(languages), - image: faker.image.unsplash.buildings(300, 857), - imageAspectRatio: 300 / 857, }, { categoryIds: ['cat6'], author: peterLustig, + image: Factory.build('image', { + url: faker.image.unsplash.buildings(300, 857), + aspectRatio: 300 / 857, + }), }, ), Factory.build( @@ -472,11 +478,13 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl'] 'post', { id: 'p10', - imageBlurred: true, }, { categoryIds: ['cat10'], author: dewey, + image: Factory.build('image', { + sensitive: true, + }), }, ), Factory.build( @@ -484,12 +492,14 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl'] { id: 'p11', language: sample(languages), - image: faker.image.unsplash.people(300, 901), - imageAspectRatio: 300 / 901, }, { categoryIds: ['cat11'], author: louie, + image: Factory.build('image', { + url: faker.image.unsplash.people(300, 901), + aspectRatio: 300 / 901, + }), }, ), Factory.build( @@ -508,12 +518,14 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl'] { id: 'p14', language: sample(languages), - image: faker.image.unsplash.objects(300, 200), - imageAspectRatio: 300 / 450, }, { categoryIds: ['cat14'], author: jennyRostock, + image: Factory.build('image', { + url: faker.image.unsplash.objects(300, 200), + aspectRatio: 300 / 450, + }), }, ), Factory.build( @@ -539,22 +551,8 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl'] const hashtagAndMention1 = 'The new physics of #QuantenFlussTheorie can explain #QuantumGravity! @peter-lustig got that already. ;-)' const createPostMutation = gql` - mutation( - $id: ID - $title: String! - $content: String! - $categoryIds: [ID] - $imageBlurred: Boolean - $imageAspectRatio: Float - ) { - CreatePost( - id: $id - title: $title - content: $content - categoryIds: $categoryIds - imageBlurred: $imageBlurred - imageAspectRatio: $imageAspectRatio - ) { + mutation($id: ID, $title: String!, $content: String!, $categoryIds: [ID]) { + CreatePost(id: $id, title: $title, content: $content, categoryIds: $categoryIds) { id } } @@ -568,7 +566,6 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl'] title: `Nature Philosophy Yoga`, content: hashtag1, categoryIds: ['cat2'], - imageAspectRatio: 300 / 200, }, }), mutate({ @@ -578,7 +575,6 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl'] title: 'This is post #7', content: `${mention1} ${faker.lorem.paragraph()}`, categoryIds: ['cat7'], - imageAspectRatio: 300 / 180, }, }), mutate({ @@ -589,7 +585,6 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl'] title: `Quantum Flow Theory explains Quantum Gravity`, content: hashtagAndMention1, categoryIds: ['cat8'], - imageAspectRatio: 300 / 900, }, }), mutate({ @@ -599,7 +594,6 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl'] title: 'This is post #12', content: `${mention2} ${faker.lorem.paragraph()}`, categoryIds: ['cat12'], - imageAspectRatio: 300 / 200, }, }), ]) @@ -759,6 +753,7 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl'] }, ), ]) + const trollingComment = comments[0] await Promise.all([ @@ -939,12 +934,13 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl'] [...Array(30).keys()].map(() => Factory.build( 'post', - { - image: faker.image.unsplash.objects(), - }, + {}, { categoryIds: ['cat1'], author: jennyRostock, + image: Factory.build('image', { + url: faker.image.unsplash.objects(), + }), }, ), ), @@ -993,12 +989,13 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl'] [...Array(21).keys()].map(() => Factory.build( 'post', - { - image: faker.image.unsplash.buildings(), - }, + {}, { categoryIds: ['cat1'], author: peterLustig, + image: Factory.build('image', { + url: faker.image.unsplash.buildings(), + }), }, ), ), @@ -1047,12 +1044,13 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl'] [...Array(11).keys()].map(() => Factory.build( 'post', - { - image: faker.image.unsplash.food(), - }, + {}, { categoryIds: ['cat1'], author: dewey, + image: Factory.build('image', { + url: faker.image.unsplash.food(), + }), }, ), ), @@ -1101,12 +1099,13 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl'] [...Array(16).keys()].map(() => Factory.build( 'post', - { - image: faker.image.unsplash.technology(), - }, + {}, { categoryIds: ['cat1'], author: louie, + image: Factory.build('image', { + url: faker.image.unsplash.technology(), + }), }, ), ), @@ -1155,12 +1154,13 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl'] [...Array(45).keys()].map(() => Factory.build( 'post', - { - image: faker.image.unsplash.people(), - }, + {}, { categoryIds: ['cat1'], author: bobDerBaumeister, + image: Factory.build('image', { + url: faker.image.unsplash.people(), + }), }, ), ), @@ -1209,12 +1209,13 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl'] [...Array(8).keys()].map(() => Factory.build( 'post', - { - image: faker.image.unsplash.nature(), - }, + {}, { categoryIds: ['cat1'], author: huey, + image: Factory.build('image', { + url: faker.image.unsplash.nature(), + }), }, ), ), diff --git a/backend/src/jwt/decode.js b/backend/src/jwt/decode.js index 5433a8c76..8dbcb080d 100644 --- a/backend/src/jwt/decode.js +++ b/backend/src/jwt/decode.js @@ -15,10 +15,10 @@ export default async (driver, authorizationHeader) => { const writeTxResultPromise = session.writeTransaction(async transaction => { const updateUserLastActiveTransactionResponse = await transaction.run( - ` + ` MATCH (user:User {id: $id, deleted: false, disabled: false }) SET user.lastActiveAt = toString(datetime()) - RETURN user {.id, .slug, .name, .avatar, .email, .role, .disabled, .actorId} + RETURN user {.id, .slug, .name, .role, .disabled, .actorId} LIMIT 1 `, { id }, diff --git a/backend/src/jwt/decode.spec.js b/backend/src/jwt/decode.spec.js index aa8ff0674..80dfe9733 100644 --- a/backend/src/jwt/decode.spec.js +++ b/backend/src/jwt/decode.spec.js @@ -69,23 +69,23 @@ describe('decode', () => { { role: 'user', name: 'Jenny Rostock', - avatar: 'https://s3.amazonaws.com/uifaces/faces/twitter/sasha_shestakov/128.jpg', id: 'u3', slug: 'jenny-rostock', }, { + image: Factory.build('image', { + url: 'https://s3.amazonaws.com/uifaces/faces/twitter/sasha_shestakov/128.jpg', + }), email: 'user@example.org', }, ) }) - it('returns user object except email', async () => { + it('returns user object without email', async () => { await expect(decode(driver, authorizationHeader)).resolves.toMatchObject({ role: 'user', name: 'Jenny Rostock', - avatar: 'https://s3.amazonaws.com/uifaces/faces/twitter/sasha_shestakov/128.jpg', id: 'u3', - email: null, slug: 'jenny-rostock', }) }) diff --git a/backend/src/middleware/permissionsMiddleware.js b/backend/src/middleware/permissionsMiddleware.js index eecfb58f5..dcb6f8973 100644 --- a/backend/src/middleware/permissionsMiddleware.js +++ b/backend/src/middleware/permissionsMiddleware.js @@ -133,7 +133,7 @@ export default shield( CreateComment: isAuthenticated, UpdateComment: isAuthor, DeleteComment: isAuthor, - DeleteUser: isDeletingOwnAccount, + DeleteUser: or(isDeletingOwnAccount, isAdmin), requestPasswordReset: allow, resetPassword: allow, AddPostEmotions: isAuthenticated, diff --git a/backend/src/middleware/softDelete/softDeleteMiddleware.spec.js b/backend/src/middleware/softDelete/softDeleteMiddleware.spec.js index de5626d14..63569ddb0 100644 --- a/backend/src/middleware/softDelete/softDeleteMiddleware.spec.js +++ b/backend/src/middleware/softDelete/softDeleteMiddleware.spec.js @@ -28,14 +28,21 @@ beforeAll(async () => { password: '1234', }, ), - Factory.build('user', { - id: 'u2', - role: 'user', - name: 'Offensive Name', - slug: 'offensive-name', - avatar: '/some/offensive/avatar.jpg', - about: 'This self description is very offensive', - }), + Factory.build( + 'user', + { + id: 'u2', + role: 'user', + name: 'Offensive Name', + slug: 'offensive-name', + about: 'This self description is very offensive', + }, + { + avatar: Factory.build('image', { + url: '/some/offensive/avatar.jpg', + }), + }, + ), neode.create('Category', { id: 'cat9', name: 'Democracy & Politics', @@ -96,10 +103,12 @@ beforeAll(async () => { title: 'Disabled post', content: 'This is an offensive post content', contentExcerpt: 'This is an offensive post content', - image: '/some/offensive/image.jpg', deleted: false, }, { + image: Factory.build('image', { + url: '/some/offensive/image.jpg', + }), author: troll, categoryIds, }, @@ -213,7 +222,9 @@ describe('softDeleteMiddleware', () => { name slug about - avatar + avatar { + url + } } } } @@ -229,7 +240,9 @@ describe('softDeleteMiddleware', () => { contributions { title slug - image + image { + url + } content contentExcerpt } @@ -253,7 +266,10 @@ describe('softDeleteMiddleware', () => { it('displays slug', () => expect(subject.slug).toEqual('offensive-name')) it('displays about', () => expect(subject.about).toEqual('This self description is very offensive')) - it('displays avatar', () => expect(subject.avatar).toEqual('/some/offensive/avatar.jpg')) + it('displays avatar', () => + expect(subject.avatar).toEqual({ + url: expect.stringContaining('/some/offensive/avatar.jpg'), + })) }) describe('Post', () => { @@ -265,7 +281,10 @@ describe('softDeleteMiddleware', () => { expect(subject.content).toEqual('This is an offensive post content')) it('displays contentExcerpt', () => expect(subject.contentExcerpt).toEqual('This is an offensive post content')) - it('displays image', () => expect(subject.image).toEqual('/some/offensive/image.jpg')) + it('displays image', () => + expect(subject.image).toEqual({ + url: expect.stringContaining('/some/offensive/image.jpg'), + })) }) describe('Comment', () => { @@ -288,7 +307,7 @@ describe('softDeleteMiddleware', () => { it('obfuscates name', () => expect(subject.name).toEqual('UNAVAILABLE')) it('obfuscates slug', () => expect(subject.slug).toEqual('UNAVAILABLE')) it('obfuscates about', () => expect(subject.about).toEqual('UNAVAILABLE')) - it('obfuscates avatar', () => expect(subject.avatar).toEqual('UNAVAILABLE')) + it('obfuscates avatar', () => expect(subject.avatar).toEqual(null)) }) describe('Post', () => { diff --git a/backend/src/models/Image.js b/backend/src/models/Image.js new file mode 100644 index 000000000..19824b493 --- /dev/null +++ b/backend/src/models/Image.js @@ -0,0 +1,7 @@ +export default { + url: { primary: true, type: 'string', uri: { allowRelative: true } }, + alt: { type: 'string' }, + sensitive: { type: 'boolean', default: false }, + aspectRatio: { type: 'float', default: 1.0 }, + createdAt: { type: 'string', isoDate: true, default: () => new Date().toISOString() }, +} diff --git a/backend/src/models/Post.js b/backend/src/models/Post.js index 15eedbf64..43f63ebd3 100644 --- a/backend/src/models/Post.js +++ b/backend/src/models/Post.js @@ -4,6 +4,12 @@ export default { id: { type: 'string', primary: true, default: uuid }, activityId: { type: 'string', allow: [null] }, objectId: { type: 'string', allow: [null] }, + image: { + type: 'relationship', + relationship: 'HERO_IMAGE', + target: 'Image', + direction: 'out', + }, author: { type: 'relationship', relationship: 'WROTE', @@ -14,7 +20,6 @@ export default { slug: { type: 'string', allow: [null], unique: 'true' }, content: { type: 'string', disallow: [null], min: 3 }, contentExcerpt: { type: 'string', allow: [null] }, - image: { type: 'string', allow: [null] }, deleted: { type: 'boolean', default: false }, disabled: { type: 'boolean', default: false }, notified: { @@ -39,8 +44,6 @@ export default { default: () => new Date().toISOString(), }, language: { type: 'string', allow: [null] }, - imageBlurred: { type: 'boolean', default: false }, - imageAspectRatio: { type: 'float', default: 1.0 }, comments: { type: 'relationship', relationship: 'COMMENTS', diff --git a/backend/src/models/User.js b/backend/src/models/User.js index d79fb79b9..ae7e1ae8c 100644 --- a/backend/src/models/User.js +++ b/backend/src/models/User.js @@ -6,8 +6,12 @@ export default { name: { type: 'string', disallow: [null], min: 3 }, slug: { type: 'string', unique: 'true', regex: /^[a-z0-9_-]+$/, lowercase: true }, encryptedPassword: 'string', - avatar: { type: 'string', allow: [null] }, - coverImg: { type: 'string', allow: [null] }, + avatar: { + type: 'relationship', + relationship: 'AVATAR_IMAGE', + target: 'Image', + direction: 'out', + }, deleted: { type: 'boolean', default: false }, disabled: { type: 'boolean', default: false }, role: { type: 'string', default: 'user' }, diff --git a/backend/src/models/index.js b/backend/src/models/index.js index dbb6a927e..c53ef89ab 100644 --- a/backend/src/models/index.js +++ b/backend/src/models/index.js @@ -1,6 +1,7 @@ // NOTE: We cannot use `fs` here to clean up the code. Cypress breaks on any npm // module that is not browser-compatible. Node's `fs` module is server-side only export default { + Image: require('./Image.js').default, Badge: require('./Badge.js').default, User: require('./User.js').default, EmailAddress: require('./EmailAddress.js').default, diff --git a/backend/src/schema/resolvers/fileUpload/index.js b/backend/src/schema/resolvers/fileUpload/index.js deleted file mode 100644 index 3c41a5d11..000000000 --- a/backend/src/schema/resolvers/fileUpload/index.js +++ /dev/null @@ -1,28 +0,0 @@ -import { createWriteStream } from 'fs' -import path from 'path' -import slug from 'slug' -import { v4 as uuid } from 'uuid' - -const localFileUpload = async ({ createReadStream, uniqueFilename }) => { - await new Promise((resolve, reject) => - createReadStream() - .pipe(createWriteStream(`public${uniqueFilename}`)) - .on('finish', resolve) - .on('error', reject), - ) - return uniqueFilename -} - -export default async function fileUpload(params, { file, url }, uploadCallback = localFileUpload) { - const upload = params[file] - if (upload) { - const { createReadStream, filename } = await upload - const { name, ext } = path.parse(filename) - const uniqueFilename = `/uploads/${uuid()}-${slug(name)}${ext}` - const location = await uploadCallback({ createReadStream, uniqueFilename }) - delete params[file] - params[url] = location - } - - return params -} diff --git a/backend/src/schema/resolvers/fileUpload/spec.js b/backend/src/schema/resolvers/fileUpload/spec.js deleted file mode 100644 index fee0bf81b..000000000 --- a/backend/src/schema/resolvers/fileUpload/spec.js +++ /dev/null @@ -1,59 +0,0 @@ -import fileUpload from '.' - -const uuid = '[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}' - -describe('fileUpload', () => { - let params - let uploadCallback - - beforeEach(() => { - params = { - uploadAttribute: { - filename: 'avatar.jpg', - mimetype: 'image/jpeg', - encoding: '7bit', - createReadStream: jest.fn(), - }, - } - uploadCallback = jest.fn(({ uniqueFilename }) => uniqueFilename) - }) - - it('calls uploadCallback', async () => { - await fileUpload(params, { file: 'uploadAttribute', url: 'attribute' }, uploadCallback) - expect(uploadCallback).toHaveBeenCalled() - }) - - describe('file name', () => { - it('saves the upload url in params[url]', async () => { - await fileUpload(params, { file: 'uploadAttribute', url: 'attribute' }, uploadCallback) - expect(params.attribute).toMatch(new RegExp(`^/uploads/${uuid}-avatar.jpg`)) - }) - - it('creates a url safe name', async () => { - params.uploadAttribute.filename = '/path/to/awkward?/ file-location/?foo- bar-avatar.jpg' - await fileUpload(params, { file: 'uploadAttribute', url: 'attribute' }, uploadCallback) - expect(params.attribute).toMatch(new RegExp(`/uploads/${uuid}-foo-bar-avatar.jpg$`)) - }) - - describe('in case of duplicates', () => { - it('creates unique names to avoid overwriting existing files', async () => { - const { attribute: first } = await fileUpload( - { - ...params, - }, - { file: 'uploadAttribute', url: 'attribute' }, - uploadCallback, - ) - - const { attribute: second } = await fileUpload( - { - ...params, - }, - { file: 'uploadAttribute', url: 'attribute' }, - uploadCallback, - ) - expect(first).not.toEqual(second) - }) - }) - }) -}) diff --git a/backend/src/schema/resolvers/images.js b/backend/src/schema/resolvers/images.js new file mode 100644 index 000000000..8b3f4a3e8 --- /dev/null +++ b/backend/src/schema/resolvers/images.js @@ -0,0 +1,8 @@ +import Resolver from './helpers/Resolver' +export default { + Image: { + ...Resolver('Image', { + undefinedToNull: ['sensitive', 'alt', 'aspectRatio'], + }), + }, +} diff --git a/backend/src/schema/resolvers/images/images.js b/backend/src/schema/resolvers/images/images.js new file mode 100644 index 000000000..51bd16d7d --- /dev/null +++ b/backend/src/schema/resolvers/images/images.js @@ -0,0 +1,121 @@ +import path from 'path' +import { v4 as uuid } from 'uuid' +import slug from 'slug' +import { existsSync, unlinkSync, createWriteStream } from 'fs' +import { getDriver } from '../../../db/neo4j' +import { UserInputError } from 'apollo-server' + +// const widths = [34, 160, 320, 640, 1024] + +export async function deleteImage(resource, relationshipType, opts = {}) { + sanitizeRelationshipType(relationshipType) + const { transaction, deleteCallback } = opts + if (!transaction) return wrapTransaction(deleteImage, [resource, relationshipType], opts) + const txResult = await transaction.run( + ` + MATCH (resource {id: $resource.id})-[rel:${relationshipType}]->(image:Image) + WITH image, image {.*} as imageProps + DETACH DELETE image + RETURN imageProps + `, + { resource }, + ) + const [image] = txResult.records.map(record => record.get('imageProps')) + // This behaviour differs from `mergeImage`. If you call `mergeImage` + // with metadata for an image that does not exist, it's an indicator + // of an error (so throw an error). If we bulk delete an image, it + // could very well be that there is no image for the resource. + if (image) deleteImageFile(image, deleteCallback) + return image +} + +export async function mergeImage(resource, relationshipType, imageInput, opts = {}) { + if (typeof imageInput === 'undefined') return + if (imageInput === null) return deleteImage(resource, relationshipType, opts) + sanitizeRelationshipType(relationshipType) + const { transaction, uploadCallback, deleteCallback } = opts + if (!transaction) + return wrapTransaction(mergeImage, [resource, relationshipType, imageInput], opts) + + let txResult + txResult = await transaction.run( + ` + MATCH (resource {id: $resource.id})-[:${relationshipType}]->(image:Image) + RETURN image {.*} + `, + { resource }, + ) + const [existingImage] = txResult.records.map(record => record.get('image')) + const { upload } = imageInput + if (!(existingImage || upload)) throw new UserInputError('Cannot find image for given resource') + if (existingImage && upload) deleteImageFile(existingImage, deleteCallback) + const url = await uploadImageFile(upload, uploadCallback) + const { alt, sensitive, aspectRatio } = imageInput + const image = { alt, sensitive, aspectRatio, url } + txResult = await transaction.run( + ` + MATCH (resource {id: $resource.id}) + MERGE (resource)-[:${relationshipType}]->(image:Image) + ON CREATE SET image.createdAt = toString(datetime()) + ON MATCH SET image.updatedAt = toString(datetime()) + SET image += $image + RETURN image {.*} + `, + { resource, image }, + ) + const [mergedImage] = txResult.records.map(record => record.get('image')) + return mergedImage +} + +const wrapTransaction = async (wrappedCallback, args, opts) => { + const session = getDriver().session() + try { + const result = await session.writeTransaction(async transaction => { + return wrappedCallback(...args, { ...opts, transaction }) + }) + return result + } finally { + session.close() + } +} + +const deleteImageFile = (image, deleteCallback = localFileDelete) => { + const { url } = image + deleteCallback(url) + return url +} + +const uploadImageFile = async (upload, uploadCallback = localFileUpload) => { + if (!upload) return undefined + const { createReadStream, filename, mimetype } = await upload + const { name, ext } = path.parse(filename) + const uniqueFilename = `${uuid()}-${slug(name)}${ext}` + + return uploadCallback({ + createReadStream, + destination: `/uploads/${uniqueFilename}`, + mimetype, + }) +} + +const sanitizeRelationshipType = relationshipType => { + // Cypher query language does not allow to parameterize relationship types + // See: https://github.com/neo4j/neo4j/issues/340 + if (!['HERO_IMAGE', 'AVATAR_IMAGE'].includes(relationshipType)) { + throw new Error(`Unknown relationship type ${relationshipType}`) + } +} + +const localFileUpload = ({ createReadStream, destination }) => { + return new Promise((resolve, reject) => + createReadStream() + .pipe(createWriteStream(`public${destination}`)) + .on('finish', () => resolve(destination)) + .on('error', reject), + ) +} + +const localFileDelete = async url => { + const location = `public${url}` + if (existsSync(location)) unlinkSync(location) +} diff --git a/backend/src/schema/resolvers/images/images.spec.js b/backend/src/schema/resolvers/images/images.spec.js new file mode 100644 index 000000000..228394b01 --- /dev/null +++ b/backend/src/schema/resolvers/images/images.spec.js @@ -0,0 +1,344 @@ +import { deleteImage, mergeImage } from './images' +import { getNeode, getDriver } from '../../../db/neo4j' +import Factory, { cleanDatabase } from '../../../db/factories' +import { UserInputError } from 'apollo-server' + +const driver = getDriver() +const neode = getNeode() +const uuid = '[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}' +let uploadCallback +let deleteCallback + +beforeEach(async () => { + await cleanDatabase() + uploadCallback = jest.fn(({ destination }) => destination) + deleteCallback = jest.fn() +}) + +describe('deleteImage', () => { + describe('given a resource with an image', () => { + let user + beforeEach(async () => { + user = await Factory.build( + 'user', + {}, + { + avatar: Factory.build('image', { + url: '/some/avatar/url/', + alt: 'This is the avatar image of a user', + }), + }, + ) + user = await user.toJson() + }) + + it('soft deletes `Image` node', async () => { + await expect(neode.all('Image')).resolves.toHaveLength(1) + await deleteImage(user, 'AVATAR_IMAGE', { deleteCallback }) + await expect(neode.all('Image')).resolves.toHaveLength(0) + }) + + it('calls deleteCallback', async () => { + user = await Factory.build('user') + user = await user.toJson() + await deleteImage(user, 'AVATAR_IMAGE', { deleteCallback }) + expect(deleteCallback).toHaveBeenCalled() + }) + + describe('given a transaction parameter', () => { + it('executes cypher statements within the transaction', async () => { + const session = driver.session() + let someString + try { + someString = await session.writeTransaction(async transaction => { + await deleteImage(user, 'AVATAR_IMAGE', { + deleteCallback, + transaction, + }) + const txResult = await transaction.run('RETURN "Hello" as result') + const [result] = txResult.records.map(record => record.get('result')) + return result + }) + } finally { + session.close() + } + await expect(neode.all('Image')).resolves.toHaveLength(0) + await expect(someString).toEqual('Hello') + }) + + it('rolls back the transaction in case of errors', async done => { + await expect(neode.all('Image')).resolves.toHaveLength(1) + const session = driver.session() + try { + await session.writeTransaction(async transaction => { + await deleteImage(user, 'AVATAR_IMAGE', { + deleteCallback, + transaction, + }) + throw new Error('Ouch!') + }) + } catch (err) { + // nothing has been deleted + await expect(neode.all('Image')).resolves.toHaveLength(1) + // all good + done() + } finally { + session.close() + } + }) + }) + }) +}) + +describe('mergeImage', () => { + let imageInput + let post + beforeEach(() => { + imageInput = { + alt: 'A description of the new image', + } + }) + + describe('on existing resource', () => { + beforeEach(async () => { + post = await Factory.build( + 'post', + { id: 'p99' }, + { + author: Factory.build('user', {}, { avatar: null }), + image: null, + }, + ) + post = await post.toJson() + }) + + describe('given image.upload', () => { + beforeEach(() => { + imageInput = { + ...imageInput, + upload: { + filename: 'image.jpg', + mimetype: 'image/jpeg', + encoding: '7bit', + createReadStream: () => ({ + pipe: () => ({ + on: (_, callback) => callback(), + }), + }), + }, + } + }) + + it('returns new image', async () => { + await expect( + mergeImage(post, 'HERO_IMAGE', imageInput, { uploadCallback, deleteCallback }), + ).resolves.toMatchObject({ + url: expect.any(String), + alt: 'A description of the new image', + }) + }) + + it('calls upload callback', async () => { + await mergeImage(post, 'HERO_IMAGE', imageInput, { uploadCallback, deleteCallback }) + expect(uploadCallback).toHaveBeenCalled() + }) + + it('creates `:Image` node', async () => { + await expect(neode.all('Image')).resolves.toHaveLength(0) + await mergeImage(post, 'HERO_IMAGE', imageInput, { uploadCallback, deleteCallback }) + await expect(neode.all('Image')).resolves.toHaveLength(1) + }) + + it('creates a url safe name', async () => { + imageInput.upload.filename = '/path/to/awkward?/ file-location/?foo- bar-avatar.jpg' + await expect( + mergeImage(post, 'HERO_IMAGE', imageInput, { uploadCallback, deleteCallback }), + ).resolves.toMatchObject({ + url: expect.stringMatching(new RegExp(`^/uploads/${uuid}-foo-bar-avatar.jpg`)), + }) + }) + + it.skip('automatically creates different image sizes', async () => { + await expect( + mergeImage(post, 'HERO_IMAGE', imageInput, { uploadCallback, deleteCallback }), + ).resolves.toEqual({ + url: expect.any(String), + alt: expect.any(String), + urlW34: expect.stringMatching(new RegExp(`^/uploads/W34/${uuid}-image.jpg`)), + urlW160: expect.stringMatching(new RegExp(`^/uploads/W160/${uuid}-image.jpg`)), + urlW320: expect.stringMatching(new RegExp(`^/uploads/W320/${uuid}-image.jpg`)), + urlW640: expect.stringMatching(new RegExp(`^/uploads/W640/${uuid}-image.jpg`)), + urlW1024: expect.stringMatching(new RegExp(`^/uploads/W1024/${uuid}-image.jpg`)), + }) + }) + + it('connects resource with image via given image type', async () => { + await mergeImage(post, 'HERO_IMAGE', imageInput, { uploadCallback, deleteCallback }) + const result = await neode.cypher(` + MATCH(p:Post {id: "p99"})-[:HERO_IMAGE]->(i:Image) RETURN i,p + `) + post = neode.hydrateFirst(result, 'p', neode.model('Post')) + const image = neode.hydrateFirst(result, 'i', neode.model('Image')) + expect(post).toBeTruthy() + expect(image).toBeTruthy() + }) + + it('whitelists relationship types', async () => { + await expect( + mergeImage(post, 'WHATEVER', imageInput, { uploadCallback, deleteCallback }), + ).rejects.toEqual(new Error('Unknown relationship type WHATEVER')) + }) + + it('sets metadata', async () => { + await mergeImage(post, 'HERO_IMAGE', imageInput, { uploadCallback, deleteCallback }) + const image = await neode.first('Image', {}) + await expect(image.toJson()).resolves.toMatchObject({ + alt: 'A description of the new image', + createdAt: expect.any(String), + url: expect.any(String), + }) + }) + + describe('given a transaction parameter', () => { + it('executes cypher statements within the transaction', async () => { + const session = driver.session() + try { + await session.writeTransaction(async transaction => { + const image = await mergeImage(post, 'HERO_IMAGE', imageInput, { + uploadCallback, + deleteCallback, + transaction, + }) + return transaction.run( + ` + MATCH(image:Image {url: $image.url}) + SET image.alt = 'This alt text gets overwritten' + RETURN image {.*} + `, + { image }, + ) + }) + } finally { + session.close() + } + const image = await neode.first('Image', { alt: 'This alt text gets overwritten' }) + await expect(image.toJson()).resolves.toMatchObject({ + alt: 'This alt text gets overwritten', + }) + }) + + it('rolls back the transaction in case of errors', async done => { + const session = driver.session() + try { + await session.writeTransaction(async transaction => { + const image = await mergeImage(post, 'HERO_IMAGE', imageInput, { + uploadCallback, + deleteCallback, + transaction, + }) + return transaction.run('Ooops invalid cypher!', { image }) + }) + } catch (err) { + // nothing has been created + await expect(neode.all('Image')).resolves.toHaveLength(0) + // all good + done() + } finally { + session.close() + } + }) + }) + + describe('if resource has an image already', () => { + beforeEach(async () => { + const [post, image] = await Promise.all([ + neode.find('Post', 'p99'), + Factory.build('image'), + ]) + await post.relateTo(image, 'image') + }) + + it('calls deleteCallback', async () => { + await mergeImage(post, 'HERO_IMAGE', imageInput, { uploadCallback, deleteCallback }) + expect(deleteCallback).toHaveBeenCalled() + }) + + it('calls uploadCallback', async () => { + await mergeImage(post, 'HERO_IMAGE', imageInput, { uploadCallback, deleteCallback }) + expect(uploadCallback).toHaveBeenCalled() + }) + + it('updates metadata of existing image node', async () => { + await expect(neode.all('Image')).resolves.toHaveLength(1) + await mergeImage(post, 'HERO_IMAGE', imageInput, { uploadCallback, deleteCallback }) + await expect(neode.all('Image')).resolves.toHaveLength(1) + const image = await neode.first('Image', {}) + await expect(image.toJson()).resolves.toMatchObject({ + alt: 'A description of the new image', + createdAt: expect.any(String), + url: expect.any(String), + // TODO + // width: + // height: + }) + }) + }) + }) + }) + + describe('without image.upload', () => { + it('throws UserInputError', async () => { + post = await Factory.build('post', { id: 'p99' }, { image: null }) + post = await post.toJson() + await expect(mergeImage(post, 'HERO_IMAGE', imageInput)).rejects.toEqual( + new UserInputError('Cannot find image for given resource'), + ) + }) + + describe('if resource has an image already', () => { + beforeEach(async () => { + post = await Factory.build( + 'post', + { + id: 'p99', + }, + { + author: Factory.build( + 'user', + {}, + { + avatar: null, + }, + ), + image: Factory.build('image', { + alt: 'This is the previous, not updated image', + url: '/some/original/url', + }), + }, + ) + post = await post.toJson() + }) + + it('does not call deleteCallback', async () => { + await mergeImage(post, 'HERO_IMAGE', imageInput, { uploadCallback, deleteCallback }) + expect(deleteCallback).not.toHaveBeenCalled() + }) + + it('does not call uploadCallback', async () => { + await mergeImage(post, 'HERO_IMAGE', imageInput, { uploadCallback, deleteCallback }) + expect(uploadCallback).not.toHaveBeenCalled() + }) + + it('updates metadata', async () => { + await mergeImage(post, 'HERO_IMAGE', imageInput) + const images = await neode.all('Image') + expect(images).toHaveLength(1) + await expect(images.first().toJson()).resolves.toMatchObject({ + createdAt: expect.any(String), + url: expect.any(String), + alt: 'A description of the new image', + }) + }) + }) + }) +}) diff --git a/backend/src/schema/resolvers/posts.js b/backend/src/schema/resolvers/posts.js index 1d4c4bfaa..eb265e528 100644 --- a/backend/src/schema/resolvers/posts.js +++ b/backend/src/schema/resolvers/posts.js @@ -2,7 +2,7 @@ import { v4 as uuid } from 'uuid' import { neo4jgraphql } from 'neo4j-graphql-js' import { isEmpty } from 'lodash' import { UserInputError } from 'apollo-server' -import fileUpload from './fileUpload' +import { mergeImage, deleteImage } from './images/images' import Resolver from './helpers/Resolver' import { filterForMutedUsers } from './helpers/filterForMutedUsers' @@ -77,14 +77,16 @@ export default { Mutation: { CreatePost: async (_parent, params, context, _resolveInfo) => { const { categoryIds } = params + const { image: imageInput } = params delete params.categoryIds - params = await fileUpload(params, { file: 'imageUpload', url: 'image' }) + delete params.image params.id = params.id || uuid() const session = context.driver.session() const writeTxResultPromise = session.writeTransaction(async transaction => { const createPostTransactionResponse = await transaction.run( ` - CREATE (post:Post {params}) + CREATE (post:Post) + SET post += $params SET post.createdAt = toString(datetime()) SET post.updatedAt = toString(datetime()) WITH post @@ -94,14 +96,18 @@ export default { UNWIND $categoryIds AS categoryId MATCH (category:Category {id: categoryId}) MERGE (post)-[:CATEGORIZED]->(category) - RETURN post + RETURN post {.*} `, { userId: context.user.id, categoryIds, params }, ) - return createPostTransactionResponse.records.map(record => record.get('post').properties) + const [post] = createPostTransactionResponse.records.map(record => record.get('post')) + if (imageInput) { + await mergeImage(post, 'HERO_IMAGE', imageInput, { transaction }) + } + return post }) try { - const [post] = await writeTxResultPromise + const post = await writeTxResultPromise return post } catch (e) { if (e.code === 'Neo.ClientError.Schema.ConstraintValidationFailed') @@ -113,8 +119,9 @@ export default { }, UpdatePost: async (_parent, params, context, _resolveInfo) => { const { categoryIds } = params + const { image: imageInput } = params delete params.categoryIds - params = await fileUpload(params, { file: 'imageUpload', url: 'image' }) + delete params.image const session = context.driver.session() let updatePostCypher = ` MATCH (post:Post {id: $params.id}) @@ -142,7 +149,7 @@ export default { ` } - updatePostCypher += `RETURN post` + updatePostCypher += `RETURN post {.*}` const updatePostVariables = { categoryIds, params } try { const writeTxResultPromise = session.writeTransaction(async transaction => { @@ -150,9 +157,11 @@ export default { updatePostCypher, updatePostVariables, ) - return updatePostTransactionResponse.records.map(record => record.get('post').properties) + const [post] = updatePostTransactionResponse.records.map(record => record.get('post')) + await mergeImage(post, 'HERO_IMAGE', imageInput, { transaction }) + return post }) - const [post] = await writeTxResultPromise + const post = await writeTxResultPromise return post } finally { session.close() @@ -171,15 +180,16 @@ export default { SET post.contentExcerpt = 'UNAVAILABLE' SET post.title = 'UNAVAILABLE' SET comment.deleted = TRUE - REMOVE post.image - RETURN post + RETURN post {.*} `, { postId: args.id }, ) - return deletePostTransactionResponse.records.map(record => record.get('post').properties) + const [post] = deletePostTransactionResponse.records.map(record => record.get('post')) + await deleteImage(post, 'HERO_IMAGE', { transaction }) + return post }) try { - const [post] = await writeTxResultPromise + const post = await writeTxResultPromise return post } finally { session.close() @@ -311,16 +321,7 @@ export default { }, Post: { ...Resolver('Post', { - undefinedToNull: [ - 'activityId', - 'objectId', - 'image', - 'language', - 'pinnedAt', - 'pinned', - 'imageBlurred', - 'imageAspectRatio', - ], + undefinedToNull: ['activityId', 'objectId', 'language', 'pinnedAt', 'pinned'], hasMany: { tags: '-[:TAGGED]->(related:Tag)', categories: '-[:CATEGORIZED]->(related:Category)', @@ -331,6 +332,7 @@ export default { hasOne: { author: '<-[:WROTE]-(related:User)', pinnedBy: '<-[:PINNED]-(related:User)', + image: '-[:HERO_IMAGE]->(related:Image)', }, count: { commentsCount: diff --git a/backend/src/schema/resolvers/posts.spec.js b/backend/src/schema/resolvers/posts.spec.js index 88a09843d..b24383fba 100644 --- a/backend/src/schema/resolvers/posts.spec.js +++ b/backend/src/schema/resolvers/posts.spec.js @@ -336,8 +336,14 @@ describe('CreatePost', () => { describe('UpdatePost', () => { let author, newlyCreatedPost const updatePostMutation = gql` - mutation($id: ID!, $title: String!, $content: String!, $categoryIds: [ID]) { - UpdatePost(id: $id, title: $title, content: $content, categoryIds: $categoryIds) { + mutation($id: ID!, $title: String!, $content: String!, $categoryIds: [ID], $image: ImageInput) { + UpdatePost( + id: $id + title: $title + content: $content + categoryIds: $categoryIds + image: $image + ) { id title content @@ -472,418 +478,471 @@ describe('UpdatePost', () => { ) }) }) + + describe('params.image', () => { + describe('is object', () => { + beforeEach(() => { + variables = { ...variables, image: { sensitive: true } } + }) + it('updates the image', async () => { + await expect(neode.first('Image', { sensitive: true })).resolves.toBeFalsy() + await mutate({ mutation: updatePostMutation, variables }) + await expect(neode.first('Image', { sensitive: true })).resolves.toBeTruthy() + }) + }) + + describe('is null', () => { + beforeEach(() => { + variables = { ...variables, image: null } + }) + it('deletes the image', async () => { + await expect(neode.all('Image')).resolves.toHaveLength(6) + await mutate({ mutation: updatePostMutation, variables }) + await expect(neode.all('Image')).resolves.toHaveLength(5) + }) + }) + + describe('is undefined', () => { + beforeEach(() => { + delete variables.image + }) + it('keeps the image unchanged', async () => { + await expect(neode.first('Image', { sensitive: true })).resolves.toBeFalsy() + await mutate({ mutation: updatePostMutation, variables }) + await expect(neode.first('Image', { sensitive: true })).resolves.toBeFalsy() + }) + }) + }) + }) +}) + +describe('pin posts', () => { + let author + const pinPostMutation = gql` + mutation($id: ID!) { + pinPost(id: $id) { + id + title + content + author { + name + slug + } + pinnedBy { + id + name + role + } + createdAt + updatedAt + pinnedAt + pinned + } + } + ` + beforeEach(async () => { + author = await Factory.build('user', { slug: 'the-author' }) + await Factory.build( + 'post', + { + id: 'p9876', + title: 'Old title', + content: 'Old content', + }, + { + author, + categoryIds, + }, + ) + variables = { + id: 'p9876', + } }) - describe('pin posts', () => { - const pinPostMutation = gql` - mutation($id: ID!) { - pinPost(id: $id) { - id - title - content - author { - name - slug - } - pinnedBy { - id - name - role - } - createdAt - updatedAt - pinnedAt - pinned - } - } - ` + describe('unauthenticated', () => { + it('throws authorization error', async () => { + authenticatedUser = null + await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject({ + errors: [{ message: 'Not Authorised!' }], + data: { pinPost: null }, + }) + }) + }) + + describe('ordinary users', () => { + it('throws authorization error', async () => { + await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject({ + errors: [{ message: 'Not Authorised!' }], + data: { pinPost: null }, + }) + }) + }) + + describe('moderators', () => { + let moderator beforeEach(async () => { - variables = { ...variables } + moderator = await user.update({ role: 'moderator', updatedAt: new Date().toISOString() }) + authenticatedUser = await moderator.toJson() }) - describe('unauthenticated', () => { - it('throws authorization error', async () => { - authenticatedUser = null - await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject({ - errors: [{ message: 'Not Authorised!' }], - data: { pinPost: null }, - }) + it('throws authorization error', async () => { + await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject({ + errors: [{ message: 'Not Authorised!' }], + data: { pinPost: null }, }) }) + }) - describe('ordinary users', () => { - it('throws authorization error', async () => { - await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject({ - errors: [{ message: 'Not Authorised!' }], - data: { pinPost: null }, - }) + describe('admins', () => { + let admin + beforeEach(async () => { + admin = await user.update({ + role: 'admin', + name: 'Admin', + updatedAt: new Date().toISOString(), }) + authenticatedUser = await admin.toJson() }) - describe('moderators', () => { - let moderator + describe('are allowed to pin posts', () => { beforeEach(async () => { - moderator = await user.update({ role: 'moderator', updatedAt: new Date().toISOString() }) - authenticatedUser = await moderator.toJson() + await Factory.build( + 'post', + { + id: 'created-and-pinned-by-same-admin', + }, + { + author: admin, + }, + ) + variables = { ...variables, id: 'created-and-pinned-by-same-admin' } }) - it('throws authorization error', async () => { - await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject({ - errors: [{ message: 'Not Authorised!' }], - data: { pinPost: null }, - }) - }) - }) - - describe('admins', () => { - let admin - beforeEach(async () => { - admin = await user.update({ - role: 'admin', - name: 'Admin', - updatedAt: new Date().toISOString(), - }) - authenticatedUser = await admin.toJson() - }) - - describe('are allowed to pin posts', () => { - beforeEach(async () => { - await Factory.build( - 'post', - { + it('responds with the updated Post', async () => { + const expected = { + data: { + pinPost: { id: 'created-and-pinned-by-same-admin', - }, - { - author: admin, - }, - ) - variables = { ...variables, id: 'created-and-pinned-by-same-admin' } - }) - - it('responds with the updated Post', async () => { - const expected = { - data: { - pinPost: { - id: 'created-and-pinned-by-same-admin', - author: { - name: 'Admin', - }, - pinnedBy: { - id: 'current-user', - name: 'Admin', - role: 'admin', - }, + author: { + name: 'Admin', + }, + pinnedBy: { + id: 'current-user', + name: 'Admin', + role: 'admin', }, }, - errors: undefined, - } + }, + errors: undefined, + } - await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject( - expected, - ) - }) - - it('sets createdAt date for PINNED', async () => { - const expected = { - data: { - pinPost: { - id: 'created-and-pinned-by-same-admin', - pinnedAt: expect.any(String), - }, - }, - errors: undefined, - } - await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject( - expected, - ) - }) - - it('sets redundant `pinned` property for performant ordering', async () => { - variables = { ...variables, id: 'created-and-pinned-by-same-admin' } - const expected = { - data: { pinPost: { pinned: true } }, - errors: undefined, - } - await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject( - expected, - ) - }) + await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject( + expected, + ) }) - describe('post created by another admin', () => { - let otherAdmin - beforeEach(async () => { - otherAdmin = await Factory.build('user', { - role: 'admin', - name: 'otherAdmin', - }) - authenticatedUser = await otherAdmin.toJson() - await Factory.build( - 'post', - { + it('sets createdAt date for PINNED', async () => { + const expected = { + data: { + pinPost: { + id: 'created-and-pinned-by-same-admin', + pinnedAt: expect.any(String), + }, + }, + errors: undefined, + } + await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject( + expected, + ) + }) + + it('sets redundant `pinned` property for performant ordering', async () => { + variables = { ...variables, id: 'created-and-pinned-by-same-admin' } + const expected = { + data: { pinPost: { pinned: true } }, + errors: undefined, + } + await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject( + expected, + ) + }) + }) + + describe('post created by another admin', () => { + let otherAdmin + beforeEach(async () => { + otherAdmin = await Factory.build('user', { + role: 'admin', + name: 'otherAdmin', + }) + authenticatedUser = await otherAdmin.toJson() + await Factory.build( + 'post', + { + id: 'created-by-one-admin-pinned-by-different-one', + }, + { + author: otherAdmin, + }, + ) + }) + + it('responds with the updated Post', async () => { + authenticatedUser = await admin.toJson() + variables = { ...variables, id: 'created-by-one-admin-pinned-by-different-one' } + const expected = { + data: { + pinPost: { id: 'created-by-one-admin-pinned-by-different-one', - }, - { - author: otherAdmin, - }, - ) - }) - - it('responds with the updated Post', async () => { - authenticatedUser = await admin.toJson() - variables = { ...variables, id: 'created-by-one-admin-pinned-by-different-one' } - const expected = { - data: { - pinPost: { - id: 'created-by-one-admin-pinned-by-different-one', - author: { - name: 'otherAdmin', - }, - pinnedBy: { - id: 'current-user', - name: 'Admin', - role: 'admin', - }, + author: { + name: 'otherAdmin', + }, + pinnedBy: { + id: 'current-user', + name: 'Admin', + role: 'admin', }, }, - errors: undefined, - } + }, + errors: undefined, + } - await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject( - expected, - ) - }) + await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject( + expected, + ) }) + }) - describe('post created by another user', () => { - it('responds with the updated Post', async () => { - const expected = { - data: { - pinPost: { - id: 'p9876', - author: { - slug: 'the-author', - }, - pinnedBy: { - id: 'current-user', - name: 'Admin', - role: 'admin', - }, + describe('post created by another user', () => { + it('responds with the updated Post', async () => { + const expected = { + data: { + pinPost: { + id: 'p9876', + author: { + slug: 'the-author', + }, + pinnedBy: { + id: 'current-user', + name: 'Admin', + role: 'admin', }, }, - errors: undefined, - } + }, + errors: undefined, + } - await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject( - expected, - ) + await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject( + expected, + ) + }) + }) + + describe('pinned post already exists', () => { + let pinnedPost + beforeEach(async () => { + await Factory.build( + 'post', + { + id: 'only-pinned-post', + }, + { + author: admin, + }, + ) + await mutate({ mutation: pinPostMutation, variables }) + }) + + it('removes previous `pinned` attribute', async () => { + const cypher = 'MATCH (post:Post) WHERE post.pinned IS NOT NULL RETURN post' + pinnedPost = await neode.cypher(cypher) + expect(pinnedPost.records).toHaveLength(1) + variables = { ...variables, id: 'only-pinned-post' } + await mutate({ mutation: pinPostMutation, variables }) + pinnedPost = await neode.cypher(cypher) + expect(pinnedPost.records).toHaveLength(1) + }) + + it('removes previous PINNED relationship', async () => { + variables = { ...variables, id: 'only-pinned-post' } + await mutate({ mutation: pinPostMutation, variables }) + pinnedPost = await neode.cypher( + `MATCH (:User)-[pinned:PINNED]->(post:Post) RETURN post, pinned`, + ) + expect(pinnedPost.records).toHaveLength(1) + }) + }) + + describe('PostOrdering', () => { + beforeEach(async () => { + await Factory.build('post', { + id: 'im-a-pinned-post', + createdAt: '2019-11-22T17:26:29.070Z', + pinned: true, + }) + await Factory.build('post', { + id: 'i-was-created-before-pinned-post', + // fairly old, so this should be 3rd + createdAt: '2019-10-22T17:26:29.070Z', }) }) - describe('pinned post already exists', () => { - let pinnedPost - beforeEach(async () => { - await Factory.build( - 'post', - { - id: 'only-pinned-post', - }, - { - author: admin, - }, - ) - await mutate({ mutation: pinPostMutation, variables }) + describe('order by `pinned_asc` and `createdAt_desc`', () => { + beforeEach(() => { + // this is the ordering in the frontend + variables = { orderBy: ['pinned_asc', 'createdAt_desc'] } }) - it('removes previous `pinned` attribute', async () => { - const cypher = 'MATCH (post:Post) WHERE post.pinned IS NOT NULL RETURN post' - pinnedPost = await neode.cypher(cypher) - expect(pinnedPost.records).toHaveLength(1) - variables = { ...variables, id: 'only-pinned-post' } - await mutate({ mutation: pinPostMutation, variables }) - pinnedPost = await neode.cypher(cypher) - expect(pinnedPost.records).toHaveLength(1) - }) - - it('removes previous PINNED relationship', async () => { - variables = { ...variables, id: 'only-pinned-post' } - await mutate({ mutation: pinPostMutation, variables }) - pinnedPost = await neode.cypher( - `MATCH (:User)-[pinned:PINNED]->(post:Post) RETURN post, pinned`, - ) - expect(pinnedPost.records).toHaveLength(1) - }) - }) - - describe('PostOrdering', () => { - beforeEach(async () => { - await Factory.build('post', { - id: 'im-a-pinned-post', - createdAt: '2019-11-22T17:26:29.070Z', - pinned: true, - }) - await Factory.build('post', { - id: 'i-was-created-before-pinned-post', - // fairly old, so this should be 3rd - createdAt: '2019-10-22T17:26:29.070Z', - }) - }) - - describe('order by `pinned_asc` and `createdAt_desc`', () => { - beforeEach(() => { - // this is the ordering in the frontend - variables = { orderBy: ['pinned_asc', 'createdAt_desc'] } - }) - - it('pinned post appear first even when created before other posts', async () => { - const postOrderingQuery = gql` - query($orderBy: [_PostOrdering]) { - Post(orderBy: $orderBy) { - id - pinned - createdAt - pinnedAt - } + it('pinned post appear first even when created before other posts', async () => { + const postOrderingQuery = gql` + query($orderBy: [_PostOrdering]) { + Post(orderBy: $orderBy) { + id + pinned + createdAt + pinnedAt } - ` - await expect(query({ query: postOrderingQuery, variables })).resolves.toMatchObject({ - data: { - Post: [ - { - id: 'im-a-pinned-post', - pinned: true, - createdAt: '2019-11-22T17:26:29.070Z', - pinnedAt: expect.any(String), - }, - { - id: 'p9876', - pinned: null, - createdAt: expect.any(String), - pinnedAt: null, - }, - { - id: 'i-was-created-before-pinned-post', - pinned: null, - createdAt: '2019-10-22T17:26:29.070Z', - pinnedAt: null, - }, - ], - }, - errors: undefined, - }) + } + ` + await expect(query({ query: postOrderingQuery, variables })).resolves.toMatchObject({ + data: { + Post: [ + { + id: 'im-a-pinned-post', + pinned: true, + createdAt: '2019-11-22T17:26:29.070Z', + pinnedAt: expect.any(String), + }, + { + id: 'p9876', + pinned: null, + createdAt: expect.any(String), + pinnedAt: null, + }, + { + id: 'i-was-created-before-pinned-post', + pinned: null, + createdAt: '2019-10-22T17:26:29.070Z', + pinnedAt: null, + }, + ], + }, + errors: undefined, }) }) }) }) }) +}) - describe('unpin posts', () => { - const unpinPostMutation = gql` - mutation($id: ID!) { - unpinPost(id: $id) { +describe('unpin posts', () => { + let pinnedPost + const unpinPostMutation = gql` + mutation($id: ID!) { + unpinPost(id: $id) { + id + title + content + author { + name + slug + } + pinnedBy { id - title - content - author { - name - slug - } - pinnedBy { - id - name - role - } - createdAt - updatedAt - pinned - pinnedAt + name + role } + createdAt + updatedAt + pinned + pinnedAt } - ` + } + ` + beforeEach(async () => { + pinnedPost = await Factory.build('post', { id: 'post-to-be-unpinned' }) + variables = { + id: 'post-to-be-unpinned', + } + }) + + describe('unauthenticated', () => { + it('throws authorization error', async () => { + authenticatedUser = null + await expect(mutate({ mutation: unpinPostMutation, variables })).resolves.toMatchObject({ + errors: [{ message: 'Not Authorised!' }], + data: { unpinPost: null }, + }) + }) + }) + + describe('users cannot unpin posts', () => { + it('throws authorization error', async () => { + await expect(mutate({ mutation: unpinPostMutation, variables })).resolves.toMatchObject({ + errors: [{ message: 'Not Authorised!' }], + data: { unpinPost: null }, + }) + }) + }) + + describe('moderators cannot unpin posts', () => { + let moderator beforeEach(async () => { - variables = { ...variables } + moderator = await user.update({ role: 'moderator', updatedAt: new Date().toISOString() }) + authenticatedUser = await moderator.toJson() }) - describe('unauthenticated', () => { - it('throws authorization error', async () => { - authenticatedUser = null - await expect(mutate({ mutation: unpinPostMutation, variables })).resolves.toMatchObject({ - errors: [{ message: 'Not Authorised!' }], - data: { unpinPost: null }, - }) + it('throws authorization error', async () => { + await expect(mutate({ mutation: unpinPostMutation, variables })).resolves.toMatchObject({ + errors: [{ message: 'Not Authorised!' }], + data: { unpinPost: null }, }) }) + }) - describe('users cannot unpin posts', () => { - it('throws authorization error', async () => { - await expect(mutate({ mutation: unpinPostMutation, variables })).resolves.toMatchObject({ - errors: [{ message: 'Not Authorised!' }], - data: { unpinPost: null }, - }) + describe('admin can unpin posts', () => { + let admin + beforeEach(async () => { + admin = await user.update({ + role: 'admin', + name: 'Admin', + updatedAt: new Date().toISOString(), }) + authenticatedUser = await admin.toJson() + await admin.relateTo(pinnedPost, 'pinned', { createdAt: new Date().toISOString() }) }) - describe('moderators cannot unpin posts', () => { - let moderator - beforeEach(async () => { - moderator = await user.update({ role: 'moderator', updatedAt: new Date().toISOString() }) - authenticatedUser = await moderator.toJson() - }) - - it('throws authorization error', async () => { - await expect(mutate({ mutation: unpinPostMutation, variables })).resolves.toMatchObject({ - errors: [{ message: 'Not Authorised!' }], - data: { unpinPost: null }, - }) - }) - }) - - describe('admin can unpin posts', () => { - let admin, pinnedPost - beforeEach(async () => { - pinnedPost = await Factory.build('post', { id: 'post-to-be-unpinned' }) - admin = await user.update({ - role: 'admin', - name: 'Admin', - updatedAt: new Date().toISOString(), - }) - authenticatedUser = await admin.toJson() - await admin.relateTo(pinnedPost, 'pinned', { createdAt: new Date().toISOString() }) - variables = { ...variables, id: 'post-to-be-unpinned' } - }) - - it('responds with the unpinned Post', async () => { - authenticatedUser = await admin.toJson() - const expected = { - data: { - unpinPost: { - id: 'post-to-be-unpinned', - pinnedBy: null, - pinnedAt: null, - }, + it('responds with the unpinned Post', async () => { + authenticatedUser = await admin.toJson() + const expected = { + data: { + unpinPost: { + id: 'post-to-be-unpinned', + pinnedBy: null, + pinnedAt: null, }, - errors: undefined, - } + }, + errors: undefined, + } - await expect(mutate({ mutation: unpinPostMutation, variables })).resolves.toMatchObject( - expected, - ) - }) + await expect(mutate({ mutation: unpinPostMutation, variables })).resolves.toMatchObject( + expected, + ) + }) - it('unsets `pinned` property', async () => { - const expected = { - data: { - unpinPost: { - id: 'post-to-be-unpinned', - pinned: null, - }, + it('unsets `pinned` property', async () => { + const expected = { + data: { + unpinPost: { + id: 'post-to-be-unpinned', + pinned: null, }, - errors: undefined, - } - await expect(mutate({ mutation: unpinPostMutation, variables })).resolves.toMatchObject( - expected, - ) - }) + }, + errors: undefined, + } + await expect(mutate({ mutation: unpinPostMutation, variables })).resolves.toMatchObject( + expected, + ) }) }) }) @@ -897,7 +956,9 @@ describe('DeletePost', () => { deleted content contentExcerpt - image + image { + url + } comments { deleted content @@ -915,9 +976,11 @@ describe('DeletePost', () => { id: 'p4711', title: 'I will be deleted', content: 'To be deleted', - image: 'path/to/some/image', }, { + image: Factory.build('image', { + url: 'path/to/some/image', + }), author, categoryIds, }, diff --git a/backend/src/schema/resolvers/registration.js b/backend/src/schema/resolvers/registration.js index 1e7708395..921570e5d 100644 --- a/backend/src/schema/resolvers/registration.js +++ b/backend/src/schema/resolvers/registration.js @@ -1,11 +1,9 @@ import { UserInputError } from 'apollo-server' import { getNeode } from '../../db/neo4j' -import fileUpload from './fileUpload' import encryptPassword from '../../helpers/encryptPassword' import generateNonce from './helpers/generateNonce' import existingEmailAddress from './helpers/existingEmailAddress' import normalizeEmail from './helpers/normalizeEmail' -import createOrUpdateLocations from './users/location' const neode = getNeode() @@ -24,8 +22,6 @@ export default { } }, SignupVerification: async (_parent, args, context) => { - const { driver } = context - const session = driver.session() const { termsAndConditionsAgreedVersion } = args const regEx = new RegExp(/^[0-9]+\.[0-9]+\.[0-9]+$/g) if (!regEx.test(termsAndConditionsAgreedVersion)) { @@ -35,27 +31,39 @@ export default { let { nonce, email } = args email = normalizeEmail(email) - const result = await neode.cypher( - ` - MATCH(email:EmailAddress {nonce: {nonce}, email: {email}}) - WHERE NOT (email)-[:BELONGS_TO]->() - RETURN email - `, - { nonce, email }, - ) - const emailAddress = await neode.hydrateFirst(result, 'email', neode.model('EmailAddress')) - if (!emailAddress) throw new UserInputError('Invalid email or nonce') - args = await fileUpload(args, { file: 'avatarUpload', url: 'avatar' }) - args = await encryptPassword(args) + delete args.nonce + delete args.email + args = encryptPassword(args) + + const { driver } = context + const session = driver.session() + const writeTxResultPromise = session.writeTransaction(async transaction => { + const createUserTransactionResponse = await transaction.run( + ` + MATCH(email:EmailAddress {nonce: $nonce, email: $email}) + WHERE NOT (email)-[:BELONGS_TO]->() + CREATE (user:User) + MERGE(user)-[:PRIMARY_EMAIL]->(email) + MERGE(user)<-[:BELONGS_TO]-(email) + SET user += $args + SET user.id = randomUUID() + SET user.role = 'user' + SET user.createdAt = toString(datetime()) + SET user.updatedAt = toString(datetime()) + SET user.allowEmbedIframes = FALSE + SET user.showShoutsPublicly = FALSE + SET email.verifiedAt = toString(datetime()) + RETURN user {.*} + `, + { args, nonce, email }, + ) + const [user] = createUserTransactionResponse.records.map(record => record.get('user')) + if (!user) throw new UserInputError('Invalid email or nonce') + return user + }) try { - const user = await neode.create('User', args) - await Promise.all([ - user.relateTo(emailAddress, 'primaryEmail'), - emailAddress.relateTo(user, 'belongsTo'), - emailAddress.update({ verifiedAt: new Date().toISOString() }), - ]) - await createOrUpdateLocations(args.id, args.locationName, session) - return user.toJson() + const user = await writeTxResultPromise + return user } catch (e) { if (e.code === 'Neo.ClientError.Schema.ConstraintValidationFailed') throw new UserInputError('User with this slug already exists!') diff --git a/backend/src/schema/resolvers/searches.js b/backend/src/schema/resolvers/searches.js index fb58b3ee0..0cf5c4ae8 100644 --- a/backend/src/schema/resolvers/searches.js +++ b/backend/src/schema/resolvers/searches.js @@ -1,22 +1,19 @@ import log from './helpers/databaseLogger' +import { queryString } from './searches/queryString' + +// see http://lucene.apache.org/core/8_3_1/queryparser/org/apache/lucene/queryparser/classic/package-summary.html#package.description export default { Query: { searchResults: async (_parent, args, context, _resolveInfo) => { const { query, limit } = args const { id: thisUserId } = context.user - // see http://lucene.apache.org/core/8_3_1/queryparser/org/apache/lucene/queryparser/classic/package-summary.html#package.description - const myQuery = query - .replace(/\s+/g, ' ') - .replace(/[[@#:*~\\$|^\]?/"'(){}+?!,.-;]/g, '') - .split(' ') - .map(s => (s.toLowerCase().match(/^(not|and|or)$/) ? '"' + s + '"' : s + '*')) - .join(' ') + const postCypher = ` CALL db.index.fulltext.queryNodes('post_fulltext_search', $query) YIELD node as resource, score MATCH (resource)<-[:WROTE]-(author:User) - WHERE score >= 0.5 + WHERE score >= 0.0 AND NOT ( author.deleted = true OR author.disabled = true OR resource.deleted = true OR resource.disabled = true @@ -39,11 +36,12 @@ export default { CALL db.index.fulltext.queryNodes('user_fulltext_search', $query) YIELD node as resource, score MATCH (resource) - WHERE score >= 0.5 + WHERE score >= 0.0 AND NOT (resource.deleted = true OR resource.disabled = true) RETURN resource {.*, __typename: labels(resource)[0]} LIMIT $limit ` + const myQuery = queryString(query) const session = context.driver.session() const searchResultPromise = session.readTransaction(async transaction => { diff --git a/backend/src/schema/resolvers/searches.spec.js b/backend/src/schema/resolvers/searches.spec.js new file mode 100644 index 000000000..c454833b8 --- /dev/null +++ b/backend/src/schema/resolvers/searches.spec.js @@ -0,0 +1,444 @@ +import Factory, { cleanDatabase } from '../../db/factories' +import { gql } from '../../helpers/jest' +import { getNeode, getDriver } from '../../db/neo4j' +import createServer from '../../server' +import { createTestClient } from 'apollo-server-testing' + +let query, authenticatedUser, user + +const driver = getDriver() +const neode = getNeode() + +beforeAll(async () => { + await cleanDatabase() + const { server } = createServer({ + context: () => { + return { + driver, + neode, + user: authenticatedUser, + } + }, + }) + query = createTestClient(server).query +}) + +afterAll(async () => { + await cleanDatabase() +}) + +const searchQuery = gql` + query($query: String!) { + findResources(query: $query, limit: 5) { + __typename + ... on Post { + id + title + content + } + ... on User { + id + slug + name + } + } + } +` +describe('resolvers/searches', () => { + let variables + + describe('given one user', () => { + beforeAll(async () => { + user = await Factory.build('user', { + id: 'a-user', + name: 'John Doe', + slug: 'john-doe', + }) + authenticatedUser = await user.toJson() + }) + + describe('query contains first name of user', () => { + it('finds the user', async () => { + variables = { query: 'John' } + await expect(query({ query: searchQuery, variables })).resolves.toMatchObject({ + data: { + findResources: [ + { + id: 'a-user', + name: 'John Doe', + slug: 'john-doe', + }, + ], + }, + }) + }) + }) + + describe('adding one post', () => { + beforeAll(async () => { + await Factory.build( + 'post', + { + id: 'a-post', + title: 'Beitrag', + content: 'Ein erster Beitrag', + }, + { authorId: 'a-user' }, + ) + }) + + describe('query contains title of post', () => { + it('finds the post', async () => { + variables = { query: 'beitrag' } + await expect(query({ query: searchQuery, variables })).resolves.toMatchObject({ + data: { + findResources: [ + { + __typename: 'Post', + id: 'a-post', + title: 'Beitrag', + content: 'Ein erster Beitrag', + }, + ], + }, + }) + }) + }) + + describe('casing', () => { + it('does not matter', async () => { + variables = { query: 'BEITRAG' } + await expect(query({ query: searchQuery, variables })).resolves.toMatchObject({ + data: { + findResources: [ + { + __typename: 'Post', + id: 'a-post', + title: 'Beitrag', + content: 'Ein erster Beitrag', + }, + ], + }, + }) + }) + }) + + describe('query consists of words not present in the corpus', () => { + it('returns empty search results', async () => { + await expect( + query({ query: searchQuery, variables: { query: 'Unfug' } }), + ).resolves.toMatchObject({ data: { findResources: [] } }) + }) + }) + + describe('testing different post content', () => { + beforeAll(async () => { + return Promise.all([ + Factory.build( + 'post', + { + id: 'b-post', + title: 'Aufruf', + content: 'Jeder sollte seinen Beitrag leisten.', + }, + { authorId: 'a-user' }, + ), + Factory.build( + 'post', + { + id: 'g-post', + title: 'Zusammengesetzte Wörter', + content: `Ein Bindestrich kann zwischen zwei Substantiven auch dann gesetzt werden, wenn drei gleichlautende Buchstaben aufeinandertreffen. Das ist etwa bei einem „Teeei“ der Fall, das so korrekt geschrieben ist. Möglich ist hier auch die Schreibweise mit Bindestrich: Tee-Ei.`, + }, + { authorId: 'a-user' }, + ), + Factory.build( + 'post', + { + id: 'c-post', + title: 'Die binomischen Formeln', + content: `1. binomische Formel: (a + b)² = a² + 2ab + b² +2. binomische Formel: (a - b)² = a² - 2ab + b² +3. binomische Formel: (a + b)(a - b) = a² - b²`, + }, + { authorId: 'a-user' }, + ), + Factory.build( + 'post', + { + id: 'd-post', + title: 'Der Panther', + content: `Sein Blick ist vom Vorübergehn der Stäbe +so müd geworden, daß er nichts mehr hält. +Ihm ist, als ob es tausend Stäbe gäbe +und hinter tausend Stäben keine Welt.`, + }, + { authorId: 'a-user' }, + ), + ]) + }) + + describe('a post which content contains the title of the first post', () => { + describe('query contains the title of the first post', () => { + it('finds both posts', async () => { + variables = { query: 'beitrag' } + await expect(query({ query: searchQuery, variables })).resolves.toMatchObject({ + data: { + findResources: expect.arrayContaining([ + { + __typename: 'Post', + id: 'a-post', + title: 'Beitrag', + content: 'Ein erster Beitrag', + }, + { + __typename: 'Post', + id: 'b-post', + title: 'Aufruf', + content: 'Jeder sollte seinen Beitrag leisten.', + }, + ]), + }, + }) + }) + }) + }) + + describe('a post that contains a hyphen between two words and German quotation marks', () => { + describe('hyphens in query', () => { + it('will be treated as ordinary characters', async () => { + variables = { query: 'tee-ei' } + await expect(query({ query: searchQuery, variables })).resolves.toMatchObject({ + data: { + findResources: [ + { + __typename: 'Post', + id: 'g-post', + title: 'Zusammengesetzte Wörter', + content: `Ein Bindestrich kann zwischen zwei Substantiven auch dann gesetzt werden, wenn drei gleichlautende Buchstaben aufeinandertreffen. Das ist etwa bei einem „Teeei“ der Fall, das so korrekt geschrieben ist. Möglich ist hier auch die Schreibweise mit Bindestrich: Tee-Ei.`, + }, + ], + }, + }) + }) + }) + + describe('German quotation marks in query to test unicode characters (\u201E ... \u201C)', () => { + it('will be treated as ordinary characters', async () => { + variables = { query: '„teeei“' } + await expect(query({ query: searchQuery, variables })).resolves.toMatchObject({ + data: { + findResources: [ + { + __typename: 'Post', + id: 'g-post', + title: 'Zusammengesetzte Wörter', + content: `Ein Bindestrich kann zwischen zwei Substantiven auch dann gesetzt werden, wenn drei gleichlautende Buchstaben aufeinandertreffen. Das ist etwa bei einem „Teeei“ der Fall, das so korrekt geschrieben ist. Möglich ist hier auch die Schreibweise mit Bindestrich: Tee-Ei.`, + }, + ], + }, + }) + }) + }) + }) + + describe('a post that contains a simple mathematical exprssion and line breaks', () => { + describe('query a part of the mathematical expression', () => { + it('finds that post', async () => { + variables = { query: '(a - b)²' } + await expect(query({ query: searchQuery, variables })).resolves.toMatchObject({ + data: { + findResources: [ + { + __typename: 'Post', + id: 'c-post', + title: 'Die binomischen Formeln', + content: `1. binomische Formel: (a + b)² = a² + 2ab + b²
+2. binomische Formel: (a - b)² = a² - 2ab + b²
+3. binomische Formel: (a + b)(a - b) = a² - b²`, + }, + ], + }, + }) + }) + }) + + describe('query the same part of the mathematical expression without spaces', () => { + it('finds that post', async () => { + variables = { query: '(a-b)²' } + await expect(query({ query: searchQuery, variables })).resolves.toMatchObject({ + data: { + findResources: [ + { + __typename: 'Post', + id: 'c-post', + title: 'Die binomischen Formeln', + content: `1. binomische Formel: (a + b)² = a² + 2ab + b²
+2. binomische Formel: (a - b)² = a² - 2ab + b²
+3. binomische Formel: (a + b)(a - b) = a² - b²`, + }, + ], + }, + }) + }) + }) + + describe('query the mathematical expression over line break', () => { + it('finds that post', async () => { + variables = { query: '+ b² 2.' } + await expect(query({ query: searchQuery, variables })).resolves.toMatchObject({ + data: { + findResources: [ + { + __typename: 'Post', + id: 'c-post', + title: 'Die binomischen Formeln', + content: `1. binomische Formel: (a + b)² = a² + 2ab + b²
+2. binomische Formel: (a - b)² = a² - 2ab + b²
+3. binomische Formel: (a + b)(a - b) = a² - b²`, + }, + ], + }, + }) + }) + }) + }) + + describe('a post that contains a poem', () => { + describe('query for more than one word, e.g. the title of the poem', () => { + it('finds the poem and another post that contains only one word but with lower score', async () => { + variables = { query: 'der panther' } + await expect(query({ query: searchQuery, variables })).resolves.toMatchObject({ + data: { + findResources: [ + { + __typename: 'Post', + id: 'd-post', + title: 'Der Panther', + content: `Sein Blick ist vom Vorübergehn der Stäbe
+so müd geworden, daß er nichts mehr hält.
+Ihm ist, als ob es tausend Stäbe gäbe
+und hinter tausend Stäben keine Welt.`, + }, + { + __typename: 'Post', + id: 'g-post', + title: 'Zusammengesetzte Wörter', + content: `Ein Bindestrich kann zwischen zwei Substantiven auch dann gesetzt werden, wenn drei gleichlautende Buchstaben aufeinandertreffen. Das ist etwa bei einem „Teeei“ der Fall, das so korrekt geschrieben ist. Möglich ist hier auch die Schreibweise mit Bindestrich: Tee-Ei.`, + }, + ], + }, + }) + }) + }) + + describe('query for the first four letters of two longer words', () => { + it('finds the posts that contain words starting with these four letters', async () => { + variables = { query: 'Vorü Subs' } + await expect(query({ query: searchQuery, variables })).resolves.toMatchObject({ + data: { + findResources: expect.arrayContaining([ + { + __typename: 'Post', + id: 'd-post', + title: 'Der Panther', + content: `Sein Blick ist vom Vorübergehn der Stäbe
+so müd geworden, daß er nichts mehr hält.
+Ihm ist, als ob es tausend Stäbe gäbe
+und hinter tausend Stäben keine Welt.`, + }, + { + __typename: 'Post', + id: 'g-post', + title: 'Zusammengesetzte Wörter', + content: `Ein Bindestrich kann zwischen zwei Substantiven auch dann gesetzt werden, wenn drei gleichlautende Buchstaben aufeinandertreffen. Das ist etwa bei einem „Teeei“ der Fall, das so korrekt geschrieben ist. Möglich ist hier auch die Schreibweise mit Bindestrich: Tee-Ei.`, + }, + ]), + }, + }) + }) + }) + }) + }) + + describe('adding two users that have the same word in their slugs', () => { + beforeAll(async () => { + await Promise.all([ + Factory.build('user', { + id: 'c-user', + name: 'Rainer Maria Rilke', + slug: 'rainer-maria-rilke', + }), + Factory.build('user', { + id: 'd-user', + name: 'Erich Maria Remarque', + slug: 'erich-maria-remarque', + }), + ]) + }) + + describe('query the word that both slugs contain', () => { + it('finds both users', async () => { + variables = { query: '-maria-' } + await expect(query({ query: searchQuery, variables })).resolves.toMatchObject({ + data: { + findResources: expect.arrayContaining([ + { + __typename: 'User', + id: 'c-user', + name: 'Rainer Maria Rilke', + slug: 'rainer-maria-rilke', + }, + { + __typename: 'User', + id: 'd-user', + name: 'Erich Maria Remarque', + slug: 'erich-maria-remarque', + }, + ]), + }, + }) + }) + }) + }) + + describe('adding a post, written by a user who is muted by the authenticated user', () => { + beforeAll(async () => { + const mutedUser = await Factory.build('user', { + id: 'muted-user', + name: 'Muted', + slug: 'muted', + }) + await user.relateTo(mutedUser, 'muted') + await Factory.build( + 'post', + { + id: 'muted-post', + title: 'Beleidigender Beitrag', + content: 'Dieser Beitrag stammt von einem bleidigendem Nutzer.', + }, + { authorId: 'muted-user' }, + ) + }) + + describe('query for text in a post written by a muted user', () => { + it('does not include the post of the muted user in the results', async () => { + variables = { query: 'beitrag' } + await expect(query({ query: searchQuery, variables })).resolves.toMatchObject({ + data: { + findResources: expect.not.arrayContaining([ + { + __typename: 'Post', + id: 'muted-post', + title: 'Beleidigender Beitrag', + content: 'Dieser Beitrag stammt von einem bleidigendem Nutzer.', + }, + ]), + }, + }) + }) + }) + }) + }) + }) +}) diff --git a/backend/src/schema/resolvers/searches/queryString.js b/backend/src/schema/resolvers/searches/queryString.js new file mode 100644 index 000000000..c3500188c --- /dev/null +++ b/backend/src/schema/resolvers/searches/queryString.js @@ -0,0 +1,47 @@ +export function queryString(str) { + const normalizedString = normalizeWhitespace(str) + const escapedString = escapeSpecialCharacters(normalizedString) + return ` +${matchWholeText(escapedString)} +${matchEachWordExactly(escapedString)} +${matchSomeWordsExactly(escapedString)} +${matchBeginningOfWords(escapedString)} +` +} + +const matchWholeText = (str, boost = 8) => { + return `"${str}"^${boost}` +} + +const matchEachWordExactly = (str, boost = 4) => { + if (!str.includes(' ')) return '' + const tmp = str + .split(' ') + .map((s, i) => (i === 0 ? `"${s}"` : `AND "${s}"`)) + .join(' ') + return `(${tmp})^${boost}` +} + +const matchSomeWordsExactly = (str, boost = 2) => { + if (!str.includes(' ')) return '' + return str + .split(' ') + .map(s => `"${s}"^${boost}`) + .join(' ') +} + +const matchBeginningOfWords = str => { + return str + .split(' ') + .filter(s => s.length > 3) + .map(s => s + '*') + .join(' ') +} + +export function normalizeWhitespace(str) { + return str.replace(/\s+/g, ' ').trim() +} + +export function escapeSpecialCharacters(str) { + return str.replace(/(["[\]&|\\{}+!()^~*?:/-])/g, '\\$1') +} diff --git a/backend/src/schema/resolvers/searches/queryString.spec.js b/backend/src/schema/resolvers/searches/queryString.spec.js new file mode 100644 index 000000000..23a746be1 --- /dev/null +++ b/backend/src/schema/resolvers/searches/queryString.spec.js @@ -0,0 +1,43 @@ +import { queryString, escapeSpecialCharacters, normalizeWhitespace } from './queryString' + +describe('queryString', () => { + describe('special characters', () => { + it('does escaping correctly', () => { + expect(escapeSpecialCharacters('+ - && || ! ( ) { } [ ] ^ " ~ * ? : \\ / ')).toEqual( + '\\+ \\- \\&\\& \\|\\| \\! \\( \\) \\{ \\} \\[ \\] \\^ \\" \\~ \\* \\? \\: \\\\ \\/ ', + ) + }) + }) + + describe('whitespace', () => { + it('normalizes correctly', () => { + expect(normalizeWhitespace(' a \t \n b \n ')).toEqual('a b') + }) + }) + + describe('exact match', () => { + it('boosts score by factor 8', () => { + expect(queryString('a couple of words')).toContain('"a couple of words"^8') + }) + }) + + describe('match all words exactly', () => { + it('boosts score by factor 4', () => { + expect(queryString('a couple of words')).toContain( + '("a" AND "couple" AND "of" AND "words")^4', + ) + }) + }) + + describe('match at least one word exactly', () => { + it('boosts score by factor 2', () => { + expect(queryString('a couple of words')).toContain('"a"^2 "couple"^2 "of"^2 "words"^2') + }) + }) + + describe('globbing for longer words', () => { + it('globs words with more than three characters', () => { + expect(queryString('a couple of words')).toContain('couple* words*') + }) + }) +}) diff --git a/backend/src/schema/resolvers/user_management.js b/backend/src/schema/resolvers/user_management.js index 2014b01b8..dd081321d 100644 --- a/backend/src/schema/resolvers/user_management.js +++ b/backend/src/schema/resolvers/user_management.js @@ -48,7 +48,7 @@ export default { const loginTransactionResponse = await transaction.run( ` MATCH (user:User {deleted: false})-[:PRIMARY_EMAIL]->(e:EmailAddress {email: $userEmail}) - RETURN user {.id, .slug, .name, .avatar, .encryptedPassword, .role, .disabled, email:e.email} as user LIMIT 1 + RETURN user {.id, .slug, .name, .encryptedPassword, .role, .disabled, email:e.email} as user LIMIT 1 `, { userEmail: email }, ) diff --git a/backend/src/schema/resolvers/user_management.spec.js b/backend/src/schema/resolvers/user_management.spec.js index 1e295638d..399e2ace3 100644 --- a/backend/src/schema/resolvers/user_management.spec.js +++ b/backend/src/schema/resolvers/user_management.spec.js @@ -106,7 +106,9 @@ describe('currentUser', () => { id slug name - avatar + avatar { + url + } email role } @@ -131,13 +133,15 @@ describe('currentUser', () => { { id: 'u3', // the `id` is the only thing that has to match the decoded JWT bearer token - avatar: 'https://s3.amazonaws.com/uifaces/faces/twitter/jimmuirhead/128.jpg', name: 'Matilde Hermiston', slug: 'matilde-hermiston', role: 'user', }, { email: 'test@example.org', + avatar: Factory.build('image', { + url: 'https://s3.amazonaws.com/uifaces/faces/twitter/jimmuirhead/128.jpg', + }), }, ) const userBearerToken = encode({ id: 'u3' }) @@ -149,7 +153,9 @@ describe('currentUser', () => { data: { currentUser: { id: 'u3', - avatar: 'https://s3.amazonaws.com/uifaces/faces/twitter/jimmuirhead/128.jpg', + avatar: Factory.build('image', { + url: 'https://s3.amazonaws.com/uifaces/faces/twitter/jimmuirhead/128.jpg', + }), email: 'test@example.org', name: 'Matilde Hermiston', slug: 'matilde-hermiston', diff --git a/backend/src/schema/resolvers/users.js b/backend/src/schema/resolvers/users.js index a1b68e20d..252265ac3 100644 --- a/backend/src/schema/resolvers/users.js +++ b/backend/src/schema/resolvers/users.js @@ -1,7 +1,7 @@ import { neo4jgraphql } from 'neo4j-graphql-js' -import fileUpload from './fileUpload' import { getNeode } from '../../db/neo4j' import { UserInputError, ForbiddenError } from 'apollo-server' +import { mergeImage, deleteImage } from './images/images' import Resolver from './helpers/Resolver' import log from './helpers/databaseLogger' import createOrUpdateLocations from './users/location' @@ -140,6 +140,8 @@ export default { }, UpdateUser: async (_parent, params, context, _resolveInfo) => { const { termsAndConditionsAgreedVersion } = params + const { avatar: avatarInput } = params + delete params.avatar if (termsAndConditionsAgreedVersion) { const regEx = new RegExp(/^[0-9]+\.[0-9]+\.[0-9]+$/g) if (!regEx.test(termsAndConditionsAgreedVersion)) { @@ -147,7 +149,6 @@ export default { } params.termsAndConditionsAgreedAt = new Date().toISOString() } - params = await fileUpload(params, { file: 'avatarUpload', url: 'avatar' }) const session = context.driver.session() const writeTxResultPromise = session.writeTransaction(async transaction => { @@ -156,14 +157,18 @@ export default { MATCH (user:User {id: $params.id}) SET user += $params SET user.updatedAt = toString(datetime()) - RETURN user + RETURN user {.*} `, { params }, ) - return updateUserTransactionResponse.records.map(record => record.get('user').properties) + const [user] = updateUserTransactionResponse.records.map(record => record.get('user')) + if (avatarInput) { + await mergeImage(user, 'AVATAR_IMAGE', avatarInput, { transaction }) + } + return user }) try { - const [user] = await writeTxResultPromise + const user = await writeTxResultPromise await createOrUpdateLocations(params.id, params.locationName, session) return user } catch (error) { @@ -173,33 +178,38 @@ export default { } }, DeleteUser: async (object, params, context, resolveInfo) => { - const { resource } = params + const { resource, id: userId } = params const session = context.driver.session() - try { + + const deleteUserTxResultPromise = session.writeTransaction(async transaction => { if (resource && resource.length) { - await session.writeTransaction(transaction => { - resource.map(node => { - return transaction.run( + await Promise.all( + resource.map(async node => { + const txResult = await transaction.run( ` - MATCH (resource:${node})<-[:WROTE]-(author:User {id: $userId}) - OPTIONAL MATCH (resource)<-[:COMMENTS]-(comment:Comment) - SET resource.deleted = true - SET resource.content = 'UNAVAILABLE' - SET resource.contentExcerpt = 'UNAVAILABLE' - SET comment.deleted = true - RETURN author - `, + MATCH (resource:${node})<-[:WROTE]-(author:User {id: $userId}) + OPTIONAL MATCH (resource)<-[:COMMENTS]-(comment:Comment) + SET resource.deleted = true + SET resource.content = 'UNAVAILABLE' + SET resource.contentExcerpt = 'UNAVAILABLE' + SET comment.deleted = true + RETURN resource {.*} + `, { - userId: context.user.id, + userId, }, ) - }) - }) + return Promise.all( + txResult.records + .map(record => record.get('resource')) + .map(resource => deleteImage(resource, 'HERO_IMAGE', { transaction })), + ) + }), + ) } - const deleteUserTxResultPromise = session.writeTransaction(async transaction => { - const deleteUserTransactionResponse = await transaction.run( - ` + const deleteUserTransactionResponse = await transaction.run( + ` MATCH (user:User {id: $userId}) SET user.deleted = true SET user.name = 'UNAVAILABLE' @@ -210,14 +220,17 @@ export default { WITH user OPTIONAL MATCH (user)<-[:OWNED_BY]-(socialMedia:SocialMedia) DETACH DELETE socialMedia - RETURN user + RETURN user {.*} `, - { userId: context.user.id }, - ) - log(deleteUserTransactionResponse) - return deleteUserTransactionResponse.records.map(record => record.get('user').properties) - }) - const [user] = await deleteUserTxResultPromise + { userId }, + ) + log(deleteUserTransactionResponse) + const [user] = deleteUserTransactionResponse.records.map(record => record.get('user')) + await deleteImage(user, 'AVATAR_IMAGE', { transaction }) + return user + }) + try { + const user = await deleteUserTxResultPromise return user } finally { session.close() @@ -236,8 +249,6 @@ export default { ...Resolver('User', { undefinedToNull: [ 'actorId', - 'avatar', - 'coverImg', 'deleted', 'disabled', 'locationName', @@ -271,6 +282,7 @@ export default { badgesCount: '<-[:REWARDED]-(related:Badge)', }, hasOne: { + avatar: '-[:AVATAR_IMAGE]->(related:Image)', invitedBy: '<-[:INVITED]-(related:User)', location: '-[:IS_IN]->(related:Location)', }, diff --git a/backend/src/schema/resolvers/users.spec.js b/backend/src/schema/resolvers/users.spec.js index 9e24b8082..cb9012133 100644 --- a/backend/src/schema/resolvers/users.spec.js +++ b/backend/src/schema/resolvers/users.spec.js @@ -29,7 +29,7 @@ beforeAll(() => { mutate = createTestClient(server).mutate }) -afterEach(async () => { +beforeEach(async () => { await cleanDatabase() }) @@ -273,189 +273,142 @@ describe('DeleteUser', () => { } } ` - beforeEach(async () => { - variables = { id: ' u343', resource: [] } + describe('as another user', () => { + beforeEach(async () => { + variables = { id: ' u343', resource: [] } - user = await Factory.build('user', { - name: 'My name should be deleted', - about: 'along with my about', - id: 'u343', + user = await Factory.build('user', { + name: 'My name should be deleted', + about: 'along with my about', + id: 'u343', + }) }) - await Factory.build( - 'user', - { - id: 'not-my-account', - }, - { - email: 'friends-account@example.org', - }, - ) - }) - describe('unauthenticated', () => { - it('throws authorization error', async () => { + beforeEach(async () => { + const anotherUser = await Factory.build( + 'user', + { + role: 'user', + }, + { + email: 'user@example.org', + password: '1234', + }, + ) + + authenticatedUser = await anotherUser.toJson() + }) + + it("an ordinary user has no authorization to delete another user's account", async () => { const { errors } = await mutate({ mutation: deleteUserMutation, variables }) expect(errors[0]).toHaveProperty('message', 'Not Authorised!') }) }) - describe('authenticated', () => { + describe('as moderator', () => { beforeEach(async () => { - authenticatedUser = await user.toJson() - }) + variables = { id: ' u343', resource: [] } - describe("attempting to delete another user's account", () => { - beforeEach(() => { - variables = { ...variables, id: 'not-my-account' } - }) - - it('throws an authorization error', async () => { - const { errors } = await mutate({ mutation: deleteUserMutation, variables }) - expect(errors[0]).toHaveProperty('message', 'Not Authorised!') + user = await Factory.build('user', { + name: 'My name should be deleted', + about: 'along with my about', + id: 'u343', }) }) - describe('attempting to delete my own account', () => { - beforeEach(() => { - variables = { ...variables, id: 'u343' } + beforeEach(async () => { + const moderator = await Factory.build( + 'user', + { + role: 'moderator', + }, + { + email: 'moderator@example.org', + password: '1234', + }, + ) + + authenticatedUser = await moderator.toJson() + }) + + it('moderator is not allowed to delete other user accounts', async () => { + const { errors } = await mutate({ mutation: deleteUserMutation, variables }) + expect(errors[0]).toHaveProperty('message', 'Not Authorised!') + }) + }) + + describe('as admin', () => { + beforeEach(async () => { + variables = { id: ' u343', resource: [] } + + user = await Factory.build('user', { + name: 'My name should be deleted', + about: 'along with my about', + id: 'u343', + }) + }) + + describe('authenticated as Admin', () => { + beforeEach(async () => { + const admin = await Factory.build( + 'user', + { + role: 'admin', + }, + { + email: 'admin@example.org', + password: '1234', + }, + ) + authenticatedUser = await admin.toJson() }) - describe('given posts and comments', () => { - beforeEach(async () => { - await Factory.build('category', { - id: 'cat9', - name: 'Democracy & Politics', - icon: 'university', - }) - await Factory.build( - 'post', - { - id: 'p139', - content: 'Post by user u343', - }, - { - author: user, - categoryIds, - }, - ) - await Factory.build( - 'comment', - { - id: 'c155', - content: 'Comment by user u343', - }, - { - author: user, - }, - ) - await Factory.build( - 'comment', - { - id: 'c156', - content: "A comment by someone else on user u343's post", - }, - { - postId: 'p139', - }, - ) + describe('deleting a user account', () => { + beforeEach(() => { + variables = { ...variables, id: 'u343' } }) - it("deletes my account, but doesn't delete posts or comments by default", async () => { - const expectedResponse = { - data: { - DeleteUser: { - id: 'u343', - name: 'UNAVAILABLE', - about: 'UNAVAILABLE', - deleted: true, - contributions: [ - { - id: 'p139', - content: 'Post by user u343', - contentExcerpt: 'Post by user u343', - deleted: false, - comments: [ - { - id: 'c156', - content: "A comment by someone else on user u343's post", - contentExcerpt: "A comment by someone else on user u343's post", - deleted: false, - }, - ], - }, - ], - comments: [ - { - id: 'c155', - content: 'Comment by user u343', - contentExcerpt: 'Comment by user u343', - deleted: false, - }, - ], - }, - }, - errors: undefined, - } - await expect(mutate({ mutation: deleteUserMutation, variables })).resolves.toMatchObject( - expectedResponse, - ) - }) - - describe('deletion of all post requested', () => { - beforeEach(() => { - variables = { ...variables, resource: ['Post'] } - }) - - describe("marks user's posts as deleted", () => { - it('posts on request', async () => { - const expectedResponse = { - data: { - DeleteUser: { - id: 'u343', - name: 'UNAVAILABLE', - about: 'UNAVAILABLE', - deleted: true, - contributions: [ - { - id: 'p139', - content: 'UNAVAILABLE', - contentExcerpt: 'UNAVAILABLE', - deleted: true, - comments: [ - { - id: 'c156', - content: 'UNAVAILABLE', - contentExcerpt: 'UNAVAILABLE', - deleted: true, - }, - ], - }, - ], - comments: [ - { - id: 'c155', - content: 'Comment by user u343', - contentExcerpt: 'Comment by user u343', - deleted: false, - }, - ], - }, - }, - errors: undefined, - } - await expect( - mutate({ mutation: deleteUserMutation, variables }), - ).resolves.toMatchObject(expectedResponse) + describe('given posts and comments', () => { + beforeEach(async () => { + await Factory.build('category', { + id: 'cat9', + name: 'Democracy & Politics', + icon: 'university', }) - }) - }) - - describe('deletion of all comments requested', () => { - beforeEach(() => { - variables = { ...variables, resource: ['Comment'] } + await Factory.build( + 'post', + { + id: 'p139', + content: 'Post by user u343', + }, + { + author: user, + categoryIds, + }, + ) + await Factory.build( + 'comment', + { + id: 'c155', + content: 'Comment by user u343', + }, + { + author: user, + }, + ) + await Factory.build( + 'comment', + { + id: 'c156', + content: "A comment by someone else on user u343's post", + }, + { + postId: 'p139', + }, + ) }) - it('marks comments as deleted', async () => { + it("deletes account, but doesn't delete posts or comments by default", async () => { const expectedResponse = { data: { DeleteUser: { @@ -482,9 +435,9 @@ describe('DeleteUser', () => { comments: [ { id: 'c155', - content: 'UNAVAILABLE', - contentExcerpt: 'UNAVAILABLE', - deleted: true, + content: 'Comment by user u343', + contentExcerpt: 'Comment by user u343', + deleted: false, }, ], }, @@ -495,14 +448,263 @@ describe('DeleteUser', () => { mutate({ mutation: deleteUserMutation, variables }), ).resolves.toMatchObject(expectedResponse) }) - }) - describe('deletion of all post and comments requested', () => { - beforeEach(() => { - variables = { ...variables, resource: ['Post', 'Comment'] } + describe('deletion of all post requested', () => { + beforeEach(() => { + variables = { ...variables, resource: ['Post'] } + }) + + describe("marks user's posts as deleted", () => { + it('on request', async () => { + const expectedResponse = { + data: { + DeleteUser: { + id: 'u343', + name: 'UNAVAILABLE', + about: 'UNAVAILABLE', + deleted: true, + contributions: [ + { + id: 'p139', + content: 'UNAVAILABLE', + contentExcerpt: 'UNAVAILABLE', + deleted: true, + comments: [ + { + id: 'c156', + content: 'UNAVAILABLE', + contentExcerpt: 'UNAVAILABLE', + deleted: true, + }, + ], + }, + ], + comments: [ + { + id: 'c155', + content: 'Comment by user u343', + contentExcerpt: 'Comment by user u343', + deleted: false, + }, + ], + }, + }, + errors: undefined, + } + await expect( + mutate({ mutation: deleteUserMutation, variables }), + ).resolves.toMatchObject(expectedResponse) + }) + + it('deletes user avatar and post hero images', async () => { + await expect(neode.all('Image')).resolves.toHaveLength(22) + await mutate({ mutation: deleteUserMutation, variables }) + await expect(neode.all('Image')).resolves.toHaveLength(20) + }) + }) }) - it('marks posts and comments as deleted', async () => { + describe('deletion of all comments requested', () => { + beforeEach(() => { + variables = { ...variables, resource: ['Comment'] } + }) + + it('marks comments as deleted', async () => { + const expectedResponse = { + data: { + DeleteUser: { + id: 'u343', + name: 'UNAVAILABLE', + about: 'UNAVAILABLE', + deleted: true, + contributions: [ + { + id: 'p139', + content: 'Post by user u343', + contentExcerpt: 'Post by user u343', + deleted: false, + comments: [ + { + id: 'c156', + content: "A comment by someone else on user u343's post", + contentExcerpt: "A comment by someone else on user u343's post", + deleted: false, + }, + ], + }, + ], + comments: [ + { + id: 'c155', + content: 'UNAVAILABLE', + contentExcerpt: 'UNAVAILABLE', + deleted: true, + }, + ], + }, + }, + errors: undefined, + } + await expect( + mutate({ mutation: deleteUserMutation, variables }), + ).resolves.toMatchObject(expectedResponse) + }) + }) + + describe('deletion of all posts and comments requested', () => { + beforeEach(() => { + variables = { ...variables, resource: ['Post', 'Comment'] } + }) + + it('marks posts and comments as deleted', async () => { + const expectedResponse = { + data: { + DeleteUser: { + id: 'u343', + name: 'UNAVAILABLE', + about: 'UNAVAILABLE', + deleted: true, + contributions: [ + { + id: 'p139', + content: 'UNAVAILABLE', + contentExcerpt: 'UNAVAILABLE', + deleted: true, + comments: [ + { + id: 'c156', + content: 'UNAVAILABLE', + contentExcerpt: 'UNAVAILABLE', + deleted: true, + }, + ], + }, + ], + comments: [ + { + id: 'c155', + content: 'UNAVAILABLE', + contentExcerpt: 'UNAVAILABLE', + deleted: true, + }, + ], + }, + }, + errors: undefined, + } + await expect( + mutate({ mutation: deleteUserMutation, variables }), + ).resolves.toMatchObject(expectedResponse) + }) + }) + }) + + describe('connected `EmailAddress` nodes', () => { + it('will be removed completely', async () => { + await expect(neode.all('EmailAddress')).resolves.toHaveLength(2) + await mutate({ mutation: deleteUserMutation, variables }) + await expect(neode.all('EmailAddress')).resolves.toHaveLength(1) + }) + }) + + describe('connected `SocialMedia` nodes', () => { + beforeEach(async () => { + const socialMedia = await Factory.build('socialMedia') + await socialMedia.relateTo(user, 'ownedBy') + }) + + it('will be removed completely', async () => { + await expect(neode.all('SocialMedia')).resolves.toHaveLength(1) + await mutate({ mutation: deleteUserMutation, variables }) + await expect(neode.all('SocialMedia')).resolves.toHaveLength(0) + }) + }) + }) + }) + }) + + describe('user deletes his own account', () => { + beforeEach(async () => { + variables = { id: 'u343', resource: [] } + + user = await Factory.build('user', { + name: 'My name should be deleted', + about: 'along with my about', + id: 'u343', + }) + await Factory.build( + 'user', + { + id: 'not-my-account', + }, + { + email: 'friends-account@example.org', + }, + ) + }) + + describe('authenticated', () => { + beforeEach(async () => { + authenticatedUser = await user.toJson() + }) + + describe("attempting to delete another user's account", () => { + beforeEach(() => { + variables = { ...variables, id: 'not-my-account' } + }) + + it('throws an authorization error', async () => { + const { errors } = await mutate({ mutation: deleteUserMutation, variables }) + expect(errors[0]).toHaveProperty('message', 'Not Authorised!') + }) + }) + + describe('attempting to delete my own account', () => { + beforeEach(() => { + variables = { ...variables, id: 'u343' } + }) + + describe('given posts and comments', () => { + beforeEach(async () => { + await Factory.build('category', { + id: 'cat9', + name: 'Democracy & Politics', + icon: 'university', + }) + await Factory.build( + 'post', + { + id: 'p139', + content: 'Post by user u343', + }, + { + author: user, + categoryIds, + }, + ) + await Factory.build( + 'comment', + { + id: 'c155', + content: 'Comment by user u343', + }, + { + author: user, + }, + ) + await Factory.build( + 'comment', + { + id: 'c156', + content: "A comment by someone else on user u343's post", + }, + { + postId: 'p139', + }, + ) + }) + + it("deletes my account, but doesn't delete posts or comments by default", async () => { const expectedResponse = { data: { DeleteUser: { @@ -513,15 +715,15 @@ describe('DeleteUser', () => { contributions: [ { id: 'p139', - content: 'UNAVAILABLE', - contentExcerpt: 'UNAVAILABLE', - deleted: true, + content: 'Post by user u343', + contentExcerpt: 'Post by user u343', + deleted: false, comments: [ { id: 'c156', - content: 'UNAVAILABLE', - contentExcerpt: 'UNAVAILABLE', - deleted: true, + content: "A comment by someone else on user u343's post", + contentExcerpt: "A comment by someone else on user u343's post", + deleted: false, }, ], }, @@ -529,9 +731,9 @@ describe('DeleteUser', () => { comments: [ { id: 'c155', - content: 'UNAVAILABLE', - contentExcerpt: 'UNAVAILABLE', - deleted: true, + content: 'Comment by user u343', + contentExcerpt: 'Comment by user u343', + deleted: false, }, ], }, @@ -542,28 +744,176 @@ describe('DeleteUser', () => { mutate({ mutation: deleteUserMutation, variables }), ).resolves.toMatchObject(expectedResponse) }) + + describe('deletion of all post requested', () => { + beforeEach(() => { + variables = { ...variables, resource: ['Post'] } + }) + + describe("marks user's posts as deleted", () => { + it('posts on request', async () => { + const expectedResponse = { + data: { + DeleteUser: { + id: 'u343', + name: 'UNAVAILABLE', + about: 'UNAVAILABLE', + deleted: true, + contributions: [ + { + id: 'p139', + content: 'UNAVAILABLE', + contentExcerpt: 'UNAVAILABLE', + deleted: true, + comments: [ + { + id: 'c156', + content: 'UNAVAILABLE', + contentExcerpt: 'UNAVAILABLE', + deleted: true, + }, + ], + }, + ], + comments: [ + { + id: 'c155', + content: 'Comment by user u343', + contentExcerpt: 'Comment by user u343', + deleted: false, + }, + ], + }, + }, + errors: undefined, + } + await expect( + mutate({ mutation: deleteUserMutation, variables }), + ).resolves.toMatchObject(expectedResponse) + }) + + it('deletes user avatar and post hero images', async () => { + await expect(neode.all('Image')).resolves.toHaveLength(22) + await mutate({ mutation: deleteUserMutation, variables }) + await expect(neode.all('Image')).resolves.toHaveLength(20) + }) + }) + }) + + describe('deletion of all comments requested', () => { + beforeEach(() => { + variables = { ...variables, resource: ['Comment'] } + }) + + it('marks comments as deleted', async () => { + const expectedResponse = { + data: { + DeleteUser: { + id: 'u343', + name: 'UNAVAILABLE', + about: 'UNAVAILABLE', + deleted: true, + contributions: [ + { + id: 'p139', + content: 'Post by user u343', + contentExcerpt: 'Post by user u343', + deleted: false, + comments: [ + { + id: 'c156', + content: "A comment by someone else on user u343's post", + contentExcerpt: "A comment by someone else on user u343's post", + deleted: false, + }, + ], + }, + ], + comments: [ + { + id: 'c155', + content: 'UNAVAILABLE', + contentExcerpt: 'UNAVAILABLE', + deleted: true, + }, + ], + }, + }, + errors: undefined, + } + await expect( + mutate({ mutation: deleteUserMutation, variables }), + ).resolves.toMatchObject(expectedResponse) + }) + }) + describe('deletion of all post and comments requested', () => { + beforeEach(() => { + variables = { ...variables, resource: ['Post', 'Comment'] } + }) + + it('marks posts and comments as deleted', async () => { + const expectedResponse = { + data: { + DeleteUser: { + id: 'u343', + name: 'UNAVAILABLE', + about: 'UNAVAILABLE', + deleted: true, + contributions: [ + { + id: 'p139', + content: 'UNAVAILABLE', + contentExcerpt: 'UNAVAILABLE', + deleted: true, + comments: [ + { + id: 'c156', + content: 'UNAVAILABLE', + contentExcerpt: 'UNAVAILABLE', + deleted: true, + }, + ], + }, + ], + comments: [ + { + id: 'c155', + content: 'UNAVAILABLE', + contentExcerpt: 'UNAVAILABLE', + deleted: true, + }, + ], + }, + }, + errors: undefined, + } + await expect( + mutate({ mutation: deleteUserMutation, variables }), + ).resolves.toMatchObject(expectedResponse) + }) + }) }) }) + }) - describe('connected `EmailAddress` nodes', () => { - it('will be removed completely', async () => { - await expect(neode.all('EmailAddress')).resolves.toHaveLength(2) - await mutate({ mutation: deleteUserMutation, variables }) - await expect(neode.all('EmailAddress')).resolves.toHaveLength(1) - }) + describe('connected `EmailAddress` nodes', () => { + it('will be removed completely', async () => { + await expect(neode.all('EmailAddress')).resolves.toHaveLength(2) + await mutate({ mutation: deleteUserMutation, variables }) + await expect(neode.all('EmailAddress')).resolves.toHaveLength(1) + }) + }) + + describe('connected `SocialMedia` nodes', () => { + beforeEach(async () => { + const socialMedia = await Factory.build('socialMedia') + await socialMedia.relateTo(user, 'ownedBy') }) - describe('connected `SocialMedia` nodes', () => { - beforeEach(async () => { - const socialMedia = await Factory.build('socialMedia') - await socialMedia.relateTo(user, 'ownedBy') - }) - - it('will be removed completely', async () => { - await expect(neode.all('SocialMedia')).resolves.toHaveLength(1) - await mutate({ mutation: deleteUserMutation, variables }) - await expect(neode.all('SocialMedia')).resolves.toHaveLength(0) - }) + it('will be removed completely', async () => { + await expect(neode.all('SocialMedia')).resolves.toHaveLength(1) + await mutate({ mutation: deleteUserMutation, variables }) + await expect(neode.all('SocialMedia')).resolves.toHaveLength(0) }) }) }) diff --git a/backend/src/schema/resolvers/users/location.spec.js b/backend/src/schema/resolvers/users/location.spec.js index 04216dcb5..2e74e5c03 100644 --- a/backend/src/schema/resolvers/users/location.spec.js +++ b/backend/src/schema/resolvers/users/location.spec.js @@ -8,28 +8,6 @@ const neode = getNeode() const driver = getDriver() let authenticatedUser, mutate, variables -const signupVerificationMutation = gql` - mutation( - $name: String! - $password: String! - $email: String! - $nonce: String! - $termsAndConditionsAgreedVersion: String! - $locationName: String - ) { - SignupVerification( - name: $name - password: $password - email: $email - nonce: $nonce - termsAndConditionsAgreedVersion: $termsAndConditionsAgreedVersion - locationName: $locationName - ) { - locationName - } - } -` - const updateUserMutation = gql` mutation($id: ID!, $name: String!, $locationName: String) { UpdateUser(id: $id, name: $name, locationName: $locationName) { @@ -38,9 +16,10 @@ const updateUserMutation = gql` } ` -let newlyCreatedNodesWithLocales = [ +const newlyCreatedNodesWithLocales = [ { city: { + lng: -74.5763, lat: 41.1534, nameES: 'Hamburg', nameFR: 'Hamburg', @@ -54,7 +33,6 @@ let newlyCreatedNodesWithLocales = [ name: 'Hamburg', namePL: 'Hamburg', id: 'place.5977106083398860', - lng: -74.5763, }, state: { namePT: 'Nova Jérsia', @@ -105,82 +83,12 @@ beforeEach(() => { authenticatedUser = null }) -afterEach(() => { - cleanDatabase() -}) +afterEach(cleanDatabase) describe('userMiddleware', () => { - describe('SignupVerification', () => { - beforeEach(async () => { - variables = { - ...variables, - name: 'John Doe', - password: '123', - email: 'john@example.org', - nonce: '123456', - termsAndConditionsAgreedVersion: '0.1.0', - locationName: 'Hamburg, New Jersey, United States of America', - } - const args = { - email: 'john@example.org', - nonce: '123456', - } - await neode.model('EmailAddress').create(args) - }) - it('creates a Location node with localised city/state/country names', async () => { - await mutate({ mutation: signupVerificationMutation, variables }) - const locations = await neode.cypher( - `MATCH (city:Location)-[:IS_IN]->(state:Location)-[:IS_IN]->(country:Location) return city, state, country`, - ) - expect( - locations.records.map(record => { - return { - city: record.get('city').properties, - state: record.get('state').properties, - country: record.get('country').properties, - } - }), - ).toEqual(newlyCreatedNodesWithLocales) - }) - }) - describe('UpdateUser', () => { let user beforeEach(async () => { - newlyCreatedNodesWithLocales = [ - { - city: { - lat: 53.55, - nameES: 'Hamburgo', - nameFR: 'Hambourg', - nameIT: 'Amburgo', - nameEN: 'Hamburg', - type: 'region', - namePT: 'Hamburgo', - nameRU: 'Гамбург', - nameDE: 'Hamburg', - nameNL: 'Hamburg', - namePL: 'Hamburg', - name: 'Hamburg', - id: 'region.10793468240398860', - lng: 10, - }, - country: { - namePT: 'Alemanha', - nameRU: 'Германия', - nameDE: 'Deutschland', - nameNL: 'Duitsland', - nameES: 'Alemania', - name: 'Germany', - namePL: 'Niemcy', - nameFR: 'Allemagne', - nameIT: 'Germania', - id: 'country.10743216036480410', - nameEN: 'Germany', - type: 'country', - }, - }, - ] user = await Factory.build('user', { id: 'updating-user', }) @@ -192,17 +100,18 @@ describe('userMiddleware', () => { ...variables, id: 'updating-user', name: 'Updating user', - locationName: 'Hamburg, Germany', + locationName: 'Hamburg, New Jersey, United States of America', } await mutate({ mutation: updateUserMutation, variables }) const locations = await neode.cypher( - `MATCH (city:Location)-[:IS_IN]->(country:Location) return city, country`, + `MATCH (city:Location)-[:IS_IN]->(state:Location)-[:IS_IN]->(country:Location) return city {.*}, state {.*}, country {.*}`, ) expect( locations.records.map(record => { return { - city: record.get('city').properties, - country: record.get('country').properties, + city: record.get('city'), + state: record.get('state'), + country: record.get('country'), } }), ).toEqual(newlyCreatedNodesWithLocales) diff --git a/backend/src/schema/types/type/EmailAddress.gql b/backend/src/schema/types/type/EmailAddress.gql index 99e309602..e09ec9e63 100644 --- a/backend/src/schema/types/type/EmailAddress.gql +++ b/backend/src/schema/types/type/EmailAddress.gql @@ -9,14 +9,10 @@ type Mutation { SignupByInvitation(email: String!, token: String!): EmailAddress SignupVerification( nonce: String! - name: String! email: String! + name: String! password: String! slug: String - avatar: String - coverImg: String - avatarUpload: Upload - locationName: String about: String termsAndConditionsAgreedVersion: String! locale: String diff --git a/backend/src/schema/types/type/Image.gql b/backend/src/schema/types/type/Image.gql new file mode 100644 index 000000000..41cc11eef --- /dev/null +++ b/backend/src/schema/types/type/Image.gql @@ -0,0 +1,18 @@ +type Image { + url: ID!, + # urlW34: String, + # urlW160: String, + # urlW320: String, + # urlW640: String, + # urlW1024: String, + alt: String, + sensitive: Boolean, + aspectRatio: Float, +} + +input ImageInput { + alt: String, + upload: Upload, + sensitive: Boolean, + aspectRatio: Float, +} diff --git a/backend/src/schema/types/type/Post.gql b/backend/src/schema/types/type/Post.gql index 71fcb9605..01d8409ad 100644 --- a/backend/src/schema/types/type/Post.gql +++ b/backend/src/schema/types/type/Post.gql @@ -40,7 +40,6 @@ input _PostFilter { content_not_starts_with: String content_ends_with: String content_not_ends_with: String - image: String visibility: Visibility visibility_not: Visibility visibility_in: [Visibility!] @@ -82,7 +81,6 @@ input _PostFilter { emotions_none: _PostEMOTEDFilter emotions_single: _PostEMOTEDFilter emotions_every: _PostEMOTEDFilter - imageBlurred: Boolean } enum _PostOrdering { @@ -94,8 +92,6 @@ enum _PostOrdering { slug_desc content_asc content_desc - image_asc - image_desc visibility_asc visibility_desc createdAt_asc @@ -118,9 +114,7 @@ type Post { slug: String! content: String! contentExcerpt: String - image: String - imageUpload: Upload - imageAspectRatio: Float + image: Image @relation(name: "HERO_IMAGE", direction: "OUT") visibility: Visibility deleted: Boolean disabled: Boolean @@ -128,7 +122,6 @@ type Post { createdAt: String updatedAt: String language: String - imageBlurred: Boolean pinnedAt: String @cypher( statement: "MATCH (this)<-[pinned:PINNED]-(:User) WHERE NOT this.deleted = true AND NOT this.disabled = true RETURN pinned.createdAt" ) @@ -178,14 +171,11 @@ type Mutation { title: String! slug: String content: String! - image: String - imageUpload: Upload + image: ImageInput, visibility: Visibility language: String categoryIds: [ID] contentExcerpt: String - imageBlurred: Boolean - imageAspectRatio: Float ): Post UpdatePost( id: ID! @@ -193,13 +183,10 @@ type Mutation { slug: String content: String! contentExcerpt: String - image: String - imageUpload: Upload + image: ImageInput, visibility: Visibility language: String categoryIds: [ID] - imageBlurred: Boolean - imageAspectRatio: Float ): Post DeletePost(id: ID!): Post AddPostEmotions(to: _PostInput!, data: _EMOTEDInput!): EMOTED diff --git a/backend/src/schema/types/type/User.gql b/backend/src/schema/types/type/User.gql index 4c3555049..af525396b 100644 --- a/backend/src/schema/types/type/User.gql +++ b/backend/src/schema/types/type/User.gql @@ -5,10 +5,6 @@ enum _UserOrdering { name_desc slug_asc slug_desc - avatar_asc - avatar_desc - coverImg_asc - coverImg_desc role_asc role_desc locationName_asc @@ -29,8 +25,7 @@ type User { name: String email: String! @cypher(statement: "MATCH (this)-[:PRIMARY_EMAIL]->(e:EmailAddress) RETURN e.email") slug: String! - avatar: String - coverImg: String + avatar: Image @relation(name: "AVATAR_IMAGE", direction: "OUT") deleted: Boolean disabled: Boolean role: UserGroup! @@ -161,8 +156,6 @@ type Query { email: String # admins need to search for a user sometimes name: String slug: String - avatar: String - coverImg: String role: UserGroup locationName: String about: String @@ -198,9 +191,7 @@ type Mutation { name: String email: String slug: String - avatar: String - coverImg: String - avatarUpload: Upload + avatar: ImageInput locationName: String about: String termsAndConditionsAgreedVersion: String diff --git a/backend/yarn.lock b/backend/yarn.lock index caa61caf5..a514a60b4 100644 --- a/backend/yarn.lock +++ b/backend/yarn.lock @@ -795,14 +795,7 @@ core-js-pure "^3.0.0" regenerator-runtime "^0.13.2" -"@babel/runtime@^7.0.0", "@babel/runtime@^7.5.5": - version "7.6.2" - resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.6.2.tgz#c3d6e41b304ef10dcf13777a33e7694ec4a9a6dd" - integrity sha512-EXxN64agfUqqIGeEjI5dL5z0Sw0ZwWo1mLTi4mQowCZ42O59b7DRpZAnTC6OqdF28wMBMFKNb/4uFGrVaigSpg== - dependencies: - regenerator-runtime "^0.13.2" - -"@babel/runtime@^7.8.4": +"@babel/runtime@^7.5.5", "@babel/runtime@^7.8.4", "@babel/runtime@^7.8.7": version "7.8.7" resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.8.7.tgz#8fefce9802db54881ba59f90bb28719b4996324d" integrity sha512-+AATMUFppJDw6aiR5NVPHqIQBlV/Pj8wY/EZH+lmvRdUo9xBaz/rF3alAwFJQavvKfeOlPE7oaaDHVbcySbCsg== @@ -887,10 +880,10 @@ resolved "https://registry.yarnpkg.com/@hapi/address/-/address-2.1.2.tgz#1c794cd6dbf2354d1eb1ef10e0303f573e1c7222" integrity sha512-O4QDrx+JoGKZc6aN64L04vqa7e41tIiLU+OvKdcYaEMP97UttL0f9GIi9/0A4WAMx0uBd6SidDIhktZhgOcN8Q== -"@hapi/address@^4.0.0": - version "4.0.0" - resolved "https://registry.yarnpkg.com/@hapi/address/-/address-4.0.0.tgz#36affb4509b5a6adc628bcc394450f2a7d51d111" - integrity sha512-GDDpkCdSUfkQCznmWUHh9dDN85BWf/V8TFKQ2JLuHdGB4Yy3YTEGBzZxoBNxfNBEvreSR/o+ZxBBSNNEVzY+lQ== +"@hapi/address@^4.0.1": + version "4.0.1" + resolved "https://registry.yarnpkg.com/@hapi/address/-/address-4.0.1.tgz#267301ddf7bc453718377a6fb3832a2f04a721dd" + integrity sha512-0oEP5UiyV4f3d6cBL8F3Z5S7iWSX39Knnl0lY8i+6gfmmIBj44JCBNtcMgwyS+5v7j3VYavNay0NFHDS+UGQcw== dependencies: "@hapi/hoek" "^9.0.0" @@ -924,12 +917,12 @@ "@hapi/hoek" "8.x.x" "@hapi/topo" "3.x.x" -"@hapi/joi@^17.1.0": - version "17.1.0" - resolved "https://registry.yarnpkg.com/@hapi/joi/-/joi-17.1.0.tgz#cc4000b6c928a6a39b9bef092151b6bdee10ce55" - integrity sha512-ob67RcPlwRWxBzLCnWvcwx5qbwf88I3ykD7gcJLWOTRfLLgosK7r6aeChz4thA3XRvuBfI0KB1tPVl2EQFlPXw== +"@hapi/joi@^17.1.0", "@hapi/joi@^17.1.1": + version "17.1.1" + resolved "https://registry.yarnpkg.com/@hapi/joi/-/joi-17.1.1.tgz#9cc8d7e2c2213d1e46708c6260184b447c661350" + integrity sha512-p4DKeZAoeZW4g3u7ZeRo+vCDuSDgSvtsB/NpfjXEHTUjSeINAi/RrVOWiVQ1isaoLzMvFEhe8n5065mQq1AdQg== dependencies: - "@hapi/address" "^4.0.0" + "@hapi/address" "^4.0.1" "@hapi/formula" "^2.0.0" "@hapi/hoek" "^9.0.0" "@hapi/pinpoint" "^2.0.0" @@ -1162,7 +1155,7 @@ url-regex "~4.1.1" video-extensions "~1.1.0" -"@metascraper/helpers@^5.11.1", "@metascraper/helpers@^5.11.6": +"@metascraper/helpers@^5.11.6": version "5.11.6" resolved "https://registry.yarnpkg.com/@metascraper/helpers/-/helpers-5.11.6.tgz#2fef2f420f06f4f8903cc6f699ccb79195950a60" integrity sha512-DKCJMz5Q4wrBPZVfJdeNarmW2WHm3Y7D6M78KKA/D0mcXPikKLoiBxjyPtjc5tEE/5er+PYFijDBmyTT60M2bg== @@ -1262,83 +1255,83 @@ resolved "https://registry.yarnpkg.com/@protobufjs/utf8/-/utf8-1.1.0.tgz#a777360b5b39a1a2e5106f8e858f2fd2d060c570" integrity sha1-p3c2C1s5oaLlEG+OhY8v0tBgxXA= -"@sentry/apm@5.13.1": - version "5.13.1" - resolved "https://registry.yarnpkg.com/@sentry/apm/-/apm-5.13.1.tgz#152a7a54b06f344112477cb376e8554860a6af86" - integrity sha512-be6M8/TOA/K7jQNZEm1YC0Y9+LdM0jyX5LMwy9NWwhneE6Iq8xvsU/pYZByj6+AAs0tIpiFd9QFxFKNUtKIRUQ== +"@sentry/apm@5.14.2": + version "5.14.2" + resolved "https://registry.yarnpkg.com/@sentry/apm/-/apm-5.14.2.tgz#b05b91a8da6826fdd20532cb745c0f9ef5c55656" + integrity sha512-51yeQ04mKEsx2WiXbMlUSXhmG/D+YFiNJXxKuFopJkKkT02qr7B3QH0vHkS9OX2oniYoBTWZVCKYUAgJUSsIug== dependencies: - "@sentry/browser" "5.13.0" - "@sentry/hub" "5.13.0" - "@sentry/minimal" "5.13.0" - "@sentry/types" "5.12.4" - "@sentry/utils" "5.13.0" + "@sentry/browser" "5.14.2" + "@sentry/hub" "5.14.2" + "@sentry/minimal" "5.14.2" + "@sentry/types" "5.14.2" + "@sentry/utils" "5.14.2" tslib "^1.9.3" -"@sentry/browser@5.13.0": - version "5.13.0" - resolved "https://registry.yarnpkg.com/@sentry/browser/-/browser-5.13.0.tgz#399b0a09d6603726d787b746bcc70659010bc50c" - integrity sha512-adiW9gG/gCrl6FQAA6Fk8osXMHxP3pYltszRK0mr55O7GcTC8RQNI3mEW/YuQV9IySUL8dFWQ0v8n0lfssHf/A== +"@sentry/browser@5.14.2": + version "5.14.2" + resolved "https://registry.yarnpkg.com/@sentry/browser/-/browser-5.14.2.tgz#b0d1bf7bd771e64de0f9f801fa6625e47fced016" + integrity sha512-Vuuy2E5mt2VQKeHpFqtowZdKUe1Ui7J2KmgZQCduVilM7dFmprdXfv/mQ3Uv+73VIiCd22PpxojR3peDksb/Gg== dependencies: - "@sentry/core" "5.13.0" - "@sentry/types" "5.12.4" - "@sentry/utils" "5.13.0" + "@sentry/core" "5.14.2" + "@sentry/types" "5.14.2" + "@sentry/utils" "5.14.2" tslib "^1.9.3" -"@sentry/core@5.13.0": - version "5.13.0" - resolved "https://registry.yarnpkg.com/@sentry/core/-/core-5.13.0.tgz#144beb2d48b53244774a7fd809f9b5b672920971" - integrity sha512-e0olbaHBmANO1RIBc7xynSkBZ6BsK7drycz0TawLUnx+0H3aEau3K9U2QVdbjwLNPdydcIS+UgYfTBtXfe0E+A== +"@sentry/core@5.14.2": + version "5.14.2" + resolved "https://registry.yarnpkg.com/@sentry/core/-/core-5.14.2.tgz#950709a2281086c64f1ba60f2c3290dc81c19659" + integrity sha512-B2XjUMCmVu4H3s5hapgynhb28MSc+irt9wRI9j0Lbjx2cxsCUr/YFGL8GuEuYwf4zXNKnh2ke6t+I37OlSaGOg== dependencies: - "@sentry/hub" "5.13.0" - "@sentry/minimal" "5.13.0" - "@sentry/types" "5.12.4" - "@sentry/utils" "5.13.0" + "@sentry/hub" "5.14.2" + "@sentry/minimal" "5.14.2" + "@sentry/types" "5.14.2" + "@sentry/utils" "5.14.2" tslib "^1.9.3" -"@sentry/hub@5.13.0": - version "5.13.0" - resolved "https://registry.yarnpkg.com/@sentry/hub/-/hub-5.13.0.tgz#f48e3e4e273f40316391cd6190e22ea69cb20c7e" - integrity sha512-MeytooJ5g91zxq4/LU1LHj7KxpggAEn1dybEsWG31QVy67J4a40zIGfYgGGIVAFSv0WVlk5Ei5C159LhgW59/w== +"@sentry/hub@5.14.2": + version "5.14.2" + resolved "https://registry.yarnpkg.com/@sentry/hub/-/hub-5.14.2.tgz#24a0990a901d49f8a362dfd404cb7cd33e429d60" + integrity sha512-0ckTDnhCANkuY+VepMPz5vl/dkFQnWmzlJiCIxgM5fCgAF8dfNd9VhGn0qVQXnzKPGoW9zxs/uAmH3/XFqqmNA== dependencies: - "@sentry/types" "5.12.4" - "@sentry/utils" "5.13.0" + "@sentry/types" "5.14.2" + "@sentry/utils" "5.14.2" tslib "^1.9.3" -"@sentry/minimal@5.13.0": - version "5.13.0" - resolved "https://registry.yarnpkg.com/@sentry/minimal/-/minimal-5.13.0.tgz#ee906191e3c2a1f7d0925fbfa0a4e96261013764" - integrity sha512-6D2Mu4TrmJmGlvb+z1Pp6yI2fUmdY1RvwK0MqmBP+QJdrd0as7cpGuwFSXgUs6CLUflDzlpn3n6WcgGV8oEDYA== +"@sentry/minimal@5.14.2": + version "5.14.2" + resolved "https://registry.yarnpkg.com/@sentry/minimal/-/minimal-5.14.2.tgz#9fa39cc6432a05aae22e892a1be3cc314c3b77c4" + integrity sha512-uih9a8KwFCQrWaGb3UxkrSntxMRT4EIlud158ZKlrsLaCOE6i08unOR4xWqlrXlKPySq16H4wjbBFQ56ogOWdQ== dependencies: - "@sentry/hub" "5.13.0" - "@sentry/types" "5.12.4" + "@sentry/hub" "5.14.2" + "@sentry/types" "5.14.2" tslib "^1.9.3" -"@sentry/node@^5.13.1": - version "5.13.1" - resolved "https://registry.yarnpkg.com/@sentry/node/-/node-5.13.1.tgz#41d2eec02bc718a0f5aa59698635242d585470f2" - integrity sha512-6/HaewN2kX0za3LncYwp6nlvm/6i0S0/D/HO7VDHMSpc8z/8/Em6xTZy7hLV3phosMoLIa5P3CRXvLVybBTrpg== +"@sentry/node@^5.14.2": + version "5.14.2" + resolved "https://registry.yarnpkg.com/@sentry/node/-/node-5.14.2.tgz#18c25a0ca34b6ea4e3d917a819e97d086d8b1c2c" + integrity sha512-8s9JAKc/oid6lIFbYLtCLDwLhUpsgeU1WdNbs1eUJQSArb6WHS6EREVBuGr3RMfe+SkwEMg1rtPKnyj4C/WRig== dependencies: - "@sentry/apm" "5.13.1" - "@sentry/core" "5.13.0" - "@sentry/hub" "5.13.0" - "@sentry/types" "5.12.4" - "@sentry/utils" "5.13.0" + "@sentry/apm" "5.14.2" + "@sentry/core" "5.14.2" + "@sentry/hub" "5.14.2" + "@sentry/types" "5.14.2" + "@sentry/utils" "5.14.2" cookie "^0.3.1" https-proxy-agent "^4.0.0" lru_map "^0.3.3" tslib "^1.9.3" -"@sentry/types@5.12.4": - version "5.12.4" - resolved "https://registry.yarnpkg.com/@sentry/types/-/types-5.12.4.tgz#6e52639bc3b4e136e9a0da5385890f8f78bb7697" - integrity sha512-JoN3YIp7Z+uxUZArj2B6NcEoXFQDhd0kqO0QpfiHZyg4Dhx2/E2aHuVx0H6Fndk+60iEZSECaCBXe2MOPo4fqA== +"@sentry/types@5.14.2": + version "5.14.2" + resolved "https://registry.yarnpkg.com/@sentry/types/-/types-5.14.2.tgz#43c3723b2f5b31234892fbe6a28b293ad050faac" + integrity sha512-NtB/o+/whR/mJJf67Nvdab7E2+/THgAUY114FWFqDLHMaoiIVWy9J/yLKtQWymwuQslh7zpPxjA1AhqTJerVCg== -"@sentry/utils@5.13.0": - version "5.13.0" - resolved "https://registry.yarnpkg.com/@sentry/utils/-/utils-5.13.0.tgz#6463e53b6178dbbd3b90e671517cbca82744b055" - integrity sha512-BcmNQN+IfFbVWGnEwXHku69zqJc97sjBRYVxpStKMaO/4aLVIQcOJCMWxVJtVoSVAHQaigBZmFutWH7EJMRJxg== +"@sentry/utils@5.14.2": + version "5.14.2" + resolved "https://registry.yarnpkg.com/@sentry/utils/-/utils-5.14.2.tgz#2e812f2788a00ca4e6e35acbeb86000792f53473" + integrity sha512-DV9/kw/O8o5xqvQYwITm0lBaBqS4RKicjguWYJQ/+F94P/SKxuXor7EE0iMDYvUGslvPz8TlgB7r+nb/YRl+Fg== dependencies: - "@sentry/types" "5.12.4" + "@sentry/types" "5.14.2" tslib "^1.9.3" "@sindresorhus/is@^0.14.0": @@ -1676,9 +1669,9 @@ acorn-walk@^6.0.1: integrity sha512-7evsyfH1cLOCdAzZAd43Cic04yKydNx0cF+7tiA19p1XnLLPU4dpCQOqpjqwokFe//vS0QqfqqjCS2JkiIs0cA== acorn@^6.0.1: - version "6.3.0" - resolved "https://registry.yarnpkg.com/acorn/-/acorn-6.3.0.tgz#0087509119ffa4fc0a0041d1e93a417e68cb856e" - integrity sha512-/czfa8BwS88b9gWQVhc8eknunSA2DoJpJyTQkhheIf5E48u1N0R4q/YxxsAeqRrmK9TQ/uYfgLDfZo91UlANIA== + version "6.4.1" + resolved "https://registry.yarnpkg.com/acorn/-/acorn-6.4.1.tgz#531e58ba3f51b9dacb9a6646ca4debf5b14ca474" + integrity sha512-ZVA9k326Nwrj3Cj9jlh3wGFutC2ZornPNARZwsNYqQYgN0EsV2d53w5RN/co65Ohn4sUAUtb1rSUAOD6XN9idA== acorn@^7.1.0: version "7.1.0" @@ -3127,10 +3120,10 @@ data-urls@^1.1.0: whatwg-mimetype "^2.2.0" whatwg-url "^7.0.0" -date-fns@2.10.0: - version "2.10.0" - resolved "https://registry.yarnpkg.com/date-fns/-/date-fns-2.10.0.tgz#abd10604d8bafb0bcbd2ba2e9b0563b922ae4b6b" - integrity sha512-EhfEKevYGWhWlZbNeplfhIU/+N+x0iCIx7VzKlXma2EdQyznVlZhCptXUY+BegNpPW2kjdx15Rvq503YcXXrcA== +date-fns@2.11.0: + version "2.11.0" + resolved "https://registry.yarnpkg.com/date-fns/-/date-fns-2.11.0.tgz#ec2b44977465b9dcb370021d5e6c019b19f36d06" + integrity sha512-8P1cDi8ebZyDxUyUprBXwidoEtiQAawYPGvpfb+Dg0G6JrQ+VozwOmm91xYC0vAv1+0VmLehEPb+isg4BGUFfA== dateformat@^2.0.0: version "2.2.0" @@ -3664,10 +3657,10 @@ eslint-plugin-import@~2.20.1: read-pkg-up "^2.0.0" resolve "^1.12.0" -eslint-plugin-jest@~23.8.1: - version "23.8.1" - resolved "https://registry.yarnpkg.com/eslint-plugin-jest/-/eslint-plugin-jest-23.8.1.tgz#247025e8a51b3a25a4cc41166369b0bfb4db83b7" - integrity sha512-OycLNqPo/2EfO6kTqnmsu1khz1gTIOxGl3ThIVwL5/oycDF4pm5uNDyvFelNLdpr4COUuM8PVi3963NEG1Efpw== +eslint-plugin-jest@~23.8.2: + version "23.8.2" + resolved "https://registry.yarnpkg.com/eslint-plugin-jest/-/eslint-plugin-jest-23.8.2.tgz#6f28b41c67ef635f803ebd9e168f6b73858eb8d4" + integrity sha512-xwbnvOsotSV27MtAe7s8uGWOori0nUsrXh2f1EnpmXua8sDfY6VZhHAhHg2sqK7HBNycRQExF074XSZ7DvfoFg== dependencies: "@typescript-eslint/experimental-utils" "^2.5.0" @@ -4155,10 +4148,10 @@ flatted@^2.0.0: resolved "https://registry.yarnpkg.com/flatted/-/flatted-2.0.1.tgz#69e57caa8f0eacbc281d2e2cb458d46fdb449e08" integrity sha512-a1hQMktqW9Nmqr5aktAux3JMNqaucxGcjtjWnZLHX7yyPCmlSV3M54nGYbqT8K+0GhF3NBgmJCc3ma+WOgX8Jg== -fn-name@~2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/fn-name/-/fn-name-2.0.1.tgz#5214d7537a4d06a4a301c0cc262feb84188002e7" - integrity sha1-UhTXU3pNBqSjAcDMJi/rhBiAAuc= +fn-name@~3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/fn-name/-/fn-name-3.0.0.tgz#0596707f635929634d791f452309ab41558e3c5c" + integrity sha512-eNMNr5exLoavuAMhIUVsOKF79SWd/zG104ef6sxBTSw+cZc6BXdQXDvYcGvp0VbxVVSp1XDUNoz7mg1xMtSznA== for-in@^1.0.2: version "1.0.2" @@ -4505,14 +4498,14 @@ graphql-redis-subscriptions@^2.2.1: optionalDependencies: ioredis "^4.6.3" -graphql-shield@~7.0.14: - version "7.0.14" - resolved "https://registry.yarnpkg.com/graphql-shield/-/graphql-shield-7.0.14.tgz#3cbbf2722f2e3393fed7f47d866a1324bc3ce76a" - integrity sha512-YVedaL+4pITisSGRqMVeGX8ydOLSTQlHQN6o0Jly7z2cSy1wOzGJIRpfofETJtGLhBnPHHy1otINzuAyjGJO/g== +graphql-shield@~7.2.0: + version "7.2.0" + resolved "https://registry.yarnpkg.com/graphql-shield/-/graphql-shield-7.2.0.tgz#81b26794370608ad78dfe3833473789fb471fbd8" + integrity sha512-eLdD+gUIKYu77XRcuHs5ewZhiBuRFeWFGxPnJa+g9AkxB7Yi5RSEjEJEx0Drg9GuNvDYpHeW7nPff4v35AT2aQ== dependencies: "@types/yup" "0.26.32" object-hash "^2.0.3" - yup "^0.28.1" + yup "^0.28.3" graphql-subscriptions@^1.0.0: version "1.1.0" @@ -6064,7 +6057,7 @@ lodash.isstring@^4.0.1: resolved "https://registry.yarnpkg.com/lodash.isstring/-/lodash.isstring-4.0.1.tgz#d527dfb5456eca7cc9bb95d5daeaf88ba54a5451" integrity sha1-1SfftUVuynzJu5XV2ur4i6VKVFE= -lodash.mergewith@^4.6.1: +lodash.mergewith@^4.6.2: version "4.6.2" resolved "https://registry.yarnpkg.com/lodash.mergewith/-/lodash.mergewith-4.6.2.tgz#617121f89ac55f59047c7aec1ccd6654c6590f55" integrity sha512-GK3g5RPZWTRSeLSpgP8Xhra+pnjBC56q9FZYe1d5RN3TJ35dbkGy3YqBSMbyCrlbi+CM9Z3Jk5yTL7RCsqboyQ== @@ -6223,12 +6216,12 @@ merge2@^1.3.0: resolved "https://registry.yarnpkg.com/merge2/-/merge2-1.3.0.tgz#5b366ee83b2f1582c48f87e47cf1a9352103ca81" integrity sha512-2j4DAdlBOkiSZIsaXk4mTE3sRS02yBHAtfy127xRV3bQUFqXkjHCHLW6Scv7DwNRbIWNHH8zpnz9zMaKXIdvYw== -metascraper-audio@^5.11.1: - version "5.11.1" - resolved "https://registry.yarnpkg.com/metascraper-audio/-/metascraper-audio-5.11.1.tgz#46a45fc8d9c4ccc1c24340d46a8c25dc3685d7b9" - integrity sha512-L5eGfw5cOww4/f3ppMa/k+bix3LdICKcKJ2WVTLgz1QkKTWt5IQrgdW+kRfwUdaUTH6w0Tco+nOO7yUCaWytAQ== +metascraper-audio@^5.11.6: + version "5.11.6" + resolved "https://registry.yarnpkg.com/metascraper-audio/-/metascraper-audio-5.11.6.tgz#392b4b84309ac017bce4b4d0d52948f3a17d7ecc" + integrity sha512-X1nEPP+bgTUStXmWuy/s/h5dix2Smuphx8VdH47/uqXRkifGByQ4nHt9Rd+rg3BNOI15bCib/Nc56awtUOG+3Q== dependencies: - "@metascraper/helpers" "^5.11.1" + "@metascraper/helpers" "^5.11.6" metascraper-author@^5.11.6: version "5.11.6" @@ -6296,13 +6289,13 @@ metascraper-publisher@^5.11.6: dependencies: "@metascraper/helpers" "^5.11.6" -metascraper-soundcloud@^5.11.5: - version "5.11.5" - resolved "https://registry.yarnpkg.com/metascraper-soundcloud/-/metascraper-soundcloud-5.11.5.tgz#989665c8d4177e0b687e12de3d951b79d69704bc" - integrity sha512-SbDtLkp/Uyg+gykNdmF+6Hy15TbNBnBWuVbRk99x+9XDoLbsK98kp1pJm0lU//RlRJAPfeWXPyMjhBMbDbeE/A== +metascraper-soundcloud@^5.11.6: + version "5.11.6" + resolved "https://registry.yarnpkg.com/metascraper-soundcloud/-/metascraper-soundcloud-5.11.6.tgz#01699553a37d5e02f73cd5b15792986f761e94e9" + integrity sha512-KR/KNK5pWthgwuixqyfL13uSwr+mUanzhC6LEYSL7kHYTtYl0mwG7P64Ab+OdloLMwRkekITK6EaD3T8Omj2tw== dependencies: - "@metascraper/helpers" "^5.11.1" - tldts "~5.6.9" + "@metascraper/helpers" "^5.11.6" + tldts "~5.6.10" metascraper-title@^5.11.6: version "5.11.6" @@ -6319,12 +6312,12 @@ metascraper-url@^5.11.6: dependencies: "@metascraper/helpers" "^5.11.6" -metascraper-video@^5.11.1: - version "5.11.1" - resolved "https://registry.yarnpkg.com/metascraper-video/-/metascraper-video-5.11.1.tgz#4018a635d816f3123c7ba97fe7669e4d61af2196" - integrity sha512-g8x6R4ntX7pt7ntuRCzL1+xIRd0JFAp/LoVPYFvdwn/D78u9GMJi+JvrNuLIEcrmtb6re6rE9MIOy8qMo1g3qA== +metascraper-video@^5.11.6: + version "5.11.6" + resolved "https://registry.yarnpkg.com/metascraper-video/-/metascraper-video-5.11.6.tgz#da8a2f81f07891391b1245346750a5450a3ae8c6" + integrity sha512-jxcLqSTvkPku1OMz/x8epDs6mnN3/IgBbcffC2TIzM7yJxcHpzxOGfVcUZ4igwKlz70lk8P8V5gIHMYAFDNdrQ== dependencies: - "@metascraper/helpers" "^5.11.1" + "@metascraper/helpers" "^5.11.6" lodash "~4.17.15" metascraper-youtube@^5.11.6: @@ -6498,10 +6491,10 @@ ms@^2.1.1: resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009" integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w== -mustache@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/mustache/-/mustache-4.0.0.tgz#7f02465dbb5b435859d154831c032acdfbbefb31" - integrity sha512-FJgjyX/IVkbXBXYUwH+OYwQKqWpFPLaLVESd70yHjSDunwzV2hZOoTBvPf4KLoxesUzzyfTH6F784Uqd7Wm5yA== +mustache@^4.0.1: + version "4.0.1" + resolved "https://registry.yarnpkg.com/mustache/-/mustache-4.0.1.tgz#d99beb031701ad433338e7ea65e0489416c854a2" + integrity sha512-yL5VE97+OXn4+Er3THSmTdCFCtx5hHWzrolvH+JObZnUYwuaG7XV+Ch4fR2cIrcYI0tFHxS7iyFYl14bW8y2sA== mute-stream@0.0.8: version "0.0.8" @@ -6572,10 +6565,10 @@ neo4j-driver@^1.7.6: text-encoding-utf-8 "^1.0.2" uri-js "^4.2.2" -neo4j-driver@^4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/neo4j-driver/-/neo4j-driver-4.0.1.tgz#b25ffde0f16602e94c46d097e16a8bacbd773d5a" - integrity sha512-SqBhXyyyayVs5gV/6BrgdKbcmU5AsYQXkFAiYO74XAE8XPLJ1HVR/Hu4wjonAX7+70DsalkWEiFN1c6UaCVzlQ== +neo4j-driver@^4.0.1, neo4j-driver@^4.0.2: + version "4.0.2" + resolved "https://registry.yarnpkg.com/neo4j-driver/-/neo4j-driver-4.0.2.tgz#78de3b91e91572bcbd9d2e02554322fe1ab399ea" + integrity sha512-xQN4BZZsweaNNac7FDYAV6f/JybghwY3lk4fwblS8V5KQ+DBMPe4Pthh672mp+wEYZGyzPalq5CfpcBrWaZ4Gw== dependencies: "@babel/runtime" "^7.5.5" rxjs "^6.5.2" @@ -6692,9 +6685,9 @@ nodemailer-html-to-text@^3.1.0: html-to-text "^5.1.1" nodemailer@^6.4.4: - version "6.4.4" - resolved "https://registry.yarnpkg.com/nodemailer/-/nodemailer-6.4.4.tgz#f4bb26a833786e8908b3ac8afbf2d0382ac24feb" - integrity sha512-2GqGu5o3FBmDibczU3+LZh9lCEiKmNx7LvHl512p8Kj+Kn5FQVOICZv85MDFz/erK0BDd5EJp3nqQLpWCZD1Gg== + version "6.4.5" + resolved "https://registry.yarnpkg.com/nodemailer/-/nodemailer-6.4.5.tgz#45614c6454d1a947242105eeddae03df87e29916" + integrity sha512-NH7aNVQyZLAvGr2+EOto7znvz+qJ02Cb/xpou98ApUt5tEAUSVUxhvHvgV/8I5dhjKTYqUw0nasoKzLNBJKrDQ== nodemon@~2.0.2: version "2.0.2" @@ -7367,10 +7360,10 @@ prop-types@^15.6.2: object-assign "^4.1.1" react-is "^16.8.1" -property-expr@^1.5.0: - version "1.5.1" - resolved "https://registry.yarnpkg.com/property-expr/-/property-expr-1.5.1.tgz#22e8706894a0c8e28d58735804f6ba3a3673314f" - integrity sha512-CGuc0VUTGthpJXL36ydB6jnbyOf/rAHFvmVrJlH+Rg0DqqLFQGAP6hIaxD/G0OAmBJPhXDHuEJigrp0e0wFV6g== +property-expr@^2.0.0: + version "2.0.2" + resolved "https://registry.yarnpkg.com/property-expr/-/property-expr-2.0.2.tgz#fff2a43919135553a3bc2fdd94bdb841965b2330" + integrity sha512-bc/5ggaYZxNkFKj374aLbEDqVADdYaLcFo8XBkishUWbaAdjlphaBFns9TvRA2pUseVL/wMFmui9X3IdNDU37g== proxy-addr@~2.0.5: version "2.0.5" @@ -7896,9 +7889,9 @@ sane@^4.0.3: walker "~1.0.5" sanitize-html@~1.22.0: - version "1.22.0" - resolved "https://registry.yarnpkg.com/sanitize-html/-/sanitize-html-1.22.0.tgz#9df779c53cf5755adb2322943c21c1c1dffca7bf" - integrity sha512-3RPo65mbTKpOAdAYWU496MSty1YbB3Y5bjwL5OclgaSSMtv65xvM7RW/EHRumzaZ1UddEJowCbSdK0xl5sAu0A== + version "1.22.1" + resolved "https://registry.yarnpkg.com/sanitize-html/-/sanitize-html-1.22.1.tgz#5b36c92ab27917ddd2775396815c2bc1a6268310" + integrity sha512-++IMC00KfMQc45UWZJlhWOlS9eMrME38sFG9GXfR+k6oBo9JXSYQgTOZCl9j3v/smFTRNT9XNwz5DseFdMY+2Q== dependencies: chalk "^2.4.1" htmlparser2 "^4.1.0" @@ -7906,7 +7899,7 @@ sanitize-html@~1.22.0: lodash.escaperegexp "^4.1.2" lodash.isplainobject "^4.0.6" lodash.isstring "^4.0.1" - lodash.mergewith "^4.6.1" + lodash.mergewith "^4.6.2" postcss "^7.0.27" srcset "^2.0.1" xtend "^4.0.1" @@ -8548,10 +8541,10 @@ symbol-tree@^3.2.2: resolved "https://registry.yarnpkg.com/symbol-tree/-/symbol-tree-3.2.4.tgz#430637d248ba77e078883951fb9aa0eed7c63fa2" integrity sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw== -synchronous-promise@^2.0.6: - version "2.0.9" - resolved "https://registry.yarnpkg.com/synchronous-promise/-/synchronous-promise-2.0.9.tgz#b83db98e9e7ae826bf9c8261fd8ac859126c780a" - integrity sha512-LO95GIW16x69LuND1nuuwM4pjgFGupg7pZ/4lU86AmchPKrhk0o2tpMU2unXRrqo81iAFe1YJ0nAGEVwsrZAgg== +synchronous-promise@^2.0.10: + version "2.0.10" + resolved "https://registry.yarnpkg.com/synchronous-promise/-/synchronous-promise-2.0.10.tgz#e64c6fd3afd25f423963353043f4a68ebd397fd8" + integrity sha512-6PC+JRGmNjiG3kJ56ZMNWDPL8hjyghF5cMXIFOKg+NiwwEZZIvxTWd0pinWKyD227odg9ygF8xVhhz7gb8Uq7A== table@^5.2.3: version "5.4.6" @@ -8667,17 +8660,17 @@ tlds@^1.187.0, tlds@^1.203.0: resolved "https://registry.yarnpkg.com/tlds/-/tlds-1.203.1.tgz#4dc9b02f53de3315bc98b80665e13de3edfc1dfc" integrity sha512-7MUlYyGJ6rSitEZ3r1Q1QNV8uSIzapS8SmmhSusBuIc7uIxPPwsKllEP0GRp1NS6Ik6F+fRZvnjDWm3ecv2hDw== -tldts-core@^5.6.9: - version "5.6.9" - resolved "https://registry.yarnpkg.com/tldts-core/-/tldts-core-5.6.9.tgz#70e9b1d944b3b93008e0b31ffd8d1de6ce690bc9" - integrity sha512-MOvSUUxUyNmNK7R7cJKBvWys1rufuobWpPaVcGJd8EEsIyJzSVOlA5Y9l9V1Z0FdzlPMBAYPcpKuoQkvH7pfRg== +tldts-core@^5.6.10: + version "5.6.10" + resolved "https://registry.yarnpkg.com/tldts-core/-/tldts-core-5.6.10.tgz#509a93c2bfd79da5a456f06ef099a19fa00bc2c9" + integrity sha512-bbz6I/200adIZgrUcnCD2RiOWkOeyDSuRSyueYN6XFs/Jwoser30nQwEqFaXeKCRsUl4IobnOGWbvUC5ihcxCA== -tldts@~5.6.9: - version "5.6.9" - resolved "https://registry.yarnpkg.com/tldts/-/tldts-5.6.9.tgz#6fb3a10161aae568b1a862e4c96101a79adb557f" - integrity sha512-Dt5c+gD6tC3hvcUZEI/yMvru1gbnFzx95s7Di+GWZUrfEjI6vQg+vthje2Apduv9RHXXPEr5BLA51OsAwPvhWQ== +tldts@~5.6.10: + version "5.6.10" + resolved "https://registry.yarnpkg.com/tldts/-/tldts-5.6.10.tgz#b9a07d7ed14c7a2b7bcf48ac1f6908d5b06d28e1" + integrity sha512-YM/3+cMeulrAqGQE8EhU7Ugmw5PAqTUJJq51XTVzsh0S9VxEwFZRkJSn7B4OY/tgQIMu8GXzPMd9fIoiOxsRYA== dependencies: - tldts-core "^5.6.9" + tldts-core "^5.6.10" tmp@^0.0.33: version "0.0.33" @@ -9385,17 +9378,17 @@ yargs@^15.0.0: y18n "^4.0.0" yargs-parser "^16.1.0" -yup@^0.28.1: - version "0.28.1" - resolved "https://registry.yarnpkg.com/yup/-/yup-0.28.1.tgz#60c0725be7057ed7a9ae61561333809332a63d47" - integrity sha512-xSHMZA7UyecSG/CCTDCtnYZMjBrYDR/C7hu0fMsZ6UcS/ngko4qCVFbw+CAmNtHlbItKkvQ3YXITODeTj/dUkw== +yup@^0.28.3: + version "0.28.3" + resolved "https://registry.yarnpkg.com/yup/-/yup-0.28.3.tgz#1ca607405a8adf24a5ac51f54bd09d527555f0ba" + integrity sha512-amVkCgFWe5bGjrrUiODkbIzrSwtB8JpZrQYSrfj2YsbRdrV+tn9LquWdZDlfOx2HXyfEA8FGnlwidE/bFDxO7Q== dependencies: - "@babel/runtime" "^7.0.0" - fn-name "~2.0.1" - lodash "^4.17.11" + "@babel/runtime" "^7.8.7" + fn-name "~3.0.0" + lodash "^4.17.15" lodash-es "^4.17.11" - property-expr "^1.5.0" - synchronous-promise "^2.0.6" + property-expr "^2.0.0" + synchronous-promise "^2.0.10" toposort "^2.0.2" zen-observable-ts@^0.8.20: diff --git a/cypress/integration/common/post.js b/cypress/integration/common/post.js index d0298c5a3..cba238a63 100644 --- a/cypress/integration/common/post.js +++ b/cypress/integration/common/post.js @@ -3,8 +3,6 @@ import locales from '../../../webapp/locales' import orderBy from 'lodash/orderBy' const languages = orderBy(locales, 'name') -const narratorAvatar = - "https://s3.amazonaws.com/uifaces/faces/twitter/nerrsoft/128.jpg"; When("I type in a comment with {int} characters", size => { var c=""; @@ -32,9 +30,11 @@ Then("my comment should be successfully created", () => { Then("I should see my comment", () => { cy.get("article.comment-card p") .should("contain", "Human Connection rocks") + .get(".user-teaser span.slug") + .should("contain", "@peter-pan") // specific enough .get(".user-avatar img") .should("have.attr", "src") - .and("contain", narratorAvatar) + .and("contain", 'https://') // some url .get(".user-teaser > .info > .text") .should("contain", "today at"); }); diff --git a/cypress/integration/common/steps.js b/cypress/integration/common/steps.js index c02829b25..22a9d016e 100644 --- a/cypress/integration/common/steps.js +++ b/cypress/integration/common/steps.js @@ -24,7 +24,6 @@ const narratorParams = { id: 'id-of-peter-pan', name: "Peter Pan", slug: "peter-pan", - avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/nerrsoft/128.jpg", ...termsAndConditionsAgreedVersion, }; @@ -422,14 +421,13 @@ When("mention {string} in the text", mention => { .click(); }); -Then("the notification gets marked as read", () => { - cy.get(".notifications-menu-popover .notification") - .first() - .should("have.class", "--read"); +Then("the unread counter is removed", () => { + cy.get('.notifications-menu .counter-icon').should('not.exist'); }); -Then("there are no notifications in the top menu", () => { - cy.get(".notifications-menu").should("contain", "0"); +Then("the notification menu button links to the all notifications page", () => { + cy.get(".notifications-menu").click(); + cy.location("pathname").should("contain", "/notifications"); }); Given("there is an annoying user called {string}", name => { diff --git a/cypress/integration/notifications/Mentions.feature b/cypress/integration/notifications/Mentions.feature index 08eddcacd..1cf265624 100644 --- a/cypress/integration/notifications/Mentions.feature +++ b/cypress/integration/notifications/Mentions.feature @@ -24,6 +24,6 @@ Feature: Notification for a mention And see 1 unread notifications in the top menu And open the notification menu and click on the first item Then I get to the post page of ".../hey-matt" - And the notification gets marked as read - But when I refresh the page - Then there are no notifications in the top menu + And the unread counter is removed + And the notification menu button links to the all notifications page + diff --git a/cypress/integration/post/DeleteImage.feature b/cypress/integration/post/DeleteImage.feature index a3fa6f9b6..07bfe43b1 100644 --- a/cypress/integration/post/DeleteImage.feature +++ b/cypress/integration/post/DeleteImage.feature @@ -7,7 +7,7 @@ Feature: Delete Teaser Image Given I have a user account Given I am logged in Given we have the following posts in our database: - | authorId | id | title | content | + | authorId | id | title | content | | id-of-peter-pan | p1 | Post to be updated | successfully updated | Scenario: Delete existing image diff --git a/cypress/integration/search/Search.feature b/cypress/integration/search/Search.feature index e83f58477..b77b45d8e 100644 --- a/cypress/integration/search/Search.feature +++ b/cypress/integration/search/Search.feature @@ -7,7 +7,7 @@ Feature: Search Given I have a user account And we have the following posts in our database: | id | title | content | - | p1 | 101 Essays that will change the way you think | 101 Essays, of course! | + | p1 | 101 Essays that will change the way you think | 101 Essays, of course (PR)! | | p2 | No searched for content | will be found in this post, I guarantee | And we have the following user accounts: | slug | name | id | @@ -24,7 +24,7 @@ Feature: Search | 101 Essays that will change the way you think | Scenario: Press enter starts search - When I type "Es" and press Enter + When I type "PR" and press Enter Then I should have one item in the select dropdown Then I should see the following posts in the select dropdown: | title | diff --git a/package.json b/package.json index 41998245c..363c5f6a2 100644 --- a/package.json +++ b/package.json @@ -32,13 +32,13 @@ "auto-changelog": "^1.16.2", "bcryptjs": "^2.4.3", "codecov": "^3.6.5", - "cross-env": "^6.0.3", + "cross-env": "^7.0.2", "cucumber": "^6.0.5", - "cypress": "^4.1.0", + "cypress": "^4.2.0", "cypress-cucumber-preprocessor": "^2.0.1", "cypress-file-upload": "^3.5.3", "cypress-plugin-retries": "^1.5.2", - "date-fns": "^2.10.0", + "date-fns": "^2.11.0", "dotenv": "^8.2.0", "expect": "^25.1.0", "faker": "Marak/faker.js#master", @@ -46,7 +46,7 @@ "import": "^0.0.6", "jsonwebtoken": "^8.5.1", "mock-socket": "^9.0.3", - "neo4j-driver": "^4.0.1", + "neo4j-driver": "^4.0.2", "neode": "^0.3.7", "npm-run-all": "^4.1.5", "rosie": "^2.0.1", diff --git a/webapp/README.md b/webapp/README.md index 897bb56ca..7a9d578e1 100644 --- a/webapp/README.md +++ b/webapp/README.md @@ -72,7 +72,7 @@ You can then visit the Storybook playground on `http://localhost:3002` After starting the application following the above guidelines, open new terminal windows and navigate to the `/webapp` directory for each of these commands: ```bash -# run eslint in /webapp +# run eslint in /webapp (use option --fix to normalize the files) $ yarn lint ``` @@ -81,6 +81,11 @@ $ yarn lint $ yarn test ``` +```bash +# run locales in /webapp (use option --fix to sort the locales) +$ yarn locales +``` + ```bash # start storybook in /webapp $ yarn storybook diff --git a/webapp/components/Badges.spec.js b/webapp/components/Badges.spec.js index 5273fca21..f81eaafb1 100644 --- a/webapp/components/Badges.spec.js +++ b/webapp/components/Badges.spec.js @@ -2,20 +2,29 @@ import { shallowMount } from '@vue/test-utils' import Badges from './Badges.vue' describe('Badges.vue', () => { - let wrapper + let propsData beforeEach(() => { - wrapper = shallowMount(Badges, {}) + propsData = {} }) - it('renders', () => { - expect(wrapper.is('div')).toBe(true) - }) + describe('shallowMount', () => { + const Wrapper = () => { + return shallowMount(Badges, { propsData }) + } - it('has class "hc-badges"', () => { - expect(wrapper.contains('.hc-badges')).toBe(true) - }) + it('has class "hc-badges"', () => { + expect(Wrapper().contains('.hc-badges')).toBe(true) + }) - // TODO: add similar software tests for other components - // TODO: add more test cases in this file + describe('given a badge', () => { + beforeEach(() => { + propsData.badges = [{ id: '1', icon: '/path/to/some/icon' }] + }) + + it('proxies badge icon, which is just a URL without metadata', () => { + expect(Wrapper().contains('img[src="/api/path/to/some/icon"]')).toBe(true) + }) + }) + }) }) diff --git a/webapp/components/CommentCard/CommentCard.story.js b/webapp/components/CommentCard/CommentCard.story.js index 1749999f3..467a125d5 100644 --- a/webapp/components/CommentCard/CommentCard.story.js +++ b/webapp/components/CommentCard/CommentCard.story.js @@ -17,8 +17,10 @@ const comment = { disabled: false, author: { id: '1', - avatar: - 'https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/db/dbc9e03ebcc384b920c31542af2d27dd8eea9dc2_full.jpg', + avatar: { + url: + 'https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/db/dbc9e03ebcc384b920c31542af2d27dd8eea9dc2_full.jpg', + }, slug: 'jenny-rostock', name: 'Rainer Unsinn', disabled: false, diff --git a/webapp/components/CommentForm/CommentForm.vue b/webapp/components/CommentForm/CommentForm.vue index 422530259..55f675656 100644 --- a/webapp/components/CommentForm/CommentForm.vue +++ b/webapp/components/CommentForm/CommentForm.vue @@ -1,6 +1,6 @@