mirror of
https://github.com/IT4Change/Ocelot-Social.git
synced 2026-01-13 08:24:48 +00:00
Merge remote-tracking branch 'origin/master' into storybook
This commit is contained in:
commit
455eac1031
20
.codecov.yml
20
.codecov.yml
@ -95,7 +95,7 @@ coverage:
|
||||
# - master
|
||||
#flags:
|
||||
# - integration
|
||||
paths:
|
||||
paths:
|
||||
- backend/ # only include coverage in "backend/" folder
|
||||
webapp: # declare a new status context "frontend"
|
||||
against: parent
|
||||
@ -127,7 +127,7 @@ coverage:
|
||||
# - integration
|
||||
# paths:
|
||||
# - folder
|
||||
|
||||
|
||||
#changes:
|
||||
# default:
|
||||
# against: parent
|
||||
@ -150,20 +150,8 @@ coverage:
|
||||
|
||||
#ignore: # files and folders for processing
|
||||
# - tests/*
|
||||
|
||||
|
||||
#fixes:
|
||||
# - "old_path::new_path"
|
||||
|
||||
comment:
|
||||
# layout options are quite limited in v4.x - there have been way more options in v1.0
|
||||
layout: reach, diff, flags, files # mostly old options: header, diff, uncovered, reach, files, tree, changes, sunburst, flags
|
||||
behavior: new # default = posts once then update, posts new if delete
|
||||
# once = post once then updates
|
||||
# new = delete old, post new
|
||||
# spammy = post new
|
||||
require_changes: false # if true: only post the comment if coverage changes
|
||||
require_base: no # [yes :: must have a base report to post]
|
||||
require_head: no # [yes :: must have a head report to post]
|
||||
branches: null # branch names that can post comment
|
||||
flags: null
|
||||
paths: null
|
||||
comment: off
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@ -16,3 +16,4 @@ cypress.env.json
|
||||
|
||||
!.gitkeep
|
||||
**/coverage
|
||||
|
||||
|
||||
10
.travis.yml
10
.travis.yml
@ -11,7 +11,6 @@ addons:
|
||||
before_install:
|
||||
- yarn global add wait-on
|
||||
# Install Codecov
|
||||
- yarn global add codecov
|
||||
- yarn install
|
||||
- cp cypress.env.template.json cypress.env.json
|
||||
|
||||
@ -29,9 +28,10 @@ script:
|
||||
- docker-compose exec backend yarn run test:jest --ci --verbose=false --coverage
|
||||
- docker-compose exec backend yarn run db:reset
|
||||
- docker-compose exec backend yarn run db:seed
|
||||
- docker-compose exec backend yarn run test:cucumber --tags "not @wip"
|
||||
- docker-compose exec backend yarn run db:reset
|
||||
- docker-compose exec backend yarn run db:seed
|
||||
# ActivityPub cucumber testing temporarily disabled because it's too buggy
|
||||
# - docker-compose exec backend yarn run test:cucumber --tags "not @wip"
|
||||
# - docker-compose exec backend yarn run db:reset
|
||||
# - docker-compose exec backend yarn run db:seed
|
||||
# Frontend
|
||||
- docker-compose exec webapp yarn run lint
|
||||
- docker-compose exec webapp yarn run test --ci --verbose=false --coverage
|
||||
@ -39,7 +39,7 @@ script:
|
||||
# Fullstack
|
||||
- yarn run cypress:run
|
||||
# Coverage
|
||||
- codecov
|
||||
- yarn run codecov
|
||||
|
||||
after_success:
|
||||
- wget https://raw.githubusercontent.com/DiscordHooks/travis-ci-discord-webhook/master/send.sh
|
||||
|
||||
@ -4,9 +4,9 @@ Thanks so much for thinking of contributing to the Human Connection project, we
|
||||
|
||||
## Getting Set Up
|
||||
|
||||
Instructions for how to install all the necessary software can be found in our [documentation](https://docs.human-connection.org/human-connection/)
|
||||
Instructions for how to install all the necessary software can be found in our [documentation](https://docs.human-connection.org/human-connection/).
|
||||
|
||||
We recommend that new folks should ideally work together with an existing developer. Please join our discord instance to chat with developers or just ask them in tickets in [Zenhub](https://app.zenhub.com/workspaces/human-connection-nitro-5c0154ecc699f60fc92cf11f/boards?repos=152252353):
|
||||
We recommend that new folks should ideally work together with an existing developer. Please join our [discord](https://discord.gg/6ub73U3) instance to chat with developers or just ask them in tickets in [Zenhub](https://app.zenhub.com/workspaces/human-connection-nitro-5c0154ecc699f60fc92cf11f/boards?repos=152252353):
|
||||
|
||||

|
||||
|
||||
@ -17,7 +17,7 @@ Here are some general notes on our development flow:
|
||||
* Currently operating in two week sprints
|
||||
* We are using ZenHub to coordinate
|
||||
* estimating time per issue is the crucial feature of [Zenhub](https://app.zenhub.com/workspaces/human-connection-nitro-5c0154ecc699f60fc92cf11f) that Github does not have
|
||||
* "up-for-grabs" links to [Github project](https://github.com/orgs/Human-Connection/projects/10?card_filter_query=label%3A"good+first+issue)
|
||||
* "up-for-grabs" links to [Github project](https://github.com/Human-Connection/Human-Connection/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22)
|
||||
* ordering on ZenHub not necessarily reflected on github projects
|
||||
* AgileVentures run open pairing sessions at 10:30am UTC each week on Tuesdays and Thursdays
|
||||
* Core team
|
||||
@ -51,19 +51,19 @@ But what do we do when waiting for merge into master \(wanting to keep PRs small
|
||||
* solutions
|
||||
* 1\) put 2nd PR into branch that the first PR is hitting - but requires update after merging
|
||||
* 2\) prefer to leave exiting PR until it can be reviewed, and instead go and work on some other part of the codebase that is not impacted by the first PR
|
||||
|
||||
|
||||
### Code Review
|
||||
* Github setting in place - at least one review is required to merge
|
||||
* Github setting in place - at least one review is required to merge
|
||||
- in principle anyone (who is not the PR owner) can review
|
||||
- but often it will be the core developers (Robert, Ulf, Greg, Wolfgang?)
|
||||
- once there is a review, and presuming no requested changes, PR opener can merge
|
||||
|
||||
* CI/tests
|
||||
- the CI needs to pass
|
||||
- the CI needs to pass
|
||||
- linting <-- autofix?
|
||||
- tests (unit, feature) (backend, frontend)
|
||||
- codecoverage
|
||||
|
||||
|
||||
## Notes
|
||||
|
||||
question: when you want to pick a task - \(find out priority\) - is it in discord? is it in AV slack? --> Robert says you can always ask in discord - group channels are the best
|
||||
@ -77,4 +77,3 @@ Matt makes point that new stories will have to be taken off the "New Issues" and
|
||||
Robert notes that everyone is invited to join the kickoff meetings
|
||||
|
||||
Robert - difference between "important" \(creates a lot of value\) and "beginner friendly" \(easy to implement\)
|
||||
|
||||
|
||||
@ -46,7 +46,7 @@ Thank you lokalise for providing us with a premium account :raised_hands:.
|
||||
## Developer Chat
|
||||
|
||||
Join our friendly open-source community on [Discord](https://discord.gg/6ub73U3) :heart_eyes_cat:
|
||||
Just introduce yourself at `#user-presentation` and mention `@@Mentor` to get you onboard :neckbeard:
|
||||
Just introduce yourself at `#introduce-yourself` and mention `@@Mentor` to get you onboard :neckbeard:
|
||||
Check out the [contribution guideline](./CONTRIBUTING.md), too!
|
||||
|
||||
|
||||
|
||||
@ -27,6 +27,7 @@
|
||||
* [Kubernetes Dashboard](deployment/digital-ocean/dashboard/README.md)
|
||||
* [HTTPS](deployment/digital-ocean/https/README.md)
|
||||
* [Human Connection](deployment/human-connection/README.md)
|
||||
* [Mailserver](deployment/human-connection/mailserver/README.md)
|
||||
* [Volumes](deployment/volumes/README.md)
|
||||
* [Neo4J Offline-Backups](deployment/volumes/neo4j-offline-backup/README.md)
|
||||
* [Volume Snapshots](deployment/volumes/volume-snapshots/README.md)
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
NEO4J_URI=bolt://localhost:7687
|
||||
NEO4J_USER=neo4j
|
||||
NEO4J_USERNAME=neo4j
|
||||
NEO4J_PASSWORD=letmein
|
||||
GRAPHQL_PORT=4000
|
||||
GRAPHQL_URI=http://localhost:4000
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
FROM node:12.4-alpine as base
|
||||
FROM node:12.6-alpine as base
|
||||
LABEL Description="Backend of the Social Network Human-Connection.org" Vendor="Human Connection gGmbH" Version="0.0.1" Maintainer="Human Connection gGmbH (developer@human-connection.org)"
|
||||
|
||||
EXPOSE 4000
|
||||
|
||||
@ -34,7 +34,6 @@
|
||||
"!**/src/**/?(*.)+(spec|test).js?(x)"
|
||||
],
|
||||
"coverageReporters": [
|
||||
"text",
|
||||
"lcov"
|
||||
],
|
||||
"testMatch": [
|
||||
@ -42,66 +41,68 @@
|
||||
]
|
||||
},
|
||||
"dependencies": {
|
||||
"@hapi/joi": "^15.1.0",
|
||||
"activitystrea.ms": "~2.1.3",
|
||||
"apollo-cache-inmemory": "~1.6.2",
|
||||
"apollo-client": "~2.6.3",
|
||||
"apollo-link-context": "~1.0.18",
|
||||
"apollo-link-http": "~1.5.15",
|
||||
"apollo-server": "~2.6.4",
|
||||
"apollo-server": "~2.7.0",
|
||||
"apollo-server-express": "^2.6.9",
|
||||
"bcryptjs": "~2.4.3",
|
||||
"cheerio": "~1.0.0-rc.3",
|
||||
"cors": "~2.8.5",
|
||||
"cross-env": "~5.2.0",
|
||||
"date-fns": "2.0.0-alpha.35",
|
||||
"date-fns": "2.0.0-beta.1",
|
||||
"debug": "~4.1.1",
|
||||
"dotenv": "~8.0.0",
|
||||
"express": "~4.17.1",
|
||||
"faker": "~4.1.0",
|
||||
"graphql": "~14.3.1",
|
||||
"express": "^4.17.1",
|
||||
"faker": "Marak/faker.js#master",
|
||||
"graphql": "~14.4.2",
|
||||
"graphql-custom-directives": "~0.2.14",
|
||||
"graphql-iso-date": "~3.6.1",
|
||||
"graphql-middleware": "~3.0.2",
|
||||
"graphql-shield": "~5.7.1",
|
||||
"graphql-shield": "~6.0.4",
|
||||
"graphql-tag": "~2.10.1",
|
||||
"graphql-yoga": "~1.18.0",
|
||||
"helmet": "~3.18.0",
|
||||
"helmet": "~3.19.0",
|
||||
"jsonwebtoken": "~8.5.1",
|
||||
"linkifyjs": "~2.1.8",
|
||||
"lodash": "~4.17.11",
|
||||
"lodash": "~4.17.14",
|
||||
"merge-graphql-schemas": "^1.5.8",
|
||||
"neo4j-driver": "~1.7.4",
|
||||
"neo4j-graphql-js": "git+https://github.com/Human-Connection/neo4j-graphql-js.git#temporary_fixes",
|
||||
"neo4j-graphql-js": "^2.6.3",
|
||||
"neode": "^0.2.16",
|
||||
"node-fetch": "~2.6.0",
|
||||
"nodemailer": "^6.2.1",
|
||||
"nodemailer": "^6.3.0",
|
||||
"npm-run-all": "~4.1.5",
|
||||
"request": "~2.88.0",
|
||||
"sanitize-html": "~1.20.1",
|
||||
"slug": "~1.1.0",
|
||||
"trunc-html": "~1.1.2",
|
||||
"uuid": "~3.3.2",
|
||||
"wait-on": "~3.2.0"
|
||||
"wait-on": "~3.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/cli": "~7.4.4",
|
||||
"@babel/core": "~7.4.5",
|
||||
"@babel/node": "~7.4.5",
|
||||
"@babel/cli": "~7.5.0",
|
||||
"@babel/core": "~7.5.4",
|
||||
"@babel/node": "~7.5.5",
|
||||
"@babel/plugin-proposal-throw-expressions": "^7.2.0",
|
||||
"@babel/preset-env": "~7.4.5",
|
||||
"@babel/register": "~7.4.4",
|
||||
"apollo-server-testing": "~2.6.4",
|
||||
"@babel/preset-env": "~7.5.5",
|
||||
"@babel/register": "~7.5.5",
|
||||
"apollo-server-testing": "~2.7.0",
|
||||
"babel-core": "~7.0.0-0",
|
||||
"babel-eslint": "~10.0.2",
|
||||
"babel-jest": "~24.8.0",
|
||||
"chai": "~4.2.0",
|
||||
"cucumber": "~5.1.0",
|
||||
"eslint": "~5.16.0",
|
||||
"eslint-config-prettier": "~5.0.0",
|
||||
"eslint": "~6.0.1",
|
||||
"eslint-config-prettier": "~6.0.0",
|
||||
"eslint-config-standard": "~12.0.0",
|
||||
"eslint-plugin-import": "~2.17.3",
|
||||
"eslint-plugin-jest": "~22.7.0",
|
||||
"eslint-plugin-import": "~2.18.0",
|
||||
"eslint-plugin-jest": "~22.11.1",
|
||||
"eslint-plugin-node": "~9.1.0",
|
||||
"eslint-plugin-prettier": "~3.1.0",
|
||||
"eslint-plugin-promise": "~4.1.1",
|
||||
"eslint-plugin-promise": "~4.2.1",
|
||||
"eslint-plugin-standard": "~4.0.0",
|
||||
"graphql-request": "~1.8.2",
|
||||
"jest": "~24.8.0",
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
import { v1 as neo4j } from 'neo4j-driver'
|
||||
import CONFIG from './../config'
|
||||
import setupNeode from './neode'
|
||||
|
||||
let driver
|
||||
|
||||
@ -14,3 +15,12 @@ export function getDriver(options = {}) {
|
||||
}
|
||||
return driver
|
||||
}
|
||||
|
||||
let neodeInstance
|
||||
export function neode() {
|
||||
if (!neodeInstance) {
|
||||
const { NEO4J_URI: uri, NEO4J_USERNAME: username, NEO4J_PASSWORD: password } = CONFIG
|
||||
neodeInstance = setupNeode({ uri, username, password })
|
||||
}
|
||||
return neodeInstance
|
||||
}
|
||||
|
||||
9
backend/src/bootstrap/neode.js
Normal file
9
backend/src/bootstrap/neode.js
Normal file
@ -0,0 +1,9 @@
|
||||
import Neode from 'neode'
|
||||
import models from '../models'
|
||||
|
||||
export default function setupNeode(options) {
|
||||
const { uri, username, password } = options
|
||||
const neodeInstance = new Neode(uri, username, password)
|
||||
neodeInstance.with(models)
|
||||
return neodeInstance
|
||||
}
|
||||
7
backend/src/helpers/encryptPassword.js
Normal file
7
backend/src/helpers/encryptPassword.js
Normal file
@ -0,0 +1,7 @@
|
||||
import { hashSync } from 'bcryptjs'
|
||||
|
||||
export default function(args) {
|
||||
args.encryptedPassword = hashSync(args.password, 10)
|
||||
delete args.password
|
||||
return args
|
||||
}
|
||||
@ -1,18 +1,8 @@
|
||||
import createServer from './server'
|
||||
import ActivityPub from './activitypub/ActivityPub'
|
||||
import CONFIG from './config'
|
||||
|
||||
const serverConfig = {
|
||||
port: CONFIG.GRAPHQL_PORT,
|
||||
// cors: {
|
||||
// credentials: true,
|
||||
// origin: [CONFIG.CLIENT_URI] // your frontend url.
|
||||
// }
|
||||
}
|
||||
|
||||
const server = createServer()
|
||||
server.start(serverConfig, options => {
|
||||
const { app } = createServer()
|
||||
app.listen({ port: CONFIG.GRAPHQL_PORT }, () => {
|
||||
/* eslint-disable-next-line no-console */
|
||||
console.log(`GraphQLServer ready at ${CONFIG.GRAPHQL_URI} 🚀`)
|
||||
ActivityPub.init(server)
|
||||
})
|
||||
|
||||
@ -4,13 +4,20 @@ import { request } from 'graphql-request'
|
||||
// not to be confused with the seeder host
|
||||
export const host = 'http://127.0.0.1:4123'
|
||||
|
||||
export async function login({ email, password }) {
|
||||
export async function login(variables) {
|
||||
const mutation = `
|
||||
mutation {
|
||||
login(email:"${email}", password:"${password}")
|
||||
}`
|
||||
const response = await request(host, mutation)
|
||||
mutation($email: String!, $password: String!) {
|
||||
login(email: $email, password: $password)
|
||||
}
|
||||
`
|
||||
const response = await request(host, mutation, variables)
|
||||
return {
|
||||
authorization: `Bearer ${response.login}`,
|
||||
}
|
||||
}
|
||||
|
||||
//* This is a fake ES2015 template string, just to benefit of syntax
|
||||
// highlighting of `gql` template strings in certain editors.
|
||||
export function gql(strings) {
|
||||
return strings.join('')
|
||||
}
|
||||
|
||||
@ -46,7 +46,7 @@ export default {
|
||||
}
|
||||
return post
|
||||
},
|
||||
CreateUser: async (resolve, root, args, context, info) => {
|
||||
SignupVerification: async (resolve, root, args, context, info) => {
|
||||
const keys = generateRsaKeyPair()
|
||||
Object.assign(args, keys)
|
||||
args.actorId = `${activityPub.host}/activitypub/users/${args.slug}`
|
||||
|
||||
@ -9,7 +9,6 @@ const setUpdatedAt = (resolve, root, args, context, info) => {
|
||||
|
||||
export default {
|
||||
Mutation: {
|
||||
CreateUser: setCreatedAt,
|
||||
CreatePost: setCreatedAt,
|
||||
CreateComment: setCreatedAt,
|
||||
CreateOrganization: setCreatedAt,
|
||||
|
||||
57
backend/src/middleware/email/emailMiddleware.js
Normal file
57
backend/src/middleware/email/emailMiddleware.js
Normal file
@ -0,0 +1,57 @@
|
||||
import CONFIG from '../../config'
|
||||
import nodemailer from 'nodemailer'
|
||||
import { resetPasswordMail, wrongAccountMail } from './templates/passwordReset'
|
||||
import { signupTemplate } from './templates/signup'
|
||||
|
||||
const transporter = () => {
|
||||
const configs = {
|
||||
host: CONFIG.SMTP_HOST,
|
||||
port: CONFIG.SMTP_PORT,
|
||||
ignoreTLS: CONFIG.SMTP_IGNORE_TLS,
|
||||
secure: false, // true for 465, false for other ports
|
||||
}
|
||||
const { SMTP_USERNAME: user, SMTP_PASSWORD: pass } = CONFIG
|
||||
if (user && pass) {
|
||||
configs.auth = { user, pass }
|
||||
}
|
||||
return nodemailer.createTransport(configs)
|
||||
}
|
||||
|
||||
const returnResponse = async (resolve, root, args, context, resolveInfo) => {
|
||||
const { response } = await resolve(root, args, context, resolveInfo)
|
||||
delete response.nonce
|
||||
return response
|
||||
}
|
||||
|
||||
const sendSignupMail = async (resolve, root, args, context, resolveInfo) => {
|
||||
const { email } = args
|
||||
const { response, nonce } = await resolve(root, args, context, resolveInfo)
|
||||
delete response.nonce
|
||||
await transporter().sendMail(signupTemplate({ email, nonce }))
|
||||
return response
|
||||
}
|
||||
|
||||
export default function({ isEnabled }) {
|
||||
if (!isEnabled)
|
||||
return {
|
||||
Mutation: {
|
||||
requestPasswordReset: returnResponse,
|
||||
Signup: returnResponse,
|
||||
SignupByInvitation: returnResponse,
|
||||
},
|
||||
}
|
||||
|
||||
return {
|
||||
Mutation: {
|
||||
requestPasswordReset: async (resolve, root, args, context, resolveInfo) => {
|
||||
const { email } = args
|
||||
const { response, user, code, name } = await resolve(root, args, context, resolveInfo)
|
||||
const mailTemplate = user ? resetPasswordMail : wrongAccountMail
|
||||
await transporter().sendMail(mailTemplate({ email, code, name }))
|
||||
return response
|
||||
},
|
||||
Signup: sendSignupMail,
|
||||
SignupByInvitation: sendSignupMail,
|
||||
},
|
||||
}
|
||||
}
|
||||
85
backend/src/middleware/email/templates/passwordReset.js
Normal file
85
backend/src/middleware/email/templates/passwordReset.js
Normal file
@ -0,0 +1,85 @@
|
||||
import CONFIG from '../../../config'
|
||||
|
||||
export const from = '"Human Connection" <info@human-connection.org>'
|
||||
|
||||
export const resetPasswordMail = options => {
|
||||
const {
|
||||
name,
|
||||
email,
|
||||
code,
|
||||
subject = 'Use this link to reset your password. The link is only valid for 24 hours.',
|
||||
supportUrl = 'https://human-connection.org/en/contact/',
|
||||
} = options
|
||||
const actionUrl = new URL('/password-reset/change-password', CONFIG.CLIENT_URI)
|
||||
actionUrl.searchParams.set('code', code)
|
||||
actionUrl.searchParams.set('email', email)
|
||||
|
||||
return {
|
||||
to: email,
|
||||
subject,
|
||||
text: `
|
||||
Hi ${name}!
|
||||
|
||||
You recently requested to reset your password for your Human Connection account.
|
||||
Use the link below to reset it. This password reset is only valid for the next
|
||||
24 hours.
|
||||
|
||||
${actionUrl}
|
||||
|
||||
If you did not request a password reset, please ignore this email or contact
|
||||
support if you have questions:
|
||||
|
||||
${supportUrl}
|
||||
|
||||
Thanks,
|
||||
The Human Connection Team
|
||||
|
||||
If you're having trouble with the link above, you can manually copy and
|
||||
paste the following code into your browser window:
|
||||
|
||||
${code}
|
||||
|
||||
Human Connection gemeinnützige GmbH
|
||||
Bahnhofstr. 11
|
||||
73235 Weilheim / Teck
|
||||
Deutschland
|
||||
`,
|
||||
}
|
||||
}
|
||||
|
||||
export const wrongAccountMail = options => {
|
||||
const {
|
||||
email,
|
||||
subject = `We received a request to reset your password with this email address (${email})`,
|
||||
supportUrl = 'https://human-connection.org/en/contact/',
|
||||
} = options
|
||||
const actionUrl = new URL('/password-reset/request', CONFIG.CLIENT_URI)
|
||||
return {
|
||||
to: email,
|
||||
subject,
|
||||
text: `
|
||||
We received a request to reset the password to access Human Connection with your
|
||||
email address, but we were unable to find an account associated with this
|
||||
address.
|
||||
|
||||
If you use Human Connection and were expecting this email, consider trying to
|
||||
request a password reset using the email address associated with your account.
|
||||
Try a different email:
|
||||
|
||||
${actionUrl}
|
||||
|
||||
If you do not use Human Connection or did not request a password reset, please
|
||||
ignore this email. Feel free to contact support if you have further questions:
|
||||
|
||||
${supportUrl}
|
||||
|
||||
Thanks,
|
||||
The Human Connection Team
|
||||
|
||||
Human Connection gemeinnützige GmbH
|
||||
Bahnhofstr. 11
|
||||
73235 Weilheim / Teck
|
||||
Deutschland
|
||||
`,
|
||||
}
|
||||
}
|
||||
43
backend/src/middleware/email/templates/signup.js
Normal file
43
backend/src/middleware/email/templates/signup.js
Normal file
@ -0,0 +1,43 @@
|
||||
import CONFIG from '../../../config'
|
||||
|
||||
export const from = '"Human Connection" <info@human-connection.org>'
|
||||
|
||||
export const signupTemplate = options => {
|
||||
const {
|
||||
email,
|
||||
nonce,
|
||||
subject = 'Signup link',
|
||||
supportUrl = 'https://human-connection.org/en/contact/',
|
||||
} = options
|
||||
const actionUrl = new URL('/registration/create-user-account', CONFIG.CLIENT_URI)
|
||||
actionUrl.searchParams.set('nonce', nonce)
|
||||
actionUrl.searchParams.set('email', email)
|
||||
|
||||
return {
|
||||
to: email,
|
||||
subject,
|
||||
text: `
|
||||
Welcome to Human Connection! Use this link to complete the registration process
|
||||
and create a user account:
|
||||
|
||||
${actionUrl}
|
||||
|
||||
You can also copy+paste this verification code in your browser window:
|
||||
|
||||
${nonce}
|
||||
|
||||
If you did not signed up for Human Connection, please ignore this email or
|
||||
contact support if you have questions:
|
||||
|
||||
${supportUrl}
|
||||
|
||||
Thanks,
|
||||
The Human Connection Team
|
||||
|
||||
Human Connection gemeinnützige GmbH
|
||||
Bahnhofstr. 11
|
||||
73235 Weilheim / Teck
|
||||
Deutschland
|
||||
`,
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,69 @@
|
||||
import extractMentionedUsers from './notifications/extractMentionedUsers'
|
||||
import extractHashtags from './hashtags/extractHashtags'
|
||||
|
||||
const notify = async (postId, idsOfMentionedUsers, context) => {
|
||||
const session = context.driver.session()
|
||||
const createdAt = new Date().toISOString()
|
||||
const cypher = `
|
||||
match(u:User) where u.id in $idsOfMentionedUsers
|
||||
match(p:Post) where p.id = $postId
|
||||
create(n:Notification{id: apoc.create.uuid(), read: false, createdAt: $createdAt})
|
||||
merge (n)-[:NOTIFIED]->(u)
|
||||
merge (p)-[:NOTIFIED]->(n)
|
||||
`
|
||||
await session.run(cypher, {
|
||||
idsOfMentionedUsers,
|
||||
createdAt,
|
||||
postId,
|
||||
})
|
||||
session.close()
|
||||
}
|
||||
|
||||
const updateHashtagsOfPost = async (postId, hashtags, context) => {
|
||||
const session = context.driver.session()
|
||||
// We need two Cypher statements, because the 'MATCH' in the 'cypherDeletePreviousRelations' statement
|
||||
// functions as an 'if'. In case there is no previous relation, the rest of the commands are omitted
|
||||
// and no new Hashtags and relations will be created.
|
||||
const cypherDeletePreviousRelations = `
|
||||
MATCH (p:Post { id: $postId })-[previousRelations:TAGGED]->(t:Tag)
|
||||
DELETE previousRelations
|
||||
RETURN p, t
|
||||
`
|
||||
const cypherCreateNewTagsAndRelations = `
|
||||
MATCH (p:Post { id: $postId})
|
||||
UNWIND $hashtags AS tagName
|
||||
MERGE (t:Tag { id: tagName, name: tagName, disabled: false, deleted: false })
|
||||
MERGE (p)-[:TAGGED]->(t)
|
||||
RETURN p, t
|
||||
`
|
||||
await session.run(cypherDeletePreviousRelations, {
|
||||
postId,
|
||||
})
|
||||
await session.run(cypherCreateNewTagsAndRelations, {
|
||||
postId,
|
||||
hashtags,
|
||||
})
|
||||
session.close()
|
||||
}
|
||||
|
||||
const handleContentData = async (resolve, root, args, context, resolveInfo) => {
|
||||
// extract user ids before xss-middleware removes classes via the following "resolve" call
|
||||
const idsOfMentionedUsers = extractMentionedUsers(args.content)
|
||||
// extract tag (hashtag) ids before xss-middleware removes classes via the following "resolve" call
|
||||
const hashtags = extractHashtags(args.content)
|
||||
|
||||
// removes classes from the content
|
||||
const post = await resolve(root, args, context, resolveInfo)
|
||||
|
||||
await notify(post.id, idsOfMentionedUsers, context)
|
||||
await updateHashtagsOfPost(post.id, hashtags, context)
|
||||
|
||||
return post
|
||||
}
|
||||
|
||||
export default {
|
||||
Mutation: {
|
||||
CreatePost: handleContentData,
|
||||
UpdatePost: handleContentData,
|
||||
},
|
||||
}
|
||||
@ -0,0 +1,285 @@
|
||||
import { GraphQLClient } from 'graphql-request'
|
||||
import { host, login, gql } from '../../jest/helpers'
|
||||
import Factory from '../../seed/factories'
|
||||
|
||||
const factory = Factory()
|
||||
let client
|
||||
|
||||
beforeEach(async () => {
|
||||
await factory.create('User', {
|
||||
id: 'you',
|
||||
name: 'Al Capone',
|
||||
slug: 'al-capone',
|
||||
email: 'test@example.org',
|
||||
password: '1234',
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await factory.cleanDatabase()
|
||||
})
|
||||
|
||||
describe('currentUser { notifications }', () => {
|
||||
const query = gql`
|
||||
query($read: Boolean) {
|
||||
currentUser {
|
||||
notifications(read: $read, orderBy: createdAt_desc) {
|
||||
read
|
||||
post {
|
||||
content
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
describe('authenticated', () => {
|
||||
let headers
|
||||
beforeEach(async () => {
|
||||
headers = await login({
|
||||
email: 'test@example.org',
|
||||
password: '1234',
|
||||
})
|
||||
client = new GraphQLClient(host, {
|
||||
headers,
|
||||
})
|
||||
})
|
||||
|
||||
describe('given another user', () => {
|
||||
let authorClient
|
||||
let authorParams
|
||||
let authorHeaders
|
||||
|
||||
beforeEach(async () => {
|
||||
authorParams = {
|
||||
email: 'author@example.org',
|
||||
password: '1234',
|
||||
id: 'author',
|
||||
}
|
||||
await factory.create('User', authorParams)
|
||||
authorHeaders = await login(authorParams)
|
||||
})
|
||||
|
||||
describe('who mentions me in a post', () => {
|
||||
let post
|
||||
const title = 'Mentioning Al Capone'
|
||||
const content =
|
||||
'Hey <a class="mention" href="/profile/you/al-capone">@al-capone</a> how do you do?'
|
||||
|
||||
beforeEach(async () => {
|
||||
const createPostMutation = gql`
|
||||
mutation($title: String!, $content: String!) {
|
||||
CreatePost(title: $title, content: $content) {
|
||||
id
|
||||
title
|
||||
content
|
||||
}
|
||||
}
|
||||
`
|
||||
authorClient = new GraphQLClient(host, {
|
||||
headers: authorHeaders,
|
||||
})
|
||||
const { CreatePost } = await authorClient.request(createPostMutation, {
|
||||
title,
|
||||
content,
|
||||
})
|
||||
post = CreatePost
|
||||
})
|
||||
|
||||
it('sends you a notification', async () => {
|
||||
const expectedContent =
|
||||
'Hey <a href="/profile/you/al-capone" target="_blank">@al-capone</a> how do you do?'
|
||||
const expected = {
|
||||
currentUser: {
|
||||
notifications: [
|
||||
{
|
||||
read: false,
|
||||
post: {
|
||||
content: expectedContent,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
await expect(
|
||||
client.request(query, {
|
||||
read: false,
|
||||
}),
|
||||
).resolves.toEqual(expected)
|
||||
})
|
||||
|
||||
describe('who mentions me again', () => {
|
||||
beforeEach(async () => {
|
||||
const updatedContent = `${post.content} One more mention to <a href="/profile/you" class="mention">@al-capone</a>`
|
||||
// The response `post.content` contains a link but the XSSmiddleware
|
||||
// should have the `mention` CSS class removed. I discovered this
|
||||
// during development and thought: A feature not a bug! This way we
|
||||
// can encode a re-mentioning of users when you edit your post or
|
||||
// comment.
|
||||
const updatePostMutation = gql`
|
||||
mutation($id: ID!, $title: String!, $content: String!) {
|
||||
UpdatePost(id: $id, content: $content, title: $title) {
|
||||
title
|
||||
content
|
||||
}
|
||||
}
|
||||
`
|
||||
authorClient = new GraphQLClient(host, {
|
||||
headers: authorHeaders,
|
||||
})
|
||||
await authorClient.request(updatePostMutation, {
|
||||
id: post.id,
|
||||
title: post.title,
|
||||
content: updatedContent,
|
||||
})
|
||||
})
|
||||
|
||||
it('creates exactly one more notification', async () => {
|
||||
const expectedContent =
|
||||
'Hey <a href="/profile/you/al-capone" target="_blank">@al-capone</a> how do you do? One more mention to <a href="/profile/you" target="_blank">@al-capone</a>'
|
||||
const expected = {
|
||||
currentUser: {
|
||||
notifications: [
|
||||
{
|
||||
read: false,
|
||||
post: {
|
||||
content: expectedContent,
|
||||
},
|
||||
},
|
||||
{
|
||||
read: false,
|
||||
post: {
|
||||
content: expectedContent,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
await expect(
|
||||
client.request(query, {
|
||||
read: false,
|
||||
}),
|
||||
).resolves.toEqual(expected)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('Hashtags', () => {
|
||||
const postId = 'p135'
|
||||
const postTitle = 'Two Hashtags'
|
||||
const postContent =
|
||||
'<p>Hey Dude, <a class="hashtag" href="/search/hashtag/Democracy">#Democracy</a> should work equal for everybody!? That seems to be the only way to have equal <a class="hashtag" href="/search/hashtag/Liberty">#Liberty</a> for everyone.</p>'
|
||||
const postWithHastagsQuery = gql`
|
||||
query($id: ID) {
|
||||
Post(id: $id) {
|
||||
tags {
|
||||
id
|
||||
name
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
const postWithHastagsVariables = {
|
||||
id: postId,
|
||||
}
|
||||
const createPostMutation = gql`
|
||||
mutation($postId: ID, $postTitle: String!, $postContent: String!) {
|
||||
CreatePost(id: $postId, title: $postTitle, content: $postContent) {
|
||||
id
|
||||
title
|
||||
content
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
describe('authenticated', () => {
|
||||
let headers
|
||||
beforeEach(async () => {
|
||||
headers = await login({
|
||||
email: 'test@example.org',
|
||||
password: '1234',
|
||||
})
|
||||
client = new GraphQLClient(host, {
|
||||
headers,
|
||||
})
|
||||
})
|
||||
|
||||
describe('create a Post with Hashtags', () => {
|
||||
beforeEach(async () => {
|
||||
await client.request(createPostMutation, {
|
||||
postId,
|
||||
postTitle,
|
||||
postContent,
|
||||
})
|
||||
})
|
||||
|
||||
it('both Hashtags are created with the "id" set to thier "name"', async () => {
|
||||
const expected = [
|
||||
{
|
||||
id: 'Democracy',
|
||||
name: 'Democracy',
|
||||
},
|
||||
{
|
||||
id: 'Liberty',
|
||||
name: 'Liberty',
|
||||
},
|
||||
]
|
||||
await expect(
|
||||
client.request(postWithHastagsQuery, postWithHastagsVariables),
|
||||
).resolves.toEqual({
|
||||
Post: [
|
||||
{
|
||||
tags: expect.arrayContaining(expected),
|
||||
},
|
||||
],
|
||||
})
|
||||
})
|
||||
|
||||
describe('afterwards update the Post by removing a Hashtag, leaving a Hashtag and add a Hashtag', () => {
|
||||
// The already existing Hashtag has no class at this point.
|
||||
const updatedPostContent =
|
||||
'<p>Hey Dude, <a class="hashtag" href="/search/hashtag/Elections">#Elections</a> should work equal for everybody!? That seems to be the only way to have equal <a href="/search/hashtag/Liberty">#Liberty</a> for everyone.</p>'
|
||||
const updatePostMutation = gql`
|
||||
mutation($postId: ID!, $postTitle: String!, $updatedPostContent: String!) {
|
||||
UpdatePost(id: $postId, title: $postTitle, content: $updatedPostContent) {
|
||||
id
|
||||
title
|
||||
content
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
it('only one previous Hashtag and the new Hashtag exists', async () => {
|
||||
await client.request(updatePostMutation, {
|
||||
postId,
|
||||
postTitle,
|
||||
updatedPostContent,
|
||||
})
|
||||
|
||||
const expected = [
|
||||
{
|
||||
id: 'Elections',
|
||||
name: 'Elections',
|
||||
},
|
||||
{
|
||||
id: 'Liberty',
|
||||
name: 'Liberty',
|
||||
},
|
||||
]
|
||||
await expect(
|
||||
client.request(postWithHastagsQuery, postWithHastagsVariables),
|
||||
).resolves.toEqual({
|
||||
Post: [
|
||||
{
|
||||
tags: expect.arrayContaining(expected),
|
||||
},
|
||||
],
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
@ -0,0 +1,28 @@
|
||||
import cheerio from 'cheerio'
|
||||
// formats of a Hashtag:
|
||||
// https://en.wikipedia.org/w/index.php?title=Hashtag&oldid=905141980#Style
|
||||
// here:
|
||||
// 0. Search for whole string.
|
||||
// 1. Hashtag has only 'a-z', 'A-Z', and '0-9'.
|
||||
// 2. If it starts with a digit '0-9' than 'a-z', or 'A-Z' has to follow.
|
||||
const ID_REGEX = /^\/search\/hashtag\/(([a-zA-Z]+[a-zA-Z0-9]*)|([0-9]+[a-zA-Z]+[a-zA-Z0-9]*))$/g
|
||||
|
||||
export default function(content) {
|
||||
if (!content) return []
|
||||
const $ = cheerio.load(content)
|
||||
// We can not search for class '.hashtag', because the classes are removed at the 'xss' middleware.
|
||||
// But we have to know, which Hashtags are removed from the content es well, so we search for the 'a' html-tag.
|
||||
const urls = $('a')
|
||||
.map((_, el) => {
|
||||
return $(el).attr('href')
|
||||
})
|
||||
.get()
|
||||
const hashtags = []
|
||||
urls.forEach(url => {
|
||||
let match
|
||||
while ((match = ID_REGEX.exec(url)) != null) {
|
||||
hashtags.push(match[1])
|
||||
}
|
||||
})
|
||||
return hashtags
|
||||
}
|
||||
@ -0,0 +1,57 @@
|
||||
import extractHashtags from './extractHashtags'
|
||||
|
||||
describe('extractHashtags', () => {
|
||||
describe('content undefined', () => {
|
||||
it('returns empty array', () => {
|
||||
expect(extractHashtags()).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('searches through links', () => {
|
||||
it('finds links with and without ".hashtag" class and extracts Hashtag names', () => {
|
||||
const content =
|
||||
'<p><a class="hashtag" href="/search/hashtag/Elections">#Elections</a><a href="/search/hashtag/Democracy">#Democracy</a></p>'
|
||||
expect(extractHashtags(content)).toEqual(['Elections', 'Democracy'])
|
||||
})
|
||||
|
||||
it('ignores mentions', () => {
|
||||
const content =
|
||||
'<p>Something inspirational about <a href="/profile/u2" target="_blank">@bob-der-baumeister</a> and <a href="/profile/u3/jenny-rostock" class="mention" target="_blank">@jenny-rostock</a>.</p>'
|
||||
expect(extractHashtags(content)).toEqual([])
|
||||
})
|
||||
|
||||
describe('handles links', () => {
|
||||
it('ignores links with domains', () => {
|
||||
const content =
|
||||
'<p><a class="hashtag" href="http://localhost:3000/search/hashtag/Elections">#Elections</a><a href="/search/hashtag/Democracy">#Democracy</a></p>'
|
||||
expect(extractHashtags(content)).toEqual(['Democracy'])
|
||||
})
|
||||
|
||||
it('ignores Hashtag links with not allowed character combinations', () => {
|
||||
const content =
|
||||
'<p>Something inspirational about <a href="/search/hashtag/AbcDefXyz0123456789!*(),2" class="hashtag" target="_blank">#AbcDefXyz0123456789!*(),2</a>, <a href="/search/hashtag/0123456789" class="hashtag" target="_blank">#0123456789</a>, <a href="/search/hashtag/0123456789a" class="hashtag" target="_blank">#0123456789a</a> and <a href="/search/hashtag/AbcDefXyz0123456789" target="_blank">#AbcDefXyz0123456789</a>.</p>'
|
||||
expect(extractHashtags(content)).toEqual(['0123456789a', 'AbcDefXyz0123456789'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('does not crash if', () => {
|
||||
it('`href` contains no Hashtag name', () => {
|
||||
const content =
|
||||
'<p>Something inspirational about <a href="/search/hashtag/" target="_blank">#Democracy</a> and <a href="/search/hashtag" target="_blank">#liberty</a>.</p>'
|
||||
expect(extractHashtags(content)).toEqual([])
|
||||
})
|
||||
|
||||
it('`href` contains Hashtag as page anchor', () => {
|
||||
const content =
|
||||
'<p>Something inspirational about <a href="https://www.example.org/#anchor" target="_blank">#anchor</a>.</p>'
|
||||
expect(extractHashtags(content)).toEqual([])
|
||||
})
|
||||
|
||||
it('`href` is empty or invalid', () => {
|
||||
const content =
|
||||
'<p>Something inspirational about <a href="" class="hashtag" target="_blank">@bob-der-baumeister</a> and <a href="not-a-url" target="_blank">@jenny-rostock</a>.</p>'
|
||||
expect(extractHashtags(content)).toEqual([])
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
@ -1,9 +1,9 @@
|
||||
import extractIds from '.'
|
||||
import extractMentionedUsers from './extractMentionedUsers'
|
||||
|
||||
describe('extractIds', () => {
|
||||
describe('extractMentionedUsers', () => {
|
||||
describe('content undefined', () => {
|
||||
it('returns empty array', () => {
|
||||
expect(extractIds()).toEqual([])
|
||||
expect(extractMentionedUsers()).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
@ -11,33 +11,33 @@ describe('extractIds', () => {
|
||||
it('ignores links without .mention class', () => {
|
||||
const content =
|
||||
'<p>Something inspirational about <a href="/profile/u2" target="_blank">@bob-der-baumeister</a> and <a href="/profile/u3" target="_blank">@jenny-rostock</a>.</p>'
|
||||
expect(extractIds(content)).toEqual([])
|
||||
expect(extractMentionedUsers(content)).toEqual([])
|
||||
})
|
||||
|
||||
describe('given a link with .mention class', () => {
|
||||
it('extracts ids', () => {
|
||||
const content =
|
||||
'<p>Something inspirational about <a href="/profile/u2" class="mention" target="_blank">@bob-der-baumeister</a> and <a href="/profile/u3/jenny-rostock" class="mention" target="_blank">@jenny-rostock</a>.</p>'
|
||||
expect(extractIds(content)).toEqual(['u2', 'u3'])
|
||||
expect(extractMentionedUsers(content)).toEqual(['u2', 'u3'])
|
||||
})
|
||||
|
||||
describe('handles links', () => {
|
||||
it('with slug and id', () => {
|
||||
const content =
|
||||
'<p>Something inspirational about <a href="/profile/u2/bob-der-baumeister" class="mention" target="_blank">@bob-der-baumeister</a> and <a href="/profile/u3/jenny-rostock/" class="mention" target="_blank">@jenny-rostock</a>.</p>'
|
||||
expect(extractIds(content)).toEqual(['u2', 'u3'])
|
||||
expect(extractMentionedUsers(content)).toEqual(['u2', 'u3'])
|
||||
})
|
||||
|
||||
it('with domains', () => {
|
||||
const content =
|
||||
'<p>Something inspirational about <a href="http://localhost:3000/profile/u2/bob-der-baumeister" class="mention" target="_blank">@bob-der-baumeister</a> and <a href="http://localhost:3000//profile/u3/jenny-rostock/" class="mention" target="_blank">@jenny-rostock</a>.</p>'
|
||||
expect(extractIds(content)).toEqual(['u2', 'u3'])
|
||||
expect(extractMentionedUsers(content)).toEqual(['u2', 'u3'])
|
||||
})
|
||||
|
||||
it('special characters', () => {
|
||||
const content =
|
||||
'<p>Something inspirational about <a href="http://localhost:3000/profile/u!*(),2/bob-der-baumeister" class="mention" target="_blank">@bob-der-baumeister</a> and <a href="http://localhost:3000//profile/u.~-3/jenny-rostock/" class="mention" target="_blank">@jenny-rostock</a>.</p>'
|
||||
expect(extractIds(content)).toEqual(['u!*(),2', 'u.~-3'])
|
||||
expect(extractMentionedUsers(content)).toEqual(['u!*(),2', 'u.~-3'])
|
||||
})
|
||||
})
|
||||
|
||||
@ -45,13 +45,13 @@ describe('extractIds', () => {
|
||||
it('`href` contains no user id', () => {
|
||||
const content =
|
||||
'<p>Something inspirational about <a href="/profile" class="mention" target="_blank">@bob-der-baumeister</a> and <a href="/profile/" class="mention" target="_blank">@jenny-rostock</a>.</p>'
|
||||
expect(extractIds(content)).toEqual([])
|
||||
expect(extractMentionedUsers(content)).toEqual([])
|
||||
})
|
||||
|
||||
it('`href` is empty or invalid', () => {
|
||||
const content =
|
||||
'<p>Something inspirational about <a href="" class="mention" target="_blank">@bob-der-baumeister</a> and <a href="not-a-url" class="mention" target="_blank">@jenny-rostock</a>.</p>'
|
||||
expect(extractIds(content)).toEqual([])
|
||||
expect(extractMentionedUsers(content)).toEqual([])
|
||||
})
|
||||
})
|
||||
})
|
||||
@ -1,6 +1,7 @@
|
||||
import { applyMiddleware } from 'graphql-middleware'
|
||||
import CONFIG from './../config'
|
||||
|
||||
import activityPub from './activityPubMiddleware'
|
||||
import password from './passwordMiddleware'
|
||||
import softDelete from './softDeleteMiddleware'
|
||||
import sluggify from './sluggifyMiddleware'
|
||||
import excerpt from './excerptMiddleware'
|
||||
@ -10,35 +11,36 @@ import permissions from './permissionsMiddleware'
|
||||
import user from './userMiddleware'
|
||||
import includedFields from './includedFieldsMiddleware'
|
||||
import orderBy from './orderByMiddleware'
|
||||
import validation from './validation'
|
||||
import notifications from './notifications'
|
||||
import validation from './validation/validationMiddleware'
|
||||
import handleContentData from './handleHtmlContent/handleContentData'
|
||||
import email from './email/emailMiddleware'
|
||||
|
||||
export default schema => {
|
||||
const middlewares = {
|
||||
permissions: permissions,
|
||||
activityPub: activityPub,
|
||||
password: password,
|
||||
dateTime: dateTime,
|
||||
validation: validation,
|
||||
sluggify: sluggify,
|
||||
excerpt: excerpt,
|
||||
notifications: notifications,
|
||||
handleContentData: handleContentData,
|
||||
xss: xss,
|
||||
softDelete: softDelete,
|
||||
user: user,
|
||||
includedFields: includedFields,
|
||||
orderBy: orderBy,
|
||||
email: email({ isEnabled: CONFIG.SMTP_HOST && CONFIG.SMTP_PORT }),
|
||||
}
|
||||
|
||||
let order = [
|
||||
'permissions',
|
||||
'activityPub',
|
||||
'password',
|
||||
// 'activityPub', disabled temporarily
|
||||
'dateTime',
|
||||
'validation',
|
||||
'sluggify',
|
||||
'excerpt',
|
||||
'notifications',
|
||||
'email',
|
||||
'handleContentData',
|
||||
'xss',
|
||||
'softDelete',
|
||||
'user',
|
||||
@ -56,5 +58,6 @@ export default schema => {
|
||||
console.log(`Warning: "${disabledMiddlewares}" middlewares have been disabled.`)
|
||||
}
|
||||
|
||||
return order.map(key => middlewares[key])
|
||||
const appliedMiddlewares = order.map(key => middlewares[key])
|
||||
return applyMiddleware(schema, ...appliedMiddlewares)
|
||||
}
|
||||
|
||||
@ -87,6 +87,9 @@ const createOrUpdateLocations = async (userId, locationName, driver) => {
|
||||
}
|
||||
|
||||
const session = driver.session()
|
||||
if (data.place_type.length > 1) {
|
||||
data.id = 'region.' + data.id.split('.')[1]
|
||||
}
|
||||
await createLocation(session, data)
|
||||
|
||||
let parent = data
|
||||
|
||||
@ -1,30 +0,0 @@
|
||||
import extractIds from './extractIds'
|
||||
|
||||
const notify = async (resolve, root, args, context, resolveInfo) => {
|
||||
// extract user ids before xss-middleware removes link classes
|
||||
const ids = extractIds(args.content)
|
||||
|
||||
const post = await resolve(root, args, context, resolveInfo)
|
||||
|
||||
const session = context.driver.session()
|
||||
const { id: postId } = post
|
||||
const createdAt = new Date().toISOString()
|
||||
const cypher = `
|
||||
match(u:User) where u.id in $ids
|
||||
match(p:Post) where p.id = $postId
|
||||
create(n:Notification{id: apoc.create.uuid(), read: false, createdAt: $createdAt})
|
||||
merge (n)-[:NOTIFIED]->(u)
|
||||
merge (p)-[:NOTIFIED]->(n)
|
||||
`
|
||||
await session.run(cypher, { ids, createdAt, postId })
|
||||
session.close()
|
||||
|
||||
return post
|
||||
}
|
||||
|
||||
export default {
|
||||
Mutation: {
|
||||
CreatePost: notify,
|
||||
UpdatePost: notify,
|
||||
},
|
||||
}
|
||||
@ -1,125 +0,0 @@
|
||||
import { GraphQLClient } from 'graphql-request'
|
||||
import { host, login } from '../../jest/helpers'
|
||||
import Factory from '../../seed/factories'
|
||||
|
||||
const factory = Factory()
|
||||
let client
|
||||
|
||||
beforeEach(async () => {
|
||||
await factory.create('User', {
|
||||
id: 'you',
|
||||
name: 'Al Capone',
|
||||
slug: 'al-capone',
|
||||
email: 'test@example.org',
|
||||
password: '1234',
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await factory.cleanDatabase()
|
||||
})
|
||||
|
||||
describe('currentUser { notifications }', () => {
|
||||
const query = `query($read: Boolean) {
|
||||
currentUser {
|
||||
notifications(read: $read, orderBy: createdAt_desc) {
|
||||
read
|
||||
post {
|
||||
content
|
||||
}
|
||||
}
|
||||
}
|
||||
}`
|
||||
|
||||
describe('authenticated', () => {
|
||||
let headers
|
||||
beforeEach(async () => {
|
||||
headers = await login({ email: 'test@example.org', password: '1234' })
|
||||
client = new GraphQLClient(host, { headers })
|
||||
})
|
||||
|
||||
describe('given another user', () => {
|
||||
let authorClient
|
||||
let authorParams
|
||||
let authorHeaders
|
||||
|
||||
beforeEach(async () => {
|
||||
authorParams = {
|
||||
email: 'author@example.org',
|
||||
password: '1234',
|
||||
id: 'author',
|
||||
}
|
||||
await factory.create('User', authorParams)
|
||||
authorHeaders = await login(authorParams)
|
||||
})
|
||||
|
||||
describe('who mentions me in a post', () => {
|
||||
let post
|
||||
const title = 'Mentioning Al Capone'
|
||||
const content =
|
||||
'Hey <a class="mention" href="/profile/you/al-capone">@al-capone</a> how do you do?'
|
||||
|
||||
beforeEach(async () => {
|
||||
const createPostMutation = `
|
||||
mutation($title: String!, $content: String!) {
|
||||
CreatePost(title: $title, content: $content) {
|
||||
id
|
||||
title
|
||||
content
|
||||
}
|
||||
}
|
||||
`
|
||||
authorClient = new GraphQLClient(host, { headers: authorHeaders })
|
||||
const { CreatePost } = await authorClient.request(createPostMutation, { title, content })
|
||||
post = CreatePost
|
||||
})
|
||||
|
||||
it('sends you a notification', async () => {
|
||||
const expectedContent =
|
||||
'Hey <a href="/profile/you/al-capone" target="_blank">@al-capone</a> how do you do?'
|
||||
const expected = {
|
||||
currentUser: {
|
||||
notifications: [{ read: false, post: { content: expectedContent } }],
|
||||
},
|
||||
}
|
||||
await expect(client.request(query, { read: false })).resolves.toEqual(expected)
|
||||
})
|
||||
|
||||
describe('who mentions me again', () => {
|
||||
beforeEach(async () => {
|
||||
const updatedContent = `${post.content} One more mention to <a href="/profile/you" class="mention">@al-capone</a>`
|
||||
// The response `post.content` contains a link but the XSSmiddleware
|
||||
// should have the `mention` CSS class removed. I discovered this
|
||||
// during development and thought: A feature not a bug! This way we
|
||||
// can encode a re-mentioning of users when you edit your post or
|
||||
// comment.
|
||||
const createPostMutation = `
|
||||
mutation($id: ID!, $content: String!) {
|
||||
UpdatePost(id: $id, content: $content) {
|
||||
title
|
||||
content
|
||||
}
|
||||
}
|
||||
`
|
||||
authorClient = new GraphQLClient(host, { headers: authorHeaders })
|
||||
await authorClient.request(createPostMutation, { id: post.id, content: updatedContent })
|
||||
})
|
||||
|
||||
it('creates exactly one more notification', async () => {
|
||||
const expectedContent =
|
||||
'Hey <a href="/profile/you/al-capone" target="_blank">@al-capone</a> how do you do? One more mention to <a href="/profile/you" target="_blank">@al-capone</a>'
|
||||
const expected = {
|
||||
currentUser: {
|
||||
notifications: [
|
||||
{ read: false, post: { content: expectedContent } },
|
||||
{ read: false, post: { content: expectedContent } },
|
||||
],
|
||||
},
|
||||
}
|
||||
await expect(client.request(query, { read: false })).resolves.toEqual(expected)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
@ -1,21 +0,0 @@
|
||||
import bcrypt from 'bcryptjs'
|
||||
import walkRecursive from '../helpers/walkRecursive'
|
||||
|
||||
export default {
|
||||
Mutation: {
|
||||
CreateUser: async (resolve, root, args, context, info) => {
|
||||
args.password = await bcrypt.hashSync(args.password, 10)
|
||||
const result = await resolve(root, args, context, info)
|
||||
result.password = '*****'
|
||||
return result
|
||||
},
|
||||
},
|
||||
Query: async (resolve, root, args, context, info) => {
|
||||
let result = await resolve(root, args, context, info)
|
||||
result = walkRecursive(result, ['password', 'privateKey'], () => {
|
||||
// replace password with asterisk
|
||||
return '*****'
|
||||
})
|
||||
return result
|
||||
},
|
||||
}
|
||||
@ -1,10 +1,12 @@
|
||||
import { rule, shield, deny, allow, or } from 'graphql-shield'
|
||||
import { rule, shield, deny, allow, and, or, not } from 'graphql-shield'
|
||||
|
||||
/*
|
||||
* TODO: implement
|
||||
* See: https://github.com/Human-Connection/Nitro-Backend/pull/40#pullrequestreview-180898363
|
||||
*/
|
||||
const isAuthenticated = rule()(async (parent, args, ctx, info) => {
|
||||
const isAuthenticated = rule({
|
||||
cache: 'contextual',
|
||||
})(async (_parent, _args, ctx, _info) => {
|
||||
return ctx.user !== null
|
||||
})
|
||||
|
||||
@ -68,6 +70,29 @@ const onlyEnabledContent = rule({
|
||||
return !(disabled || deleted)
|
||||
})
|
||||
|
||||
const invitationLimitReached = rule({
|
||||
cache: 'no_cache',
|
||||
})(async (parent, args, { user, driver }) => {
|
||||
const session = driver.session()
|
||||
try {
|
||||
const result = await session.run(
|
||||
`
|
||||
MATCH (user:User {id:$id})-[:GENERATED]->(i:InvitationCode)
|
||||
RETURN COUNT(i) >= 3 as limitReached
|
||||
`,
|
||||
{ id: user.id },
|
||||
)
|
||||
const [limitReached] = result.records.map(record => {
|
||||
return record.get('limitReached')
|
||||
})
|
||||
return limitReached
|
||||
} catch (e) {
|
||||
throw e
|
||||
} finally {
|
||||
session.close()
|
||||
}
|
||||
})
|
||||
|
||||
const isAuthor = rule({
|
||||
cache: 'no_cache',
|
||||
})(async (parent, args, { user, driver }) => {
|
||||
@ -99,37 +124,43 @@ const isDeletingOwnAccount = rule({
|
||||
return context.user.id === args.id
|
||||
})
|
||||
|
||||
const noEmailFilter = rule({
|
||||
cache: 'no_cache',
|
||||
})(async (_, args) => {
|
||||
return !('email' in args)
|
||||
})
|
||||
|
||||
// Permissions
|
||||
const permissions = shield(
|
||||
{
|
||||
Query: {
|
||||
'*': deny,
|
||||
findPosts: allow,
|
||||
Category: isAdmin,
|
||||
Tag: isAdmin,
|
||||
Category: allow,
|
||||
Tag: allow,
|
||||
Report: isModerator,
|
||||
Notification: isAdmin,
|
||||
statistics: allow,
|
||||
currentUser: allow,
|
||||
Post: or(onlyEnabledContent, isModerator),
|
||||
Comment: allow,
|
||||
User: allow,
|
||||
User: or(noEmailFilter, isAdmin),
|
||||
isLoggedIn: allow,
|
||||
Badge: allow,
|
||||
},
|
||||
Mutation: {
|
||||
'*': deny,
|
||||
login: allow,
|
||||
SignupByInvitation: allow,
|
||||
Signup: isAdmin,
|
||||
SignupVerification: allow,
|
||||
CreateInvitationCode: and(isAuthenticated, or(not(invitationLimitReached), isAdmin)),
|
||||
UpdateNotification: belongsToMe,
|
||||
CreateUser: isAdmin,
|
||||
UpdateUser: onlyYourself,
|
||||
CreatePost: isAuthenticated,
|
||||
UpdatePost: isAuthor,
|
||||
DeletePost: isAuthor,
|
||||
report: isAuthenticated,
|
||||
CreateBadge: isAdmin,
|
||||
UpdateBadge: isAdmin,
|
||||
DeleteBadge: isAdmin,
|
||||
AddUserBadges: isAdmin,
|
||||
CreateSocialMedia: isAuthenticated,
|
||||
DeleteSocialMedia: isAuthenticated,
|
||||
// AddBadgeRewarded: isAdmin,
|
||||
@ -145,6 +176,7 @@ const permissions = shield(
|
||||
enable: isModerator,
|
||||
disable: isModerator,
|
||||
CreateComment: isAuthenticated,
|
||||
UpdateComment: isAuthor,
|
||||
DeleteComment: isAuthor,
|
||||
DeleteUser: isDeletingOwnAccount,
|
||||
requestPasswordReset: allow,
|
||||
@ -152,8 +184,6 @@ const permissions = shield(
|
||||
},
|
||||
User: {
|
||||
email: isMyOwn,
|
||||
password: isMyOwn,
|
||||
privateKey: isMyOwn,
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@ -13,12 +13,16 @@ const isUniqueFor = (context, type) => {
|
||||
|
||||
export default {
|
||||
Mutation: {
|
||||
SignupVerification: async (resolve, root, args, context, info) => {
|
||||
args.slug = args.slug || (await uniqueSlug(args.name, isUniqueFor(context, 'User')))
|
||||
return resolve(root, args, context, info)
|
||||
},
|
||||
CreatePost: async (resolve, root, args, context, info) => {
|
||||
args.slug = args.slug || (await uniqueSlug(args.title, isUniqueFor(context, 'Post')))
|
||||
return resolve(root, args, context, info)
|
||||
},
|
||||
CreateUser: async (resolve, root, args, context, info) => {
|
||||
args.slug = args.slug || (await uniqueSlug(args.name, isUniqueFor(context, 'User')))
|
||||
UpdatePost: async (resolve, root, args, context, info) => {
|
||||
args.slug = args.slug || (await uniqueSlug(args.title, isUniqueFor(context, 'Post')))
|
||||
return resolve(root, args, context, info)
|
||||
},
|
||||
CreateOrganization: async (resolve, root, args, context, info) => {
|
||||
|
||||
@ -1,10 +1,12 @@
|
||||
import { GraphQLClient } from 'graphql-request'
|
||||
import Factory from '../seed/factories'
|
||||
import { host, login } from '../jest/helpers'
|
||||
import { neode } from '../bootstrap/neo4j'
|
||||
|
||||
let authenticatedClient
|
||||
let headers
|
||||
const factory = Factory()
|
||||
const instance = neode()
|
||||
|
||||
beforeEach(async () => {
|
||||
const adminParams = { role: 'admin', email: 'admin@example.org', password: '1234' }
|
||||
@ -76,33 +78,41 @@ describe('slugify', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('CreateUser', () => {
|
||||
const action = async (mutation, params) => {
|
||||
return authenticatedClient.request(`mutation {
|
||||
${mutation}(password: "yo", email: "123@123.de", ${params}) { slug }
|
||||
}`)
|
||||
describe('SignupVerification', () => {
|
||||
const mutation = `mutation($password: String!, $email: String!, $name: String!, $slug: String, $nonce: String!) {
|
||||
SignupVerification(email: $email, password: $password, name: $name, slug: $slug, nonce: $nonce) { slug }
|
||||
}
|
||||
`
|
||||
|
||||
const action = async variables => {
|
||||
// required for SignupVerification
|
||||
await instance.create('EmailAddress', { email: '123@example.org', nonce: '123456' })
|
||||
|
||||
const defaultVariables = { nonce: '123456', password: 'yo', email: '123@example.org' }
|
||||
return authenticatedClient.request(mutation, { ...defaultVariables, ...variables })
|
||||
}
|
||||
|
||||
it('generates a slug based on name', async () => {
|
||||
await expect(action('CreateUser', 'name: "I am a user"')).resolves.toEqual({
|
||||
CreateUser: { slug: 'i-am-a-user' },
|
||||
await expect(action({ name: 'I am a user' })).resolves.toEqual({
|
||||
SignupVerification: { slug: 'i-am-a-user' },
|
||||
})
|
||||
})
|
||||
|
||||
describe('if slug exists', () => {
|
||||
beforeEach(async () => {
|
||||
await action('CreateUser', 'name: "Pre-existing user", slug: "pre-existing-user"')
|
||||
await factory.create('User', { name: 'pre-existing user', slug: 'pre-existing-user' })
|
||||
})
|
||||
|
||||
it('chooses another slug', async () => {
|
||||
await expect(action('CreateUser', 'name: "pre-existing-user"')).resolves.toEqual({
|
||||
CreateUser: { slug: 'pre-existing-user-1' },
|
||||
await expect(action({ name: 'pre-existing-user' })).resolves.toEqual({
|
||||
SignupVerification: { slug: 'pre-existing-user-1' },
|
||||
})
|
||||
})
|
||||
|
||||
describe('but if the client specifies a slug', () => {
|
||||
it('rejects CreateUser', async () => {
|
||||
it('rejects SignupVerification', async () => {
|
||||
await expect(
|
||||
action('CreateUser', 'name: "Pre-existing user", slug: "pre-existing-user"'),
|
||||
action({ name: 'Pre-existing user', slug: 'pre-existing-user' }),
|
||||
).rejects.toThrow('already exists')
|
||||
})
|
||||
})
|
||||
|
||||
@ -2,7 +2,7 @@ import createOrUpdateLocations from './nodes/locations'
|
||||
|
||||
export default {
|
||||
Mutation: {
|
||||
CreateUser: async (resolve, root, args, context, info) => {
|
||||
SignupVerification: async (resolve, root, args, context, info) => {
|
||||
const result = await resolve(root, args, context, info)
|
||||
await createOrUpdateLocations(args.id, args.locationName, context.driver)
|
||||
return result
|
||||
|
||||
@ -1,31 +0,0 @@
|
||||
import { UserInputError } from 'apollo-server'
|
||||
|
||||
const USERNAME_MIN_LENGTH = 3
|
||||
|
||||
const validateUsername = async (resolve, root, args, context, info) => {
|
||||
if (!('name' in args) || (args.name && args.name.length >= USERNAME_MIN_LENGTH)) {
|
||||
/* eslint-disable-next-line no-return-await */
|
||||
return await resolve(root, args, context, info)
|
||||
} else {
|
||||
throw new UserInputError(`Username must be at least ${USERNAME_MIN_LENGTH} characters long!`)
|
||||
}
|
||||
}
|
||||
|
||||
const validateUrl = async (resolve, root, args, context, info) => {
|
||||
const { url } = args
|
||||
const isValid = url.match(/^(?:https?:\/\/)(?:[^@\n])?(?:www\.)?([^:/\n?]+)/g)
|
||||
if (isValid) {
|
||||
/* eslint-disable-next-line no-return-await */
|
||||
return await resolve(root, args, context, info)
|
||||
} else {
|
||||
throw new UserInputError('Input is not a URL')
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
Mutation: {
|
||||
CreateUser: validateUsername,
|
||||
UpdateUser: validateUsername,
|
||||
CreateSocialMedia: validateUrl,
|
||||
},
|
||||
}
|
||||
64
backend/src/middleware/validation/validationMiddleware.js
Normal file
64
backend/src/middleware/validation/validationMiddleware.js
Normal file
@ -0,0 +1,64 @@
|
||||
import { UserInputError } from 'apollo-server'
|
||||
import Joi from '@hapi/joi'
|
||||
|
||||
const COMMENT_MIN_LENGTH = 1
|
||||
const NO_POST_ERR_MESSAGE = 'Comment cannot be created without a post!'
|
||||
|
||||
const validate = schema => {
|
||||
return async (resolve, root, args, context, info) => {
|
||||
const validation = schema.validate(args)
|
||||
if (validation.error) throw new UserInputError(validation.error)
|
||||
return resolve(root, args, context, info)
|
||||
}
|
||||
}
|
||||
|
||||
const socialMediaSchema = Joi.object().keys({
|
||||
url: Joi.string()
|
||||
.uri()
|
||||
.required(),
|
||||
})
|
||||
|
||||
const validateCommentCreation = async (resolve, root, args, context, info) => {
|
||||
const content = args.content.replace(/<(?:.|\n)*?>/gm, '').trim()
|
||||
const { postId } = args
|
||||
|
||||
if (!args.content || content.length < COMMENT_MIN_LENGTH) {
|
||||
throw new UserInputError(`Comment must be at least ${COMMENT_MIN_LENGTH} character long!`)
|
||||
}
|
||||
const session = context.driver.session()
|
||||
const postQueryRes = await session.run(
|
||||
`
|
||||
MATCH (post:Post {id: $postId})
|
||||
RETURN post`,
|
||||
{
|
||||
postId,
|
||||
},
|
||||
)
|
||||
const [post] = postQueryRes.records.map(record => {
|
||||
return record.get('post')
|
||||
})
|
||||
|
||||
if (!post) {
|
||||
throw new UserInputError(NO_POST_ERR_MESSAGE)
|
||||
} else {
|
||||
return resolve(root, args, context, info)
|
||||
}
|
||||
}
|
||||
|
||||
const validateUpdateComment = async (resolve, root, args, context, info) => {
|
||||
const COMMENT_MIN_LENGTH = 1
|
||||
const content = args.content.replace(/<(?:.|\n)*?>/gm, '').trim()
|
||||
if (!args.content || content.length < COMMENT_MIN_LENGTH) {
|
||||
throw new UserInputError(`Comment must be at least ${COMMENT_MIN_LENGTH} character long!`)
|
||||
}
|
||||
|
||||
return resolve(root, args, context, info)
|
||||
}
|
||||
|
||||
export default {
|
||||
Mutation: {
|
||||
CreateSocialMedia: validate(socialMediaSchema),
|
||||
CreateComment: validateCommentCreation,
|
||||
UpdateComment: validateUpdateComment,
|
||||
},
|
||||
}
|
||||
7
backend/src/models/Badge.js
Normal file
7
backend/src/models/Badge.js
Normal file
@ -0,0 +1,7 @@
|
||||
module.exports = {
|
||||
id: { type: 'string', primary: true, lowercase: true },
|
||||
status: { type: 'string', valid: ['permanent', 'temporary'] },
|
||||
type: { type: 'string', valid: ['role', 'crowdfunding'] },
|
||||
icon: { type: 'string', required: true },
|
||||
createdAt: { type: 'string', isoDate: true, default: () => new Date().toISOString() },
|
||||
}
|
||||
13
backend/src/models/EmailAddress.js
Normal file
13
backend/src/models/EmailAddress.js
Normal file
@ -0,0 +1,13 @@
|
||||
module.exports = {
|
||||
email: { type: 'string', primary: true, lowercase: true, email: true },
|
||||
createdAt: { type: 'string', isoDate: true, default: () => new Date().toISOString() },
|
||||
verifiedAt: { type: 'string', isoDate: true },
|
||||
nonce: { type: 'string', token: true },
|
||||
belongsTo: {
|
||||
type: 'relationship',
|
||||
relationship: 'BELONGS_TO',
|
||||
target: 'User',
|
||||
direction: 'out',
|
||||
eager: true,
|
||||
},
|
||||
}
|
||||
16
backend/src/models/InvitationCode.js
Normal file
16
backend/src/models/InvitationCode.js
Normal file
@ -0,0 +1,16 @@
|
||||
module.exports = {
|
||||
createdAt: { type: 'string', isoDate: true, default: () => new Date().toISOString() },
|
||||
token: { type: 'string', primary: true, token: true },
|
||||
generatedBy: {
|
||||
type: 'relationship',
|
||||
relationship: 'GENERATED',
|
||||
target: 'User',
|
||||
direction: 'in',
|
||||
},
|
||||
activated: {
|
||||
type: 'relationship',
|
||||
relationship: 'ACTIVATED',
|
||||
target: 'EmailAddress',
|
||||
direction: 'out',
|
||||
},
|
||||
}
|
||||
59
backend/src/models/User.js
Normal file
59
backend/src/models/User.js
Normal file
@ -0,0 +1,59 @@
|
||||
import uuid from 'uuid/v4'
|
||||
|
||||
module.exports = {
|
||||
id: { type: 'string', primary: true, default: uuid }, // TODO: should be type: 'uuid' but simplified for our tests
|
||||
actorId: { type: 'string', allow: [null] },
|
||||
name: { type: 'string', min: 3 },
|
||||
slug: 'string',
|
||||
encryptedPassword: 'string',
|
||||
avatar: { type: 'string', allow: [null] },
|
||||
coverImg: { type: 'string', allow: [null] },
|
||||
deleted: { type: 'boolean', default: false },
|
||||
disabled: { type: 'boolean', default: false },
|
||||
role: { type: 'string', default: 'user' },
|
||||
publicKey: 'string',
|
||||
privateKey: 'string',
|
||||
wasInvited: 'boolean',
|
||||
wasSeeded: 'boolean',
|
||||
locationName: { type: 'string', allow: [null] },
|
||||
about: { type: 'string', allow: [null] },
|
||||
primaryEmail: {
|
||||
type: 'relationship',
|
||||
relationship: 'PRIMARY_EMAIL',
|
||||
target: 'EmailAddress',
|
||||
direction: 'out',
|
||||
},
|
||||
following: {
|
||||
type: 'relationship',
|
||||
relationship: 'FOLLOWS',
|
||||
target: 'User',
|
||||
direction: 'out',
|
||||
},
|
||||
followedBy: {
|
||||
type: 'relationship',
|
||||
relationship: 'FOLLOWS',
|
||||
target: 'User',
|
||||
direction: 'in',
|
||||
},
|
||||
friends: { type: 'relationship', relationship: 'FRIENDS', target: 'User', direction: 'both' },
|
||||
disabledBy: {
|
||||
type: 'relationship',
|
||||
relationship: 'DISABLED',
|
||||
target: 'User',
|
||||
direction: 'in',
|
||||
},
|
||||
rewarded: {
|
||||
type: 'relationship',
|
||||
relationship: 'REWARDED',
|
||||
target: 'Badge',
|
||||
direction: 'in',
|
||||
},
|
||||
invitedBy: { type: 'relationship', relationship: 'INVITED', target: 'User', direction: 'in' },
|
||||
createdAt: { type: 'string', isoDate: true, default: () => new Date().toISOString() },
|
||||
updatedAt: {
|
||||
type: 'string',
|
||||
isoDate: true,
|
||||
required: true,
|
||||
default: () => new Date().toISOString(),
|
||||
},
|
||||
}
|
||||
20
backend/src/models/User.spec.js
Normal file
20
backend/src/models/User.spec.js
Normal file
@ -0,0 +1,20 @@
|
||||
import Factory from '../seed/factories'
|
||||
import { neode } from '../bootstrap/neo4j'
|
||||
|
||||
const factory = Factory()
|
||||
const instance = neode()
|
||||
|
||||
afterEach(async () => {
|
||||
await factory.cleanDatabase()
|
||||
})
|
||||
|
||||
describe('role', () => {
|
||||
it('defaults to `user`', async () => {
|
||||
const user = await instance.create('User', { name: 'John' })
|
||||
await expect(user.toJson()).resolves.toEqual(
|
||||
expect.objectContaining({
|
||||
role: 'user',
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
8
backend/src/models/index.js
Normal file
8
backend/src/models/index.js
Normal file
@ -0,0 +1,8 @@
|
||||
// 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 {
|
||||
Badge: require('./Badge.js'),
|
||||
User: require('./User.js'),
|
||||
InvitationCode: require('./InvitationCode.js'),
|
||||
EmailAddress: require('./EmailAddress.js'),
|
||||
}
|
||||
@ -12,10 +12,26 @@ export default applyScalars(
|
||||
resolvers,
|
||||
config: {
|
||||
query: {
|
||||
exclude: ['Notfication', 'Statistics', 'LoggedInUser'],
|
||||
exclude: [
|
||||
'Badge',
|
||||
'InvitationCode',
|
||||
'EmailAddress',
|
||||
'Notfication',
|
||||
'Statistics',
|
||||
'LoggedInUser',
|
||||
],
|
||||
// add 'User' here as soon as possible
|
||||
},
|
||||
mutation: {
|
||||
exclude: ['Notfication', 'Statistics', 'LoggedInUser'],
|
||||
exclude: [
|
||||
'Badge',
|
||||
'InvitationCode',
|
||||
'EmailAddress',
|
||||
'Notfication',
|
||||
'Statistics',
|
||||
'LoggedInUser',
|
||||
],
|
||||
// add 'User' here as soon as possible
|
||||
},
|
||||
debug: CONFIG.DEBUG,
|
||||
},
|
||||
|
||||
9
backend/src/schema/resolvers/badges.js
Normal file
9
backend/src/schema/resolvers/badges.js
Normal file
@ -0,0 +1,9 @@
|
||||
import { neo4jgraphql } from 'neo4j-graphql-js'
|
||||
|
||||
export default {
|
||||
Query: {
|
||||
Badge: async (object, args, context, resolveInfo) => {
|
||||
return neo4jgraphql(object, args, context, resolveInfo, false)
|
||||
},
|
||||
},
|
||||
}
|
||||
@ -1,200 +0,0 @@
|
||||
import { GraphQLClient } from 'graphql-request'
|
||||
import Factory from '../../seed/factories'
|
||||
import { host, login } from '../../jest/helpers'
|
||||
|
||||
const factory = Factory()
|
||||
let client
|
||||
|
||||
describe('badges', () => {
|
||||
beforeEach(async () => {
|
||||
await factory.create('User', {
|
||||
email: 'user@example.org',
|
||||
role: 'user',
|
||||
password: '1234',
|
||||
})
|
||||
await factory.create('User', {
|
||||
id: 'u2',
|
||||
role: 'moderator',
|
||||
email: 'moderator@example.org',
|
||||
})
|
||||
await factory.create('User', {
|
||||
id: 'u3',
|
||||
role: 'admin',
|
||||
email: 'admin@example.org',
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await factory.cleanDatabase()
|
||||
})
|
||||
|
||||
describe('CreateBadge', () => {
|
||||
const variables = {
|
||||
id: 'b1',
|
||||
key: 'indiegogo_en_racoon',
|
||||
type: 'crowdfunding',
|
||||
status: 'permanent',
|
||||
icon: '/img/badges/indiegogo_en_racoon.svg',
|
||||
}
|
||||
|
||||
const mutation = `
|
||||
mutation(
|
||||
$id: ID
|
||||
$key: String!
|
||||
$type: BadgeType!
|
||||
$status: BadgeStatus!
|
||||
$icon: String!
|
||||
) {
|
||||
CreateBadge(id: $id, key: $key, type: $type, status: $status, icon: $icon) {
|
||||
id,
|
||||
key,
|
||||
type,
|
||||
status,
|
||||
icon
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
describe('unauthenticated', () => {
|
||||
it('throws authorization error', async () => {
|
||||
client = new GraphQLClient(host)
|
||||
await expect(client.request(mutation, variables)).rejects.toThrow('Not Authorised')
|
||||
})
|
||||
})
|
||||
|
||||
describe('authenticated admin', () => {
|
||||
beforeEach(async () => {
|
||||
const headers = await login({ email: 'admin@example.org', password: '1234' })
|
||||
client = new GraphQLClient(host, { headers })
|
||||
})
|
||||
it('creates a badge', async () => {
|
||||
const expected = {
|
||||
CreateBadge: {
|
||||
icon: '/img/badges/indiegogo_en_racoon.svg',
|
||||
id: 'b1',
|
||||
key: 'indiegogo_en_racoon',
|
||||
status: 'permanent',
|
||||
type: 'crowdfunding',
|
||||
},
|
||||
}
|
||||
await expect(client.request(mutation, variables)).resolves.toEqual(expected)
|
||||
})
|
||||
})
|
||||
|
||||
describe('authenticated moderator', () => {
|
||||
beforeEach(async () => {
|
||||
const headers = await login({ email: 'moderator@example.org', password: '1234' })
|
||||
client = new GraphQLClient(host, { headers })
|
||||
})
|
||||
|
||||
it('throws authorization error', async () => {
|
||||
await expect(client.request(mutation, variables)).rejects.toThrow('Not Authorised')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('UpdateBadge', () => {
|
||||
beforeEach(async () => {
|
||||
await factory.authenticateAs({ email: 'admin@example.org', password: '1234' })
|
||||
await factory.create('Badge', { id: 'b1' })
|
||||
})
|
||||
const variables = {
|
||||
id: 'b1',
|
||||
key: 'whatever',
|
||||
}
|
||||
|
||||
const mutation = `
|
||||
mutation($id: ID!, $key: String!) {
|
||||
UpdateBadge(id: $id, key: $key) {
|
||||
id
|
||||
key
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
describe('unauthenticated', () => {
|
||||
it('throws authorization error', async () => {
|
||||
client = new GraphQLClient(host)
|
||||
await expect(client.request(mutation, variables)).rejects.toThrow('Not Authorised')
|
||||
})
|
||||
})
|
||||
|
||||
describe('authenticated moderator', () => {
|
||||
beforeEach(async () => {
|
||||
const headers = await login({ email: 'moderator@example.org', password: '1234' })
|
||||
client = new GraphQLClient(host, { headers })
|
||||
})
|
||||
|
||||
it('throws authorization error', async () => {
|
||||
await expect(client.request(mutation, variables)).rejects.toThrow('Not Authorised')
|
||||
})
|
||||
})
|
||||
|
||||
describe('authenticated admin', () => {
|
||||
beforeEach(async () => {
|
||||
const headers = await login({ email: 'admin@example.org', password: '1234' })
|
||||
client = new GraphQLClient(host, { headers })
|
||||
})
|
||||
it('updates a badge', async () => {
|
||||
const expected = {
|
||||
UpdateBadge: {
|
||||
id: 'b1',
|
||||
key: 'whatever',
|
||||
},
|
||||
}
|
||||
await expect(client.request(mutation, variables)).resolves.toEqual(expected)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('DeleteBadge', () => {
|
||||
beforeEach(async () => {
|
||||
await factory.authenticateAs({ email: 'admin@example.org', password: '1234' })
|
||||
await factory.create('Badge', { id: 'b1' })
|
||||
})
|
||||
const variables = {
|
||||
id: 'b1',
|
||||
}
|
||||
|
||||
const mutation = `
|
||||
mutation($id: ID!) {
|
||||
DeleteBadge(id: $id) {
|
||||
id
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
describe('unauthenticated', () => {
|
||||
it('throws authorization error', async () => {
|
||||
client = new GraphQLClient(host)
|
||||
await expect(client.request(mutation, variables)).rejects.toThrow('Not Authorised')
|
||||
})
|
||||
})
|
||||
|
||||
describe('authenticated moderator', () => {
|
||||
beforeEach(async () => {
|
||||
const headers = await login({ email: 'moderator@example.org', password: '1234' })
|
||||
client = new GraphQLClient(host, { headers })
|
||||
})
|
||||
|
||||
it('throws authorization error', async () => {
|
||||
await expect(client.request(mutation, variables)).rejects.toThrow('Not Authorised')
|
||||
})
|
||||
})
|
||||
|
||||
describe('authenticated admin', () => {
|
||||
beforeEach(async () => {
|
||||
const headers = await login({ email: 'admin@example.org', password: '1234' })
|
||||
client = new GraphQLClient(host, { headers })
|
||||
})
|
||||
it('deletes a badge', async () => {
|
||||
const expected = {
|
||||
DeleteBadge: {
|
||||
id: 'b1',
|
||||
},
|
||||
}
|
||||
await expect(client.request(mutation, variables)).resolves.toEqual(expected)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
@ -1,59 +1,50 @@
|
||||
import { neo4jgraphql } from 'neo4j-graphql-js'
|
||||
import { UserInputError } from 'apollo-server'
|
||||
|
||||
const COMMENT_MIN_LENGTH = 1
|
||||
const NO_POST_ERR_MESSAGE = 'Comment cannot be created without a post!'
|
||||
|
||||
export default {
|
||||
Mutation: {
|
||||
CreateComment: async (object, params, context, resolveInfo) => {
|
||||
const content = params.content.replace(/<(?:.|\n)*?>/gm, '').trim()
|
||||
const { postId } = params
|
||||
// Adding relationship from comment to post by passing in the postId,
|
||||
// but we do not want to create the comment with postId as an attribute
|
||||
// because we use relationships for this. So, we are deleting it from params
|
||||
// before comment creation.
|
||||
delete params.postId
|
||||
|
||||
if (!params.content || content.length < COMMENT_MIN_LENGTH) {
|
||||
throw new UserInputError(`Comment must be at least ${COMMENT_MIN_LENGTH} character long!`)
|
||||
}
|
||||
if (!postId.trim()) {
|
||||
throw new UserInputError(NO_POST_ERR_MESSAGE)
|
||||
}
|
||||
|
||||
const session = context.driver.session()
|
||||
const postQueryRes = await session.run(
|
||||
`
|
||||
MATCH (post:Post {id: $postId})
|
||||
RETURN post`,
|
||||
{
|
||||
postId,
|
||||
},
|
||||
const commentWithoutRelationships = await neo4jgraphql(
|
||||
object,
|
||||
params,
|
||||
context,
|
||||
resolveInfo,
|
||||
false,
|
||||
)
|
||||
const [post] = postQueryRes.records.map(record => {
|
||||
return record.get('post')
|
||||
})
|
||||
|
||||
if (!post) {
|
||||
throw new UserInputError(NO_POST_ERR_MESSAGE)
|
||||
}
|
||||
const comment = await neo4jgraphql(object, params, context, resolveInfo, false)
|
||||
|
||||
await session.run(
|
||||
let transactionRes = await session.run(
|
||||
`
|
||||
MATCH (post:Post {id: $postId}), (comment:Comment {id: $commentId}), (author:User {id: $userId})
|
||||
MERGE (post)<-[:COMMENTS]-(comment)<-[:WROTE]-(author)
|
||||
RETURN post`,
|
||||
RETURN comment, author`,
|
||||
{
|
||||
userId: context.user.id,
|
||||
postId,
|
||||
commentId: comment.id,
|
||||
commentId: commentWithoutRelationships.id,
|
||||
},
|
||||
)
|
||||
session.close()
|
||||
|
||||
return comment
|
||||
const [commentWithAuthor] = transactionRes.records.map(record => {
|
||||
return {
|
||||
comment: record.get('comment'),
|
||||
author: record.get('author'),
|
||||
}
|
||||
})
|
||||
|
||||
const { comment, author } = commentWithAuthor
|
||||
|
||||
const commentReturnedWithAuthor = {
|
||||
...comment.properties,
|
||||
author: author.properties,
|
||||
}
|
||||
session.close()
|
||||
return commentReturnedWithAuthor
|
||||
},
|
||||
DeleteComment: async (object, params, context, resolveInfo) => {
|
||||
const comment = await neo4jgraphql(object, params, context, resolveInfo, false)
|
||||
|
||||
@ -1,7 +1,6 @@
|
||||
import gql from 'graphql-tag'
|
||||
import { GraphQLClient } from 'graphql-request'
|
||||
import Factory from '../../seed/factories'
|
||||
import { host, login } from '../../jest/helpers'
|
||||
import { host, login, gql } from '../../jest/helpers'
|
||||
|
||||
const factory = Factory()
|
||||
let client
|
||||
@ -9,12 +8,37 @@ let createCommentVariables
|
||||
let createPostVariables
|
||||
let createCommentVariablesSansPostId
|
||||
let createCommentVariablesWithNonExistentPost
|
||||
let userParams
|
||||
let headers
|
||||
|
||||
const createPostMutation = gql`
|
||||
mutation($id: ID!, $title: String!, $content: String!) {
|
||||
CreatePost(id: $id, title: $title, content: $content) {
|
||||
id
|
||||
}
|
||||
}
|
||||
`
|
||||
const createCommentMutation = gql`
|
||||
mutation($id: ID, $postId: ID!, $content: String!) {
|
||||
CreateComment(id: $id, postId: $postId, content: $content) {
|
||||
id
|
||||
content
|
||||
}
|
||||
}
|
||||
`
|
||||
createPostVariables = {
|
||||
id: 'p1',
|
||||
title: 'post to comment on',
|
||||
content: 'please comment on me',
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
await factory.create('User', {
|
||||
userParams = {
|
||||
name: 'TestUser',
|
||||
email: 'test@example.org',
|
||||
password: '1234',
|
||||
})
|
||||
}
|
||||
await factory.create('User', userParams)
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
@ -22,28 +46,6 @@ afterEach(async () => {
|
||||
})
|
||||
|
||||
describe('CreateComment', () => {
|
||||
const createCommentMutation = gql`
|
||||
mutation($postId: ID, $content: String!) {
|
||||
CreateComment(postId: $postId, content: $content) {
|
||||
id
|
||||
content
|
||||
}
|
||||
}
|
||||
`
|
||||
const createPostMutation = gql`
|
||||
mutation($id: ID!, $title: String!, $content: String!) {
|
||||
CreatePost(id: $id, title: $title, content: $content) {
|
||||
id
|
||||
}
|
||||
}
|
||||
`
|
||||
const commentQueryForPostId = gql`
|
||||
query($content: String) {
|
||||
Comment(content: $content) {
|
||||
postId
|
||||
}
|
||||
}
|
||||
`
|
||||
describe('unauthenticated', () => {
|
||||
it('throws authorization error', async () => {
|
||||
createCommentVariables = {
|
||||
@ -58,12 +60,8 @@ describe('CreateComment', () => {
|
||||
})
|
||||
|
||||
describe('authenticated', () => {
|
||||
let headers
|
||||
beforeEach(async () => {
|
||||
headers = await login({
|
||||
email: 'test@example.org',
|
||||
password: '1234',
|
||||
})
|
||||
headers = await login(userParams)
|
||||
client = new GraphQLClient(host, {
|
||||
headers,
|
||||
})
|
||||
@ -71,11 +69,6 @@ describe('CreateComment', () => {
|
||||
postId: 'p1',
|
||||
content: "I'm authorised to comment",
|
||||
}
|
||||
createPostVariables = {
|
||||
id: 'p1',
|
||||
title: 'post to comment on',
|
||||
content: 'please comment on me',
|
||||
}
|
||||
await client.request(createPostMutation, createPostVariables)
|
||||
})
|
||||
|
||||
@ -96,7 +89,7 @@ describe('CreateComment', () => {
|
||||
|
||||
const { User } = await client.request(gql`
|
||||
{
|
||||
User(email: "test@example.org") {
|
||||
User(name: "TestUser") {
|
||||
comments {
|
||||
content
|
||||
}
|
||||
@ -191,109 +184,196 @@ describe('CreateComment', () => {
|
||||
client.request(createCommentMutation, createCommentVariablesWithNonExistentPost),
|
||||
).rejects.toThrow('Comment cannot be created without a post!')
|
||||
})
|
||||
|
||||
it('does not create the comment with the postId as an attribute', async () => {
|
||||
const commentQueryVariablesByContent = {
|
||||
content: "I'm authorised to comment",
|
||||
}
|
||||
|
||||
await client.request(createCommentMutation, createCommentVariables)
|
||||
const { Comment } = await client.request(
|
||||
commentQueryForPostId,
|
||||
commentQueryVariablesByContent,
|
||||
)
|
||||
expect(Comment).toEqual([
|
||||
{
|
||||
postId: null,
|
||||
},
|
||||
])
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('DeleteComment', () => {
|
||||
const deleteCommentMutation = gql`
|
||||
mutation($id: ID!) {
|
||||
DeleteComment(id: $id) {
|
||||
id
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
let deleteCommentVariables = {
|
||||
id: 'c1',
|
||||
}
|
||||
|
||||
describe('ManageComments', () => {
|
||||
let authorParams
|
||||
beforeEach(async () => {
|
||||
authorParams = {
|
||||
email: 'author@example.org',
|
||||
password: '1234',
|
||||
}
|
||||
const asAuthor = Factory()
|
||||
await asAuthor.create('User', {
|
||||
email: 'author@example.org',
|
||||
password: '1234',
|
||||
})
|
||||
await asAuthor.authenticateAs({
|
||||
email: 'author@example.org',
|
||||
password: '1234',
|
||||
})
|
||||
await asAuthor.create('User', authorParams)
|
||||
await asAuthor.authenticateAs(authorParams)
|
||||
await asAuthor.create('Post', {
|
||||
id: 'p1',
|
||||
content: 'Post to be commented',
|
||||
})
|
||||
await asAuthor.create('Comment', {
|
||||
id: 'c1',
|
||||
id: 'c456',
|
||||
postId: 'p1',
|
||||
content: 'Comment to be deleted',
|
||||
})
|
||||
})
|
||||
|
||||
describe('unauthenticated', () => {
|
||||
it('throws authorization error', async () => {
|
||||
client = new GraphQLClient(host)
|
||||
await expect(client.request(deleteCommentMutation, deleteCommentVariables)).rejects.toThrow(
|
||||
'Not Authorised',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('authenticated but not the author', () => {
|
||||
beforeEach(async () => {
|
||||
let headers
|
||||
headers = await login({
|
||||
email: 'test@example.org',
|
||||
password: '1234',
|
||||
})
|
||||
client = new GraphQLClient(host, {
|
||||
headers,
|
||||
})
|
||||
})
|
||||
|
||||
it('throws authorization error', async () => {
|
||||
await expect(client.request(deleteCommentMutation, deleteCommentVariables)).rejects.toThrow(
|
||||
'Not Authorised',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('authenticated as author', () => {
|
||||
beforeEach(async () => {
|
||||
let headers
|
||||
headers = await login({
|
||||
email: 'author@example.org',
|
||||
password: '1234',
|
||||
})
|
||||
client = new GraphQLClient(host, {
|
||||
headers,
|
||||
})
|
||||
})
|
||||
|
||||
it('deletes the comment', async () => {
|
||||
const expected = {
|
||||
DeleteComment: {
|
||||
id: 'c1',
|
||||
},
|
||||
describe('UpdateComment', () => {
|
||||
const updateCommentMutation = gql`
|
||||
mutation($content: String!, $id: ID!) {
|
||||
UpdateComment(content: $content, id: $id) {
|
||||
id
|
||||
content
|
||||
}
|
||||
}
|
||||
await expect(client.request(deleteCommentMutation, deleteCommentVariables)).resolves.toEqual(
|
||||
expected,
|
||||
)
|
||||
`
|
||||
|
||||
let updateCommentVariables = {
|
||||
id: 'c456',
|
||||
content: 'The comment is updated',
|
||||
}
|
||||
|
||||
describe('unauthenticated', () => {
|
||||
it('throws authorization error', async () => {
|
||||
client = new GraphQLClient(host)
|
||||
await expect(client.request(updateCommentMutation, updateCommentVariables)).rejects.toThrow(
|
||||
'Not Authorised',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('authenticated but not the author', () => {
|
||||
beforeEach(async () => {
|
||||
headers = await login({
|
||||
email: 'test@example.org',
|
||||
password: '1234',
|
||||
})
|
||||
client = new GraphQLClient(host, {
|
||||
headers,
|
||||
})
|
||||
})
|
||||
|
||||
it('throws authorization error', async () => {
|
||||
await expect(client.request(updateCommentMutation, updateCommentVariables)).rejects.toThrow(
|
||||
'Not Authorised',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('authenticated as author', () => {
|
||||
beforeEach(async () => {
|
||||
headers = await login(authorParams)
|
||||
client = new GraphQLClient(host, {
|
||||
headers,
|
||||
})
|
||||
})
|
||||
|
||||
it('updates the comment', async () => {
|
||||
const expected = {
|
||||
UpdateComment: {
|
||||
id: 'c456',
|
||||
content: 'The comment is updated',
|
||||
},
|
||||
}
|
||||
await expect(
|
||||
client.request(updateCommentMutation, updateCommentVariables),
|
||||
).resolves.toEqual(expected)
|
||||
})
|
||||
|
||||
it('throw an error if an empty string is sent from the editor as content', async () => {
|
||||
updateCommentVariables = {
|
||||
id: 'c456',
|
||||
content: '<p></p>',
|
||||
}
|
||||
|
||||
await expect(client.request(updateCommentMutation, updateCommentVariables)).rejects.toThrow(
|
||||
'Comment must be at least 1 character long!',
|
||||
)
|
||||
})
|
||||
|
||||
it('throws an error if a comment sent from the editor does not contain a single letter character', async () => {
|
||||
updateCommentVariables = {
|
||||
id: 'c456',
|
||||
content: '<p> </p>',
|
||||
}
|
||||
|
||||
await expect(client.request(updateCommentMutation, updateCommentVariables)).rejects.toThrow(
|
||||
'Comment must be at least 1 character long!',
|
||||
)
|
||||
})
|
||||
|
||||
it('throws an error if commentId is sent as an empty string', async () => {
|
||||
updateCommentVariables = {
|
||||
id: '',
|
||||
content: '<p>Hello</p>',
|
||||
}
|
||||
|
||||
await expect(client.request(updateCommentMutation, updateCommentVariables)).rejects.toThrow(
|
||||
'Not Authorised!',
|
||||
)
|
||||
})
|
||||
|
||||
it('throws an error if the comment does not exist in the database', async () => {
|
||||
updateCommentVariables = {
|
||||
id: 'c1000',
|
||||
content: '<p>Hello</p>',
|
||||
}
|
||||
|
||||
await expect(client.request(updateCommentMutation, updateCommentVariables)).rejects.toThrow(
|
||||
'Not Authorised!',
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('DeleteComment', () => {
|
||||
const deleteCommentMutation = gql`
|
||||
mutation($id: ID!) {
|
||||
DeleteComment(id: $id) {
|
||||
id
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
let deleteCommentVariables = {
|
||||
id: 'c456',
|
||||
}
|
||||
|
||||
describe('unauthenticated', () => {
|
||||
it('throws authorization error', async () => {
|
||||
client = new GraphQLClient(host)
|
||||
await expect(client.request(deleteCommentMutation, deleteCommentVariables)).rejects.toThrow(
|
||||
'Not Authorised',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('authenticated but not the author', () => {
|
||||
beforeEach(async () => {
|
||||
headers = await login({
|
||||
email: 'test@example.org',
|
||||
password: '1234',
|
||||
})
|
||||
client = new GraphQLClient(host, {
|
||||
headers,
|
||||
})
|
||||
})
|
||||
|
||||
it('throws authorization error', async () => {
|
||||
await expect(client.request(deleteCommentMutation, deleteCommentVariables)).rejects.toThrow(
|
||||
'Not Authorised',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('authenticated as author', () => {
|
||||
beforeEach(async () => {
|
||||
headers = await login(authorParams)
|
||||
client = new GraphQLClient(host, {
|
||||
headers,
|
||||
})
|
||||
})
|
||||
|
||||
it('deletes the comment', async () => {
|
||||
const expected = {
|
||||
DeleteComment: {
|
||||
id: 'c456',
|
||||
},
|
||||
}
|
||||
await expect(
|
||||
client.request(deleteCommentMutation, deleteCommentVariables),
|
||||
).resolves.toEqual(expected)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@ -12,7 +12,6 @@ const storeUpload = ({ createReadStream, fileLocation }) =>
|
||||
|
||||
export default async function fileUpload(params, { file, url }, uploadCallback = storeUpload) {
|
||||
const upload = params[file]
|
||||
|
||||
if (upload) {
|
||||
const { createReadStream, filename } = await upload
|
||||
const { name } = path.parse(filename)
|
||||
|
||||
@ -254,7 +254,7 @@ describe('enable', () => {
|
||||
beforeEach(async () => {
|
||||
authenticateClient = setupAuthenticateClient({
|
||||
role: 'moderator',
|
||||
email: 'someUser@example.org',
|
||||
email: 'someuser@example.org',
|
||||
password: '1234',
|
||||
})
|
||||
})
|
||||
|
||||
@ -1,28 +1,11 @@
|
||||
import uuid from 'uuid/v4'
|
||||
import bcrypt from 'bcryptjs'
|
||||
import CONFIG from '../../config'
|
||||
import nodemailer from 'nodemailer'
|
||||
import { resetPasswordMail, wrongAccountMail } from './passwordReset/emailTemplates'
|
||||
|
||||
const transporter = () => {
|
||||
const configs = {
|
||||
host: CONFIG.SMTP_HOST,
|
||||
port: CONFIG.SMTP_PORT,
|
||||
ignoreTLS: CONFIG.SMTP_IGNORE_TLS,
|
||||
secure: false, // true for 465, false for other ports
|
||||
}
|
||||
const { SMTP_USERNAME: user, SMTP_PASSWORD: pass } = CONFIG
|
||||
if (user && pass) {
|
||||
configs.auth = { user, pass }
|
||||
}
|
||||
return nodemailer.createTransport(configs)
|
||||
}
|
||||
|
||||
export async function createPasswordReset(options) {
|
||||
const { driver, code, email, issuedAt = new Date() } = options
|
||||
const session = driver.session()
|
||||
const cypher = `
|
||||
MATCH (u:User) WHERE u.email = $email
|
||||
MATCH (u:User)-[:PRIMARY_EMAIL]->(e:EmailAddress {email:$email})
|
||||
CREATE(pr:PasswordReset {code: $code, issuedAt: datetime($issuedAt), usedAt: NULL})
|
||||
MERGE (u)-[:REQUESTED]->(pr)
|
||||
RETURN u
|
||||
@ -42,27 +25,28 @@ export default {
|
||||
requestPasswordReset: async (_, { email }, { driver }) => {
|
||||
const code = uuid().substring(0, 6)
|
||||
const [user] = await createPasswordReset({ driver, code, email })
|
||||
if (CONFIG.SMTP_HOST && CONFIG.SMTP_PORT) {
|
||||
const name = (user && user.name) || ''
|
||||
const mailTemplate = user ? resetPasswordMail : wrongAccountMail
|
||||
await transporter().sendMail(mailTemplate({ email, code, name }))
|
||||
}
|
||||
return true
|
||||
const name = (user && user.name) || ''
|
||||
return { user, code, name, response: true }
|
||||
},
|
||||
resetPassword: async (_, { email, code, newPassword }, { driver }) => {
|
||||
const session = driver.session()
|
||||
const stillValid = new Date()
|
||||
stillValid.setDate(stillValid.getDate() - 1)
|
||||
const newHashedPassword = await bcrypt.hashSync(newPassword, 10)
|
||||
const encryptedNewPassword = await bcrypt.hashSync(newPassword, 10)
|
||||
const cypher = `
|
||||
MATCH (pr:PasswordReset {code: $code})
|
||||
MATCH (u:User {email: $email})-[:REQUESTED]->(pr)
|
||||
MATCH (e:EmailAddress {email: $email})<-[:PRIMARY_EMAIL]-(u:User)-[:REQUESTED]->(pr)
|
||||
WHERE duration.between(pr.issuedAt, datetime()).days <= 0 AND pr.usedAt IS NULL
|
||||
SET pr.usedAt = datetime()
|
||||
SET u.password = $newHashedPassword
|
||||
SET u.encryptedPassword = $encryptedNewPassword
|
||||
RETURN pr
|
||||
`
|
||||
let transactionRes = await session.run(cypher, { stillValid, email, code, newHashedPassword })
|
||||
let transactionRes = await session.run(cypher, {
|
||||
stillValid,
|
||||
email,
|
||||
code,
|
||||
encryptedNewPassword,
|
||||
})
|
||||
const [reset] = transactionRes.records.map(record => record.get('pr'))
|
||||
const result = !!(reset && reset.properties.usedAt)
|
||||
session.close()
|
||||
|
||||
@ -1,30 +1,74 @@
|
||||
import { neo4jgraphql } from 'neo4j-graphql-js'
|
||||
import uuid from 'uuid/v4'
|
||||
import fileUpload from './fileUpload'
|
||||
|
||||
export default {
|
||||
Mutation: {
|
||||
UpdatePost: async (object, params, context, resolveInfo) => {
|
||||
const { categoryIds } = params
|
||||
delete params.categoryIds
|
||||
params = await fileUpload(params, { file: 'imageUpload', url: 'image' })
|
||||
return neo4jgraphql(object, params, context, resolveInfo, false)
|
||||
const session = context.driver.session()
|
||||
const cypherDeletePreviousRelations = `
|
||||
MATCH (post:Post { id: $params.id })-[previousRelations:CATEGORIZED]->(category:Category)
|
||||
DELETE previousRelations
|
||||
RETURN post, category
|
||||
`
|
||||
|
||||
await session.run(cypherDeletePreviousRelations, { params })
|
||||
|
||||
let updatePostCypher = `MATCH (post:Post {id: $params.id})
|
||||
SET post = $params
|
||||
`
|
||||
if (categoryIds && categoryIds.length) {
|
||||
updatePostCypher += `WITH post
|
||||
UNWIND $categoryIds AS categoryId
|
||||
MATCH (category:Category {id: categoryId})
|
||||
MERGE (post)-[:CATEGORIZED]->(category)
|
||||
`
|
||||
}
|
||||
updatePostCypher += `RETURN post`
|
||||
const updatePostVariables = { categoryIds, params }
|
||||
|
||||
const transactionRes = await session.run(updatePostCypher, updatePostVariables)
|
||||
const [post] = transactionRes.records.map(record => {
|
||||
return record.get('post')
|
||||
})
|
||||
|
||||
session.close()
|
||||
|
||||
return post.properties
|
||||
},
|
||||
|
||||
CreatePost: async (object, params, context, resolveInfo) => {
|
||||
const { categoryIds } = params
|
||||
delete params.categoryIds
|
||||
params = await fileUpload(params, { file: 'imageUpload', url: 'image' })
|
||||
const result = await neo4jgraphql(object, params, context, resolveInfo, false)
|
||||
params.id = params.id || uuid()
|
||||
let createPostCypher = `CREATE (post:Post {params})
|
||||
WITH post
|
||||
MATCH (author:User {id: $userId})
|
||||
MERGE (post)<-[:WROTE]-(author)
|
||||
`
|
||||
if (categoryIds) {
|
||||
createPostCypher += `WITH post
|
||||
UNWIND $categoryIds AS categoryId
|
||||
MATCH (category:Category {id: categoryId})
|
||||
MERGE (post)-[:CATEGORIZED]->(category)
|
||||
`
|
||||
}
|
||||
createPostCypher += `RETURN post`
|
||||
const createPostVariables = { userId: context.user.id, categoryIds, params }
|
||||
|
||||
const session = context.driver.session()
|
||||
await session.run(
|
||||
'MATCH (author:User {id: $userId}), (post:Post {id: $postId}) ' +
|
||||
'MERGE (post)<-[:WROTE]-(author) ' +
|
||||
'RETURN author',
|
||||
{
|
||||
userId: context.user.id,
|
||||
postId: result.id,
|
||||
},
|
||||
)
|
||||
const transactionRes = await session.run(createPostCypher, createPostVariables)
|
||||
|
||||
const [post] = transactionRes.records.map(record => {
|
||||
return record.get('post')
|
||||
})
|
||||
|
||||
session.close()
|
||||
|
||||
return result
|
||||
return post.properties
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
@ -4,12 +4,69 @@ import { host, login } from '../../jest/helpers'
|
||||
|
||||
const factory = Factory()
|
||||
let client
|
||||
let userParams
|
||||
let authorParams
|
||||
|
||||
const postTitle = 'I am a title'
|
||||
const postContent = 'Some content'
|
||||
const oldTitle = 'Old title'
|
||||
const oldContent = 'Old content'
|
||||
const newTitle = 'New title'
|
||||
const newContent = 'New content'
|
||||
const createPostVariables = { title: postTitle, content: postContent }
|
||||
const createPostWithCategoriesMutation = `
|
||||
mutation($title: String!, $content: String!, $categoryIds: [ID]) {
|
||||
CreatePost(title: $title, content: $content, categoryIds: $categoryIds) {
|
||||
id
|
||||
title
|
||||
}
|
||||
}
|
||||
`
|
||||
const createPostWithCategoriesVariables = {
|
||||
title: postTitle,
|
||||
content: postContent,
|
||||
categoryIds: ['cat9', 'cat4', 'cat15'],
|
||||
}
|
||||
const postQueryWithCategories = `
|
||||
query($id: ID) {
|
||||
Post(id: $id) {
|
||||
categories {
|
||||
id
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
const createPostWithoutCategoriesVariables = {
|
||||
title: 'This is a post without categories',
|
||||
content: 'I should be able to filter it out',
|
||||
categoryIds: null,
|
||||
}
|
||||
const postQueryFilteredByCategory = `
|
||||
query Post($filter: _PostFilter) {
|
||||
Post(filter: $filter) {
|
||||
title
|
||||
id
|
||||
categories {
|
||||
id
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
const postCategoriesFilterParam = { categories_some: { id_in: ['cat4'] } }
|
||||
const postQueryFilteredByCategoryVariables = {
|
||||
filter: postCategoriesFilterParam,
|
||||
}
|
||||
beforeEach(async () => {
|
||||
await factory.create('User', {
|
||||
userParams = {
|
||||
name: 'TestUser',
|
||||
email: 'test@example.org',
|
||||
password: '1234',
|
||||
})
|
||||
}
|
||||
authorParams = {
|
||||
email: 'author@example.org',
|
||||
password: '1234',
|
||||
}
|
||||
await factory.create('User', userParams)
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
@ -18,8 +75,8 @@ afterEach(async () => {
|
||||
|
||||
describe('CreatePost', () => {
|
||||
const mutation = `
|
||||
mutation {
|
||||
CreatePost(title: "I am a title", content: "Some content") {
|
||||
mutation($title: String!, $content: String!) {
|
||||
CreatePost(title: $title, content: $content) {
|
||||
title
|
||||
content
|
||||
slug
|
||||
@ -32,32 +89,32 @@ describe('CreatePost', () => {
|
||||
describe('unauthenticated', () => {
|
||||
it('throws authorization error', async () => {
|
||||
client = new GraphQLClient(host)
|
||||
await expect(client.request(mutation)).rejects.toThrow('Not Authorised')
|
||||
await expect(client.request(mutation, createPostVariables)).rejects.toThrow('Not Authorised')
|
||||
})
|
||||
})
|
||||
|
||||
describe('authenticated', () => {
|
||||
let headers
|
||||
beforeEach(async () => {
|
||||
headers = await login({ email: 'test@example.org', password: '1234' })
|
||||
headers = await login(userParams)
|
||||
client = new GraphQLClient(host, { headers })
|
||||
})
|
||||
|
||||
it('creates a post', async () => {
|
||||
const expected = {
|
||||
CreatePost: {
|
||||
title: 'I am a title',
|
||||
content: 'Some content',
|
||||
title: postTitle,
|
||||
content: postContent,
|
||||
},
|
||||
}
|
||||
await expect(client.request(mutation)).resolves.toMatchObject(expected)
|
||||
await expect(client.request(mutation, createPostVariables)).resolves.toMatchObject(expected)
|
||||
})
|
||||
|
||||
it('assigns the authenticated user as author', async () => {
|
||||
await client.request(mutation)
|
||||
await client.request(mutation, createPostVariables)
|
||||
const { User } = await client.request(
|
||||
`{
|
||||
User(email:"test@example.org") {
|
||||
User(name: "TestUser") {
|
||||
contributions {
|
||||
title
|
||||
}
|
||||
@ -65,94 +122,207 @@ describe('CreatePost', () => {
|
||||
}`,
|
||||
{ headers },
|
||||
)
|
||||
expect(User).toEqual([{ contributions: [{ title: 'I am a title' }] }])
|
||||
expect(User).toEqual([{ contributions: [{ title: postTitle }] }])
|
||||
})
|
||||
|
||||
describe('disabled and deleted', () => {
|
||||
it('initially false', async () => {
|
||||
const expected = { CreatePost: { disabled: false, deleted: false } }
|
||||
await expect(client.request(mutation)).resolves.toMatchObject(expected)
|
||||
await expect(client.request(mutation, createPostVariables)).resolves.toMatchObject(expected)
|
||||
})
|
||||
})
|
||||
|
||||
describe('language', () => {
|
||||
it('allows a user to set the language of the post', async () => {
|
||||
const createPostWithLanguageMutation = `
|
||||
mutation {
|
||||
CreatePost(title: "I am a title", content: "Some content", language: "en") {
|
||||
mutation($title: String!, $content: String!, $language: String) {
|
||||
CreatePost(title: $title, content: $content, language: $language) {
|
||||
language
|
||||
}
|
||||
}
|
||||
`
|
||||
const createPostWithLanguageVariables = {
|
||||
title: postTitle,
|
||||
content: postContent,
|
||||
language: 'en',
|
||||
}
|
||||
const expected = { CreatePost: { language: 'en' } }
|
||||
await expect(client.request(createPostWithLanguageMutation)).resolves.toEqual(
|
||||
expect.objectContaining(expected),
|
||||
await expect(
|
||||
client.request(createPostWithLanguageMutation, createPostWithLanguageVariables),
|
||||
).resolves.toEqual(expect.objectContaining(expected))
|
||||
})
|
||||
})
|
||||
|
||||
describe('categories', () => {
|
||||
let postWithCategories
|
||||
beforeEach(async () => {
|
||||
await Promise.all([
|
||||
factory.create('Category', {
|
||||
id: 'cat9',
|
||||
name: 'Democracy & Politics',
|
||||
icon: 'university',
|
||||
}),
|
||||
factory.create('Category', {
|
||||
id: 'cat4',
|
||||
name: 'Environment & Nature',
|
||||
icon: 'tree',
|
||||
}),
|
||||
factory.create('Category', {
|
||||
id: 'cat15',
|
||||
name: 'Consumption & Sustainability',
|
||||
icon: 'shopping-cart',
|
||||
}),
|
||||
])
|
||||
postWithCategories = await client.request(
|
||||
createPostWithCategoriesMutation,
|
||||
createPostWithCategoriesVariables,
|
||||
)
|
||||
})
|
||||
|
||||
it('allows a user to set the categories of the post', async () => {
|
||||
const expected = [{ id: 'cat9' }, { id: 'cat4' }, { id: 'cat15' }]
|
||||
const postQueryWithCategoriesVariables = {
|
||||
id: postWithCategories.CreatePost.id,
|
||||
}
|
||||
|
||||
await expect(
|
||||
client.request(postQueryWithCategories, postQueryWithCategoriesVariables),
|
||||
).resolves.toEqual({ Post: [{ categories: expect.arrayContaining(expected) }] })
|
||||
})
|
||||
|
||||
it('allows a user to filter for posts by category', async () => {
|
||||
await client.request(createPostWithCategoriesMutation, createPostWithoutCategoriesVariables)
|
||||
const categoryIds = [{ id: 'cat4' }, { id: 'cat15' }, { id: 'cat9' }]
|
||||
const expected = {
|
||||
Post: [
|
||||
{
|
||||
title: postTitle,
|
||||
id: postWithCategories.CreatePost.id,
|
||||
categories: expect.arrayContaining(categoryIds),
|
||||
},
|
||||
],
|
||||
}
|
||||
await expect(
|
||||
client.request(postQueryFilteredByCategory, postQueryFilteredByCategoryVariables),
|
||||
).resolves.toEqual(expected)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('UpdatePost', () => {
|
||||
const mutation = `
|
||||
mutation($id: ID!, $content: String) {
|
||||
UpdatePost(id: $id, content: $content) {
|
||||
id
|
||||
content
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
let variables = {
|
||||
id: 'p1',
|
||||
content: 'New content',
|
||||
}
|
||||
|
||||
let updatePostMutation
|
||||
let updatePostVariables
|
||||
beforeEach(async () => {
|
||||
const asAuthor = Factory()
|
||||
await asAuthor.create('User', {
|
||||
email: 'author@example.org',
|
||||
password: '1234',
|
||||
})
|
||||
await asAuthor.authenticateAs({
|
||||
email: 'author@example.org',
|
||||
password: '1234',
|
||||
})
|
||||
await asAuthor.create('User', authorParams)
|
||||
await asAuthor.authenticateAs(authorParams)
|
||||
await asAuthor.create('Post', {
|
||||
id: 'p1',
|
||||
content: 'Old content',
|
||||
title: oldTitle,
|
||||
content: oldContent,
|
||||
})
|
||||
updatePostMutation = `
|
||||
mutation($id: ID!, $title: String!, $content: String!, $categoryIds: [ID]) {
|
||||
UpdatePost(id: $id, title: $title, content: $content, categoryIds: $categoryIds) {
|
||||
id
|
||||
content
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
updatePostVariables = {
|
||||
id: 'p1',
|
||||
title: newTitle,
|
||||
content: newContent,
|
||||
categoryIds: null,
|
||||
}
|
||||
})
|
||||
|
||||
describe('unauthenticated', () => {
|
||||
it('throws authorization error', async () => {
|
||||
client = new GraphQLClient(host)
|
||||
await expect(client.request(mutation, variables)).rejects.toThrow('Not Authorised')
|
||||
await expect(client.request(updatePostMutation, updatePostVariables)).rejects.toThrow(
|
||||
'Not Authorised',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('authenticated but not the author', () => {
|
||||
let headers
|
||||
beforeEach(async () => {
|
||||
headers = await login({ email: 'test@example.org', password: '1234' })
|
||||
headers = await login(userParams)
|
||||
client = new GraphQLClient(host, { headers })
|
||||
})
|
||||
|
||||
it('throws authorization error', async () => {
|
||||
await expect(client.request(mutation, variables)).rejects.toThrow('Not Authorised')
|
||||
await expect(client.request(updatePostMutation, updatePostVariables)).rejects.toThrow(
|
||||
'Not Authorised',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('authenticated as author', () => {
|
||||
let headers
|
||||
beforeEach(async () => {
|
||||
headers = await login({ email: 'author@example.org', password: '1234' })
|
||||
headers = await login(authorParams)
|
||||
client = new GraphQLClient(host, { headers })
|
||||
})
|
||||
|
||||
it('updates a post', async () => {
|
||||
const expected = { UpdatePost: { id: 'p1', content: 'New content' } }
|
||||
await expect(client.request(mutation, variables)).resolves.toEqual(expected)
|
||||
const expected = { UpdatePost: { id: 'p1', content: newContent } }
|
||||
await expect(client.request(updatePostMutation, updatePostVariables)).resolves.toEqual(
|
||||
expected,
|
||||
)
|
||||
})
|
||||
|
||||
describe('categories', () => {
|
||||
let postWithCategories
|
||||
beforeEach(async () => {
|
||||
await Promise.all([
|
||||
factory.create('Category', {
|
||||
id: 'cat9',
|
||||
name: 'Democracy & Politics',
|
||||
icon: 'university',
|
||||
}),
|
||||
factory.create('Category', {
|
||||
id: 'cat4',
|
||||
name: 'Environment & Nature',
|
||||
icon: 'tree',
|
||||
}),
|
||||
factory.create('Category', {
|
||||
id: 'cat15',
|
||||
name: 'Consumption & Sustainability',
|
||||
icon: 'shopping-cart',
|
||||
}),
|
||||
factory.create('Category', {
|
||||
id: 'cat27',
|
||||
name: 'Animal Protection',
|
||||
icon: 'paw',
|
||||
}),
|
||||
])
|
||||
postWithCategories = await client.request(
|
||||
createPostWithCategoriesMutation,
|
||||
createPostWithCategoriesVariables,
|
||||
)
|
||||
updatePostVariables = {
|
||||
id: postWithCategories.CreatePost.id,
|
||||
title: newTitle,
|
||||
content: newContent,
|
||||
categoryIds: ['cat27'],
|
||||
}
|
||||
})
|
||||
|
||||
it('allows a user to update the categories of a post', async () => {
|
||||
await client.request(updatePostMutation, updatePostVariables)
|
||||
const expected = [{ id: 'cat27' }]
|
||||
const postQueryWithCategoriesVariables = {
|
||||
id: postWithCategories.CreatePost.id,
|
||||
}
|
||||
await expect(
|
||||
client.request(postQueryWithCategories, postQueryWithCategoriesVariables),
|
||||
).resolves.toEqual({ Post: [{ categories: expect.arrayContaining(expected) }] })
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
@ -173,14 +343,8 @@ describe('DeletePost', () => {
|
||||
|
||||
beforeEach(async () => {
|
||||
const asAuthor = Factory()
|
||||
await asAuthor.create('User', {
|
||||
email: 'author@example.org',
|
||||
password: '1234',
|
||||
})
|
||||
await asAuthor.authenticateAs({
|
||||
email: 'author@example.org',
|
||||
password: '1234',
|
||||
})
|
||||
await asAuthor.create('User', authorParams)
|
||||
await asAuthor.authenticateAs(authorParams)
|
||||
await asAuthor.create('Post', {
|
||||
id: 'p1',
|
||||
content: 'To be deleted',
|
||||
@ -197,7 +361,7 @@ describe('DeletePost', () => {
|
||||
describe('authenticated but not the author', () => {
|
||||
let headers
|
||||
beforeEach(async () => {
|
||||
headers = await login({ email: 'test@example.org', password: '1234' })
|
||||
headers = await login(userParams)
|
||||
client = new GraphQLClient(host, { headers })
|
||||
})
|
||||
|
||||
@ -209,7 +373,7 @@ describe('DeletePost', () => {
|
||||
describe('authenticated as author', () => {
|
||||
let headers
|
||||
beforeEach(async () => {
|
||||
headers = await login({ email: 'author@example.org', password: '1234' })
|
||||
headers = await login(authorParams)
|
||||
client = new GraphQLClient(host, { headers })
|
||||
})
|
||||
|
||||
|
||||
107
backend/src/schema/resolvers/registration.js
Normal file
107
backend/src/schema/resolvers/registration.js
Normal file
@ -0,0 +1,107 @@
|
||||
import { UserInputError } from 'apollo-server'
|
||||
import uuid from 'uuid/v4'
|
||||
import { neode } from '../../bootstrap/neo4j'
|
||||
import fileUpload from './fileUpload'
|
||||
import encryptPassword from '../../helpers/encryptPassword'
|
||||
|
||||
const instance = neode()
|
||||
|
||||
/*
|
||||
* TODO: remove this function as soon type `User` has no `email` property
|
||||
* anymore
|
||||
*/
|
||||
const checkEmailDoesNotExist = async ({ email }) => {
|
||||
email = email.toLowerCase()
|
||||
const emails = await instance.all('EmailAddress', { email })
|
||||
if (emails.length > 0) throw new UserInputError('User account with this email already exists.')
|
||||
}
|
||||
|
||||
export default {
|
||||
Mutation: {
|
||||
CreateInvitationCode: async (parent, args, context, resolveInfo) => {
|
||||
args.token = uuid().substring(0, 6)
|
||||
const {
|
||||
user: { id: userId },
|
||||
} = context
|
||||
let response
|
||||
try {
|
||||
const [user, invitationCode] = await Promise.all([
|
||||
instance.find('User', userId),
|
||||
instance.create('InvitationCode', args),
|
||||
])
|
||||
await invitationCode.relateTo(user, 'generatedBy')
|
||||
response = invitationCode.toJson()
|
||||
response.generatedBy = user.toJson()
|
||||
} catch (e) {
|
||||
throw new UserInputError(e)
|
||||
}
|
||||
return response
|
||||
},
|
||||
Signup: async (parent, args, context, resolveInfo) => {
|
||||
const nonce = uuid().substring(0, 6)
|
||||
args.nonce = nonce
|
||||
await checkEmailDoesNotExist({ email: args.email })
|
||||
try {
|
||||
const emailAddress = await instance.create('EmailAddress', args)
|
||||
return { response: emailAddress.toJson(), nonce }
|
||||
} catch (e) {
|
||||
throw new UserInputError(e.message)
|
||||
}
|
||||
},
|
||||
SignupByInvitation: async (parent, args, context, resolveInfo) => {
|
||||
const { token } = args
|
||||
const nonce = uuid().substring(0, 6)
|
||||
args.nonce = nonce
|
||||
await checkEmailDoesNotExist({ email: args.email })
|
||||
try {
|
||||
const result = await instance.cypher(
|
||||
`
|
||||
MATCH (invitationCode:InvitationCode {token:{token}})
|
||||
WHERE NOT (invitationCode)-[:ACTIVATED]->()
|
||||
RETURN invitationCode
|
||||
`,
|
||||
{ token },
|
||||
)
|
||||
const validInvitationCode = instance.hydrateFirst(
|
||||
result,
|
||||
'invitationCode',
|
||||
instance.model('InvitationCode'),
|
||||
)
|
||||
if (!validInvitationCode)
|
||||
throw new UserInputError('Invitation code already used or does not exist.')
|
||||
const emailAddress = await instance.create('EmailAddress', args)
|
||||
await validInvitationCode.relateTo(emailAddress, 'activated')
|
||||
return { response: emailAddress.toJson(), nonce }
|
||||
} catch (e) {
|
||||
throw new UserInputError(e)
|
||||
}
|
||||
},
|
||||
SignupVerification: async (object, args, context, resolveInfo) => {
|
||||
let { nonce, email } = args
|
||||
email = email.toLowerCase()
|
||||
const result = await instance.cypher(
|
||||
`
|
||||
MATCH(email:EmailAddress {nonce: {nonce}, email: {email}})
|
||||
WHERE NOT (email)-[:BELONGS_TO]->()
|
||||
RETURN email
|
||||
`,
|
||||
{ nonce, email },
|
||||
)
|
||||
const emailAddress = await instance.hydrateFirst(result, 'email', instance.model('Email'))
|
||||
if (!emailAddress) throw new UserInputError('Invalid email or nonce')
|
||||
args = await fileUpload(args, { file: 'avatarUpload', url: 'avatar' })
|
||||
args = await encryptPassword(args)
|
||||
try {
|
||||
const user = await instance.create('User', args)
|
||||
await Promise.all([
|
||||
user.relateTo(emailAddress, 'primaryEmail'),
|
||||
emailAddress.relateTo(user, 'belongsTo'),
|
||||
emailAddress.update({ verifiedAt: new Date().toISOString() }),
|
||||
])
|
||||
return user.toJson()
|
||||
} catch (e) {
|
||||
throw new UserInputError(e.message)
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
404
backend/src/schema/resolvers/registration.spec.js
Normal file
404
backend/src/schema/resolvers/registration.spec.js
Normal file
@ -0,0 +1,404 @@
|
||||
import { GraphQLClient } from 'graphql-request'
|
||||
import Factory from '../../seed/factories'
|
||||
import { host, login } from '../../jest/helpers'
|
||||
import { neode } from '../../bootstrap/neo4j'
|
||||
|
||||
let factory
|
||||
let client
|
||||
let variables
|
||||
let action
|
||||
let userParams
|
||||
const instance = neode()
|
||||
|
||||
beforeEach(async () => {
|
||||
variables = {}
|
||||
factory = Factory()
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await factory.cleanDatabase()
|
||||
})
|
||||
|
||||
describe('CreateInvitationCode', () => {
|
||||
const mutation = `mutation { CreateInvitationCode { token } }`
|
||||
|
||||
it('throws Authorization error', async () => {
|
||||
const client = new GraphQLClient(host)
|
||||
await expect(client.request(mutation)).rejects.toThrow('Not Authorised!')
|
||||
})
|
||||
|
||||
describe('authenticated', () => {
|
||||
beforeEach(async () => {
|
||||
userParams = {
|
||||
id: 'i123',
|
||||
name: 'Inviter',
|
||||
email: 'inviter@example.org',
|
||||
password: '1234',
|
||||
}
|
||||
action = async () => {
|
||||
const factory = Factory()
|
||||
await factory.create('User', userParams)
|
||||
const headers = await login(userParams)
|
||||
client = new GraphQLClient(host, { headers })
|
||||
return client.request(mutation)
|
||||
}
|
||||
})
|
||||
|
||||
it('resolves', async () => {
|
||||
await expect(action()).resolves.toEqual({
|
||||
CreateInvitationCode: { token: expect.any(String) },
|
||||
})
|
||||
})
|
||||
|
||||
it('creates an InvitationCode with a `createdAt` attribute', async () => {
|
||||
await action()
|
||||
const codes = await instance.all('InvitationCode')
|
||||
const invitation = await codes.first().toJson()
|
||||
expect(invitation.createdAt).toBeTruthy()
|
||||
expect(Date.parse(invitation.createdAt)).toEqual(expect.any(Number))
|
||||
})
|
||||
|
||||
it('relates inviting User to InvitationCode', async () => {
|
||||
await action()
|
||||
const result = await instance.cypher(
|
||||
'MATCH(code:InvitationCode)<-[:GENERATED]-(user:User) RETURN user',
|
||||
)
|
||||
const inviter = instance.hydrateFirst(result, 'user', instance.model('User'))
|
||||
await expect(inviter.toJson()).resolves.toEqual(expect.objectContaining({ name: 'Inviter' }))
|
||||
})
|
||||
|
||||
describe('who has invited a lot of users already', () => {
|
||||
beforeEach(() => {
|
||||
action = async () => {
|
||||
const factory = Factory()
|
||||
await factory.create('User', userParams)
|
||||
const headers = await login(userParams)
|
||||
client = new GraphQLClient(host, { headers })
|
||||
await Promise.all(
|
||||
[1, 2, 3].map(() => {
|
||||
return client.request(mutation)
|
||||
}),
|
||||
)
|
||||
return client.request(mutation, variables)
|
||||
}
|
||||
})
|
||||
|
||||
describe('as ordinary `user`', () => {
|
||||
it('throws `Not Authorised` because of maximum number of invitations', async () => {
|
||||
await expect(action()).rejects.toThrow('Not Authorised')
|
||||
})
|
||||
|
||||
it('creates no additional invitation codes', async done => {
|
||||
try {
|
||||
await action()
|
||||
} catch (e) {
|
||||
const invitationCodes = await instance.all('InvitationCode')
|
||||
await expect(invitationCodes.toJson()).resolves.toHaveLength(3)
|
||||
done()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('as a strong donator', () => {
|
||||
beforeEach(() => {
|
||||
// What is the setup?
|
||||
})
|
||||
|
||||
it.todo('can invite more people')
|
||||
// it('can invite more people', async () => {
|
||||
// await action()
|
||||
// const invitationQuery = `{ User { createdAt } }`
|
||||
// const { User: users } = await client.request(invitationQuery )
|
||||
// expect(users).toHaveLength(3 + 1 + 1)
|
||||
// })
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('SignupByInvitation', () => {
|
||||
const mutation = `mutation($email: String!, $token: String!) {
|
||||
SignupByInvitation(email: $email, token: $token) { email }
|
||||
}`
|
||||
|
||||
beforeEach(() => {
|
||||
client = new GraphQLClient(host)
|
||||
action = async () => {
|
||||
return client.request(mutation, variables)
|
||||
}
|
||||
})
|
||||
|
||||
describe('with valid email but invalid InvitationCode', () => {
|
||||
beforeEach(() => {
|
||||
variables.email = 'any-email@example.org'
|
||||
variables.token = 'wut?'
|
||||
})
|
||||
|
||||
it('throws UserInputError', async () => {
|
||||
await expect(action()).rejects.toThrow('Invitation code already used or does not exist.')
|
||||
})
|
||||
})
|
||||
|
||||
describe('with valid InvitationCode', () => {
|
||||
beforeEach(async () => {
|
||||
const inviterParams = {
|
||||
name: 'Inviter',
|
||||
email: 'inviter@example.org',
|
||||
password: '1234',
|
||||
}
|
||||
const factory = Factory()
|
||||
await factory.create('User', inviterParams)
|
||||
const headersOfInviter = await login(inviterParams)
|
||||
const anotherClient = new GraphQLClient(host, { headers: headersOfInviter })
|
||||
const invitationMutation = `mutation { CreateInvitationCode { token } }`
|
||||
const {
|
||||
CreateInvitationCode: { token },
|
||||
} = await anotherClient.request(invitationMutation)
|
||||
variables.token = token
|
||||
})
|
||||
|
||||
describe('given an invalid email', () => {
|
||||
beforeEach(() => {
|
||||
variables.email = 'someuser'
|
||||
})
|
||||
|
||||
it('throws `email is not a valid email`', async () => {
|
||||
await expect(action()).rejects.toThrow('"email" must be a valid email')
|
||||
})
|
||||
|
||||
it('creates no additional EmailAddress node', async done => {
|
||||
try {
|
||||
await action()
|
||||
} catch (e) {
|
||||
let emailAddresses = await instance.all('EmailAddress')
|
||||
emailAddresses = await emailAddresses.toJson
|
||||
expect(emailAddresses).toHaveLength(0)
|
||||
done()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('given a valid email', () => {
|
||||
beforeEach(() => {
|
||||
variables.email = 'someUser@example.org'
|
||||
})
|
||||
|
||||
it('resolves', async () => {
|
||||
await expect(action()).resolves.toEqual({
|
||||
SignupByInvitation: { email: 'someuser@example.org' },
|
||||
})
|
||||
})
|
||||
|
||||
describe('creates a EmailAddress node', () => {
|
||||
it('with a `createdAt` attribute', async () => {
|
||||
await action()
|
||||
let emailAddress = await instance.first('EmailAddress', { email: 'someuser@example.org' })
|
||||
emailAddress = await emailAddress.toJson()
|
||||
expect(emailAddress.createdAt).toBeTruthy()
|
||||
expect(Date.parse(emailAddress.createdAt)).toEqual(expect.any(Number))
|
||||
})
|
||||
|
||||
it('with a cryptographic `nonce`', async () => {
|
||||
await action()
|
||||
let emailAddress = await instance.first('EmailAddress', { email: 'someuser@example.org' })
|
||||
emailAddress = await emailAddress.toJson()
|
||||
expect(emailAddress.nonce).toEqual(expect.any(String))
|
||||
})
|
||||
|
||||
it('connects inviter through invitation code', async () => {
|
||||
await action()
|
||||
const result = await instance.cypher(
|
||||
'MATCH(inviter:User)-[:GENERATED]->(:InvitationCode)-[:ACTIVATED]->(email:EmailAddress {email: {email}}) RETURN inviter',
|
||||
{ email: 'someuser@example.org' },
|
||||
)
|
||||
const inviter = instance.hydrateFirst(result, 'inviter', instance.model('User'))
|
||||
await expect(inviter.toJson()).resolves.toEqual(
|
||||
expect.objectContaining({ name: 'Inviter' }),
|
||||
)
|
||||
})
|
||||
|
||||
describe('using the same InvitationCode twice', () => {
|
||||
it('rejects because codes can be used only once', async done => {
|
||||
await action()
|
||||
try {
|
||||
variables.email = 'yetanotheremail@example.org'
|
||||
await action()
|
||||
} catch (e) {
|
||||
expect(e.message).toMatch(/Invitation code already used/)
|
||||
done()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('if a user account with the given email already exists', () => {
|
||||
beforeEach(async () => {
|
||||
await factory.create('User', { email: 'someuser@example.org' })
|
||||
})
|
||||
|
||||
it('throws unique violation error', async () => {
|
||||
await expect(action()).rejects.toThrow('User account with this email already exists.')
|
||||
})
|
||||
})
|
||||
|
||||
describe('if the EmailAddress already exists but without user account', () => {
|
||||
// shall we re-send the registration email?
|
||||
it.todo('decide what to do')
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('Signup', () => {
|
||||
const mutation = `mutation($email: String!) {
|
||||
Signup(email: $email) { email }
|
||||
}`
|
||||
|
||||
it('throws AuthorizationError', async () => {
|
||||
client = new GraphQLClient(host)
|
||||
await expect(
|
||||
client.request(mutation, { email: 'get-me-a-user-account@example.org' }),
|
||||
).rejects.toThrow('Not Authorised')
|
||||
})
|
||||
|
||||
describe('as admin', () => {
|
||||
beforeEach(async () => {
|
||||
userParams = {
|
||||
role: 'admin',
|
||||
email: 'admin@example.org',
|
||||
password: '1234',
|
||||
}
|
||||
variables.email = 'someuser@example.org'
|
||||
const factory = Factory()
|
||||
await factory.create('User', userParams)
|
||||
const headers = await login(userParams)
|
||||
client = new GraphQLClient(host, { headers })
|
||||
action = async () => {
|
||||
return client.request(mutation, variables)
|
||||
}
|
||||
})
|
||||
|
||||
it('is allowed to signup users by email', async () => {
|
||||
await expect(action()).resolves.toEqual({ Signup: { email: 'someuser@example.org' } })
|
||||
})
|
||||
|
||||
it('creates a Signup with a cryptographic `nonce`', async () => {
|
||||
await action()
|
||||
let emailAddress = await instance.first('EmailAddress', { email: 'someuser@example.org' })
|
||||
emailAddress = await emailAddress.toJson()
|
||||
expect(emailAddress.nonce).toEqual(expect.any(String))
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('SignupVerification', () => {
|
||||
const mutation = `
|
||||
mutation($name: String!, $password: String!, $email: String!, $nonce: String!) {
|
||||
SignupVerification(name: $name, password: $password, email: $email, nonce: $nonce) {
|
||||
id
|
||||
}
|
||||
}
|
||||
`
|
||||
describe('given valid password and email', () => {
|
||||
let variables = {
|
||||
nonce: '123456',
|
||||
name: 'John Doe',
|
||||
password: '123',
|
||||
email: 'john@example.org',
|
||||
}
|
||||
|
||||
describe('unauthenticated', () => {
|
||||
beforeEach(async () => {
|
||||
client = new GraphQLClient(host)
|
||||
})
|
||||
|
||||
describe('EmailAddress exists, but is already related to a user account', () => {
|
||||
beforeEach(async () => {
|
||||
const { email, nonce } = variables
|
||||
const [emailAddress, user] = await Promise.all([
|
||||
instance.model('EmailAddress').create({ email, nonce }),
|
||||
instance
|
||||
.model('User')
|
||||
.create({ name: 'Somebody', password: '1234', email: 'john@example.org' }),
|
||||
])
|
||||
await emailAddress.relateTo(user, 'belongsTo')
|
||||
})
|
||||
|
||||
describe('sending a valid nonce', () => {
|
||||
beforeEach(() => {
|
||||
variables.nonce = '123456'
|
||||
})
|
||||
|
||||
it('rejects', async () => {
|
||||
await expect(client.request(mutation, variables)).rejects.toThrow(
|
||||
'Invalid email or nonce',
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('disconnected EmailAddress exists', () => {
|
||||
beforeEach(async () => {
|
||||
const args = {
|
||||
email: 'john@example.org',
|
||||
nonce: '123456',
|
||||
}
|
||||
await instance.model('EmailAddress').create(args)
|
||||
})
|
||||
|
||||
describe('sending a valid nonce', () => {
|
||||
it('creates a user account', async () => {
|
||||
const expected = {
|
||||
SignupVerification: {
|
||||
id: expect.any(String),
|
||||
},
|
||||
}
|
||||
await expect(client.request(mutation, variables)).resolves.toEqual(expected)
|
||||
})
|
||||
|
||||
it('sets `verifiedAt` attribute of EmailAddress', async () => {
|
||||
await client.request(mutation, variables)
|
||||
const email = await instance.first('EmailAddress', { email: 'john@example.org' })
|
||||
await expect(email.toJson()).resolves.toEqual(
|
||||
expect.objectContaining({
|
||||
verifiedAt: expect.any(String),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('connects User with EmailAddress', async () => {
|
||||
const cypher = `
|
||||
MATCH(email:EmailAddress)-[:BELONGS_TO]->(u:User {name: {name}})
|
||||
RETURN email
|
||||
`
|
||||
await client.request(mutation, variables)
|
||||
const { records: emails } = await instance.cypher(cypher, { name: 'John Doe' })
|
||||
expect(emails).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('marks the EmailAddress as primary', async () => {
|
||||
const cypher = `
|
||||
MATCH(email:EmailAddress)<-[:PRIMARY_EMAIL]-(u:User {name: {name}})
|
||||
RETURN email
|
||||
`
|
||||
await client.request(mutation, variables)
|
||||
const { records: emails } = await instance.cypher(cypher, { name: 'John Doe' })
|
||||
expect(emails).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('sending invalid nonce', () => {
|
||||
beforeEach(() => {
|
||||
variables.nonce = 'wut2'
|
||||
})
|
||||
|
||||
it('rejects', async () => {
|
||||
await expect(client.request(mutation, variables)).rejects.toThrow(
|
||||
'Invalid email or nonce',
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
@ -11,12 +11,31 @@ export default {
|
||||
description: description,
|
||||
}
|
||||
|
||||
const reportQueryRes = await session.run(
|
||||
`
|
||||
match (u:User {id:$submitterId}) -[:REPORTED]->(report)-[:REPORTED]-> (resource {id: $resourceId})
|
||||
return labels(resource)[0] as label
|
||||
`,
|
||||
{
|
||||
resourceId: id,
|
||||
submitterId: user.id,
|
||||
},
|
||||
)
|
||||
const [rep] = reportQueryRes.records.map(record => {
|
||||
return {
|
||||
label: record.get('label'),
|
||||
}
|
||||
})
|
||||
|
||||
if (rep) {
|
||||
throw new Error(rep.label)
|
||||
}
|
||||
const res = await session.run(
|
||||
`
|
||||
MATCH (submitter:User {id: $userId})
|
||||
MATCH (resource {id: $resourceId})
|
||||
WHERE resource:User OR resource:Comment OR resource:Post
|
||||
CREATE (report:Report $reportData)
|
||||
MERGE (report:Report {id: {reportData}.id })
|
||||
MERGE (resource)<-[:REPORTED]-(report)
|
||||
MERGE (report)<-[:REPORTED]-(submitter)
|
||||
RETURN report, submitter, resource, labels(resource)[0] as type
|
||||
@ -27,6 +46,7 @@ export default {
|
||||
reportData,
|
||||
},
|
||||
)
|
||||
|
||||
session.close()
|
||||
|
||||
const [dbResponse] = res.records.map(r => {
|
||||
@ -59,6 +79,7 @@ export default {
|
||||
response.user = resource.properties
|
||||
break
|
||||
}
|
||||
|
||||
return response
|
||||
},
|
||||
},
|
||||
|
||||
@ -13,7 +13,9 @@ describe('report', () => {
|
||||
|
||||
beforeEach(async () => {
|
||||
returnedObject = '{ description }'
|
||||
variables = { id: 'whatever' }
|
||||
variables = {
|
||||
id: 'whatever',
|
||||
}
|
||||
headers = {}
|
||||
await factory.create('User', {
|
||||
id: 'u1',
|
||||
@ -42,7 +44,9 @@ describe('report', () => {
|
||||
) ${returnedObject}
|
||||
}
|
||||
`
|
||||
client = new GraphQLClient(host, { headers })
|
||||
client = new GraphQLClient(host, {
|
||||
headers,
|
||||
})
|
||||
return client.request(mutation, variables)
|
||||
}
|
||||
|
||||
@ -53,7 +57,10 @@ describe('report', () => {
|
||||
|
||||
describe('authenticated', () => {
|
||||
beforeEach(async () => {
|
||||
headers = await login({ email: 'test@example.org', password: '1234' })
|
||||
headers = await login({
|
||||
email: 'test@example.org',
|
||||
password: '1234',
|
||||
})
|
||||
})
|
||||
|
||||
describe('invalid resource id', () => {
|
||||
@ -66,19 +73,25 @@ describe('report', () => {
|
||||
|
||||
describe('valid resource id', () => {
|
||||
beforeEach(async () => {
|
||||
variables = { id: 'u2' }
|
||||
variables = {
|
||||
id: 'u2',
|
||||
}
|
||||
})
|
||||
|
||||
it('creates a report', async () => {
|
||||
await expect(action()).resolves.toEqual({
|
||||
report: { description: 'Violates code of conduct' },
|
||||
})
|
||||
})
|
||||
|
||||
/*
|
||||
it('creates a report', async () => {
|
||||
await expect(action()).resolves.toEqual({
|
||||
type: null,
|
||||
})
|
||||
})
|
||||
*/
|
||||
it('returns the submitter', async () => {
|
||||
returnedObject = '{ submitter { email } }'
|
||||
await expect(action()).resolves.toEqual({
|
||||
report: { submitter: { email: 'test@example.org' } },
|
||||
report: {
|
||||
submitter: {
|
||||
email: 'test@example.org',
|
||||
},
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
@ -86,50 +99,72 @@ describe('report', () => {
|
||||
it('returns type "User"', async () => {
|
||||
returnedObject = '{ type }'
|
||||
await expect(action()).resolves.toEqual({
|
||||
report: { type: 'User' },
|
||||
report: {
|
||||
type: 'User',
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('returns resource in user attribute', async () => {
|
||||
returnedObject = '{ user { name } }'
|
||||
await expect(action()).resolves.toEqual({
|
||||
report: { user: { name: 'abusive-user' } },
|
||||
report: {
|
||||
user: {
|
||||
name: 'abusive-user',
|
||||
},
|
||||
},
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('reported resource is a post', () => {
|
||||
beforeEach(async () => {
|
||||
await factory.authenticateAs({ email: 'test@example.org', password: '1234' })
|
||||
await factory.authenticateAs({
|
||||
email: 'test@example.org',
|
||||
password: '1234',
|
||||
})
|
||||
await factory.create('Post', {
|
||||
id: 'p23',
|
||||
title: 'Matt and Robert having a pair-programming',
|
||||
})
|
||||
variables = { id: 'p23' }
|
||||
variables = {
|
||||
id: 'p23',
|
||||
}
|
||||
})
|
||||
|
||||
it('returns type "Post"', async () => {
|
||||
returnedObject = '{ type }'
|
||||
await expect(action()).resolves.toEqual({
|
||||
report: { type: 'Post' },
|
||||
report: {
|
||||
type: 'Post',
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('returns resource in post attribute', async () => {
|
||||
returnedObject = '{ post { title } }'
|
||||
await expect(action()).resolves.toEqual({
|
||||
report: { post: { title: 'Matt and Robert having a pair-programming' } },
|
||||
report: {
|
||||
post: {
|
||||
title: 'Matt and Robert having a pair-programming',
|
||||
},
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('returns null in user attribute', async () => {
|
||||
returnedObject = '{ user { name } }'
|
||||
await expect(action()).resolves.toEqual({
|
||||
report: { user: null },
|
||||
report: {
|
||||
user: null,
|
||||
},
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
/* An der Stelle würde ich den p23 noch mal prüfen, diesmal muss aber eine error meldung kommen.
|
||||
At this point I would check the p23 again, but this time there must be an error message. */
|
||||
|
||||
describe('reported resource is a comment', () => {
|
||||
beforeEach(async () => {
|
||||
createPostVariables = {
|
||||
@ -147,34 +182,54 @@ describe('report', () => {
|
||||
id: 'c34',
|
||||
content: 'Robert getting tired.',
|
||||
})
|
||||
variables = { id: 'c34' }
|
||||
variables = {
|
||||
id: 'c34',
|
||||
}
|
||||
})
|
||||
|
||||
it('returns type "Comment"', async () => {
|
||||
returnedObject = '{ type }'
|
||||
await expect(action()).resolves.toEqual({
|
||||
report: { type: 'Comment' },
|
||||
report: {
|
||||
type: 'Comment',
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('returns resource in comment attribute', async () => {
|
||||
returnedObject = '{ comment { content } }'
|
||||
await expect(action()).resolves.toEqual({
|
||||
report: { comment: { content: 'Robert getting tired.' } },
|
||||
report: {
|
||||
comment: {
|
||||
content: 'Robert getting tired.',
|
||||
},
|
||||
},
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
/* An der Stelle würde ich den c34 noch mal prüfen, diesmal muss aber eine error meldung kommen.
|
||||
At this point I would check the c34 again, but this time there must be an error message. */
|
||||
|
||||
describe('reported resource is a tag', () => {
|
||||
beforeEach(async () => {
|
||||
await factory.create('Tag', { id: 't23' })
|
||||
variables = { id: 't23' }
|
||||
await factory.create('Tag', {
|
||||
id: 't23',
|
||||
})
|
||||
variables = {
|
||||
id: 't23',
|
||||
}
|
||||
})
|
||||
|
||||
it('returns null', async () => {
|
||||
await expect(action()).resolves.toEqual({ report: null })
|
||||
await expect(action()).resolves.toEqual({
|
||||
report: null,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
/* An der Stelle würde ich den t23 noch mal prüfen, diesmal muss aber eine error meldung kommen.
|
||||
At this point I would check the t23 again, but this time there must be an error message. */
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@ -1,47 +1,47 @@
|
||||
import { neode } from '../../bootstrap/neo4j'
|
||||
import { UserInputError } from 'apollo-server'
|
||||
|
||||
const instance = neode()
|
||||
|
||||
const getUserAndBadge = async ({ badgeKey, userId }) => {
|
||||
let user = await instance.first('User', 'id', userId)
|
||||
const badge = await instance.first('Badge', 'id', badgeKey)
|
||||
if (!user) throw new UserInputError("Couldn't find a user with that id")
|
||||
if (!badge) throw new UserInputError("Couldn't find a badge with that id")
|
||||
return { user, badge }
|
||||
}
|
||||
|
||||
export default {
|
||||
Mutation: {
|
||||
reward: async (_object, params, context, _resolveInfo) => {
|
||||
const { fromBadgeId, toUserId } = params
|
||||
const session = context.driver.session()
|
||||
|
||||
let transactionRes = await session.run(
|
||||
`MATCH (badge:Badge {id: $badgeId}), (rewardedUser:User {id: $rewardedUserId})
|
||||
MERGE (badge)-[:REWARDED]->(rewardedUser)
|
||||
RETURN rewardedUser {.id}`,
|
||||
{
|
||||
badgeId: fromBadgeId,
|
||||
rewardedUserId: toUserId,
|
||||
},
|
||||
)
|
||||
|
||||
const [rewardedUser] = transactionRes.records.map(record => {
|
||||
return record.get('rewardedUser')
|
||||
})
|
||||
|
||||
session.close()
|
||||
|
||||
return rewardedUser.id
|
||||
const { user, badge } = await getUserAndBadge(params)
|
||||
await user.relateTo(badge, 'rewarded')
|
||||
return user.toJson()
|
||||
},
|
||||
|
||||
unreward: async (_object, params, context, _resolveInfo) => {
|
||||
const { fromBadgeId, toUserId } = params
|
||||
const { badgeKey, userId } = params
|
||||
const { user } = await getUserAndBadge(params)
|
||||
const session = context.driver.session()
|
||||
|
||||
let transactionRes = await session.run(
|
||||
`MATCH (badge:Badge {id: $badgeId})-[reward:REWARDED]->(rewardedUser:User {id: $rewardedUserId})
|
||||
DELETE reward
|
||||
RETURN rewardedUser {.id}`,
|
||||
{
|
||||
badgeId: fromBadgeId,
|
||||
rewardedUserId: toUserId,
|
||||
},
|
||||
)
|
||||
const [rewardedUser] = transactionRes.records.map(record => {
|
||||
return record.get('rewardedUser')
|
||||
})
|
||||
session.close()
|
||||
|
||||
return rewardedUser.id
|
||||
try {
|
||||
// silly neode cannot remove relationships
|
||||
await session.run(
|
||||
`
|
||||
MATCH (badge:Badge {id: $badgeKey})-[reward:REWARDED]->(rewardedUser:User {id: $userId})
|
||||
DELETE reward
|
||||
RETURN rewardedUser
|
||||
`,
|
||||
{
|
||||
badgeKey,
|
||||
userId,
|
||||
},
|
||||
)
|
||||
} catch (err) {
|
||||
throw err
|
||||
} finally {
|
||||
session.close()
|
||||
}
|
||||
return user.toJson()
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
@ -1,12 +1,19 @@
|
||||
import { GraphQLClient } from 'graphql-request'
|
||||
import Factory from '../../seed/factories'
|
||||
import { host, login } from '../../jest/helpers'
|
||||
import { host, login, gql } from '../../jest/helpers'
|
||||
|
||||
const factory = Factory()
|
||||
let user
|
||||
let badge
|
||||
|
||||
describe('rewards', () => {
|
||||
const variables = {
|
||||
from: 'indiegogo_en_rhino',
|
||||
to: 'u1',
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
await factory.create('User', {
|
||||
user = await factory.create('User', {
|
||||
id: 'u1',
|
||||
role: 'user',
|
||||
email: 'user@example.org',
|
||||
@ -22,9 +29,8 @@ describe('rewards', () => {
|
||||
role: 'admin',
|
||||
email: 'admin@example.org',
|
||||
})
|
||||
await factory.create('Badge', {
|
||||
id: 'b6',
|
||||
key: 'indiegogo_en_rhino',
|
||||
badge = await factory.create('Badge', {
|
||||
id: 'indiegogo_en_rhino',
|
||||
type: 'crowdfunding',
|
||||
status: 'permanent',
|
||||
icon: '/img/badges/indiegogo_en_rhino.svg',
|
||||
@ -35,21 +41,19 @@ describe('rewards', () => {
|
||||
await factory.cleanDatabase()
|
||||
})
|
||||
|
||||
describe('RewardBadge', () => {
|
||||
const mutation = `
|
||||
mutation(
|
||||
$from: ID!
|
||||
$to: ID!
|
||||
) {
|
||||
reward(fromBadgeId: $from, toUserId: $to)
|
||||
describe('reward', () => {
|
||||
const mutation = gql`
|
||||
mutation($from: ID!, $to: ID!) {
|
||||
reward(badgeKey: $from, userId: $to) {
|
||||
id
|
||||
badges {
|
||||
id
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
describe('unauthenticated', () => {
|
||||
const variables = {
|
||||
from: 'b6',
|
||||
to: 'u1',
|
||||
}
|
||||
let client
|
||||
|
||||
it('throws authorization error', async () => {
|
||||
@ -65,74 +69,95 @@ describe('rewards', () => {
|
||||
client = new GraphQLClient(host, { headers })
|
||||
})
|
||||
|
||||
describe('badge for id does not exist', () => {
|
||||
it('rejects with a telling error message', async () => {
|
||||
await expect(
|
||||
client.request(mutation, {
|
||||
...variables,
|
||||
from: 'bullshit',
|
||||
}),
|
||||
).rejects.toThrow("Couldn't find a badge with that id")
|
||||
})
|
||||
})
|
||||
|
||||
describe('user for id does not exist', () => {
|
||||
it('rejects with a telling error message', async () => {
|
||||
await expect(
|
||||
client.request(mutation, {
|
||||
...variables,
|
||||
to: 'bullshit',
|
||||
}),
|
||||
).rejects.toThrow("Couldn't find a user with that id")
|
||||
})
|
||||
})
|
||||
|
||||
it('rewards a badge to user', async () => {
|
||||
const variables = {
|
||||
from: 'b6',
|
||||
to: 'u1',
|
||||
}
|
||||
const expected = {
|
||||
reward: 'u1',
|
||||
reward: {
|
||||
id: 'u1',
|
||||
badges: [{ id: 'indiegogo_en_rhino' }],
|
||||
},
|
||||
}
|
||||
await expect(client.request(mutation, variables)).resolves.toEqual(expected)
|
||||
})
|
||||
|
||||
it('rewards a second different badge to same user', async () => {
|
||||
await factory.create('Badge', {
|
||||
id: 'b1',
|
||||
key: 'indiegogo_en_racoon',
|
||||
type: 'crowdfunding',
|
||||
status: 'permanent',
|
||||
id: 'indiegogo_en_racoon',
|
||||
icon: '/img/badges/indiegogo_en_racoon.svg',
|
||||
})
|
||||
const variables = {
|
||||
from: 'b1',
|
||||
to: 'u1',
|
||||
}
|
||||
const badges = [{ id: 'indiegogo_en_racoon' }, { id: 'indiegogo_en_rhino' }]
|
||||
const expected = {
|
||||
reward: 'u1',
|
||||
reward: {
|
||||
id: 'u1',
|
||||
badges: expect.arrayContaining(badges),
|
||||
},
|
||||
}
|
||||
await expect(client.request(mutation, variables)).resolves.toEqual(expected)
|
||||
await client.request(mutation, variables)
|
||||
await expect(
|
||||
client.request(mutation, {
|
||||
...variables,
|
||||
from: 'indiegogo_en_racoon',
|
||||
}),
|
||||
).resolves.toEqual(expected)
|
||||
})
|
||||
|
||||
it('rewards the same badge as well to another user', async () => {
|
||||
const variables1 = {
|
||||
from: 'b6',
|
||||
to: 'u1',
|
||||
}
|
||||
await client.request(mutation, variables1)
|
||||
|
||||
const variables2 = {
|
||||
from: 'b6',
|
||||
to: 'u2',
|
||||
}
|
||||
const expected = {
|
||||
reward: 'u2',
|
||||
reward: {
|
||||
id: 'u2',
|
||||
badges: [{ id: 'indiegogo_en_rhino' }],
|
||||
},
|
||||
}
|
||||
await expect(client.request(mutation, variables2)).resolves.toEqual(expected)
|
||||
await expect(
|
||||
client.request(mutation, {
|
||||
...variables,
|
||||
to: 'u2',
|
||||
}),
|
||||
).resolves.toEqual(expected)
|
||||
})
|
||||
it('returns the original reward if a reward is attempted a second time', async () => {
|
||||
const variables = {
|
||||
from: 'b6',
|
||||
to: 'u1',
|
||||
}
|
||||
|
||||
it('creates no duplicate reward relationships', async () => {
|
||||
await client.request(mutation, variables)
|
||||
await client.request(mutation, variables)
|
||||
|
||||
const query = `{
|
||||
User( id: "u1" ) {
|
||||
badgesCount
|
||||
const query = gql`
|
||||
{
|
||||
User(id: "u1") {
|
||||
badgesCount
|
||||
badges {
|
||||
id
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
const expected = { User: [{ badgesCount: 1 }] }
|
||||
const expected = { User: [{ badgesCount: 1, badges: [{ id: 'indiegogo_en_rhino' }] }] }
|
||||
|
||||
await expect(client.request(query)).resolves.toEqual(expected)
|
||||
})
|
||||
})
|
||||
|
||||
describe('authenticated moderator', () => {
|
||||
const variables = {
|
||||
from: 'b6',
|
||||
to: 'u1',
|
||||
}
|
||||
let client
|
||||
beforeEach(async () => {
|
||||
const headers = await login({ email: 'moderator@example.org', password: '1234' })
|
||||
@ -147,27 +172,41 @@ describe('rewards', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('RemoveReward', () => {
|
||||
describe('unreward', () => {
|
||||
beforeEach(async () => {
|
||||
await factory.relate('User', 'Badges', { from: 'b6', to: 'u1' })
|
||||
await user.relateTo(badge, 'rewarded')
|
||||
})
|
||||
const variables = {
|
||||
from: 'b6',
|
||||
to: 'u1',
|
||||
}
|
||||
const expected = {
|
||||
unreward: 'u1',
|
||||
}
|
||||
const expected = { unreward: { id: 'u1', badges: [] } }
|
||||
|
||||
const mutation = `
|
||||
mutation(
|
||||
$from: ID!
|
||||
$to: ID!
|
||||
) {
|
||||
unreward(fromBadgeId: $from, toUserId: $to)
|
||||
const mutation = gql`
|
||||
mutation($from: ID!, $to: ID!) {
|
||||
unreward(badgeKey: $from, userId: $to) {
|
||||
id
|
||||
badges {
|
||||
id
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
describe('check test setup', () => {
|
||||
it('user has one badge', async () => {
|
||||
const query = gql`
|
||||
{
|
||||
User(id: "u1") {
|
||||
badgesCount
|
||||
badges {
|
||||
id
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
const expected = { User: [{ badgesCount: 1, badges: [{ id: 'indiegogo_en_rhino' }] }] }
|
||||
const client = new GraphQLClient(host)
|
||||
await expect(client.request(query)).resolves.toEqual(expected)
|
||||
})
|
||||
})
|
||||
|
||||
describe('unauthenticated', () => {
|
||||
let client
|
||||
|
||||
@ -188,12 +227,9 @@ describe('rewards', () => {
|
||||
await expect(client.request(mutation, variables)).resolves.toEqual(expected)
|
||||
})
|
||||
|
||||
it('fails to remove a not existing badge from user', async () => {
|
||||
it('does not crash when unrewarding multiple times', async () => {
|
||||
await client.request(mutation, variables)
|
||||
|
||||
await expect(client.request(mutation, variables)).rejects.toThrow(
|
||||
"Cannot read property 'id' of undefined",
|
||||
)
|
||||
await expect(client.request(mutation, variables)).resolves.toEqual(expected)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@ -1,7 +1,6 @@
|
||||
import gql from 'graphql-tag'
|
||||
import { GraphQLClient } from 'graphql-request'
|
||||
import Factory from '../../seed/factories'
|
||||
import { host, login } from '../../jest/helpers'
|
||||
import { host, login, gql } from '../../jest/helpers'
|
||||
|
||||
const factory = Factory()
|
||||
|
||||
@ -98,14 +97,19 @@ describe('SocialMedia', () => {
|
||||
const variables = {
|
||||
url: '',
|
||||
}
|
||||
await expect(client.request(mutationC, variables)).rejects.toThrow('Input is not a URL')
|
||||
await expect(client.request(mutationC, variables)).rejects.toThrow(
|
||||
'"url" is not allowed to be empty',
|
||||
)
|
||||
})
|
||||
|
||||
it('validates URLs', async () => {
|
||||
const variables = {
|
||||
url: 'not-a-url',
|
||||
}
|
||||
await expect(client.request(mutationC, variables)).rejects.toThrow('Input is not a URL')
|
||||
|
||||
await expect(client.request(mutationC, variables)).rejects.toThrow(
|
||||
'"url" must be a valid uri',
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@ -2,10 +2,13 @@ import encode from '../../jwt/encode'
|
||||
import bcrypt from 'bcryptjs'
|
||||
import { AuthenticationError } from 'apollo-server'
|
||||
import { neo4jgraphql } from 'neo4j-graphql-js'
|
||||
import { neode } from '../../bootstrap/neo4j'
|
||||
|
||||
const instance = neode()
|
||||
|
||||
export default {
|
||||
Query: {
|
||||
isLoggedIn: (parent, args, { driver, user }) => {
|
||||
isLoggedIn: (_, args, { driver, user }) => {
|
||||
return Boolean(user && user.id)
|
||||
},
|
||||
currentUser: async (object, params, ctx, resolveInfo) => {
|
||||
@ -15,40 +18,29 @@ export default {
|
||||
},
|
||||
},
|
||||
Mutation: {
|
||||
signup: async (parent, { email, password }, { req }) => {
|
||||
// if (data[email]) {
|
||||
// throw new Error('Another User with same email exists.')
|
||||
// }
|
||||
// data[email] = {
|
||||
// password: await bcrypt.hashSync(password, 10),
|
||||
// }
|
||||
|
||||
return true
|
||||
},
|
||||
login: async (parent, { email, password }, { driver, req, user }) => {
|
||||
login: async (_, { email, password }, { driver, req, user }) => {
|
||||
// if (user && user.id) {
|
||||
// throw new Error('Already logged in.')
|
||||
// }
|
||||
const session = driver.session()
|
||||
const result = await session.run(
|
||||
'MATCH (user:User {email: $userEmail}) ' +
|
||||
'RETURN user {.id, .slug, .name, .avatar, .email, .password, .role, .disabled} as user LIMIT 1',
|
||||
'MATCH (user:User)-[:PRIMARY_EMAIL]->(e:EmailAddress {email: $userEmail})' +
|
||||
'RETURN user {.id, .slug, .name, .avatar, .encryptedPassword, .role, .disabled, email:e.email} as user LIMIT 1',
|
||||
{
|
||||
userEmail: email,
|
||||
},
|
||||
)
|
||||
|
||||
session.close()
|
||||
const [currentUser] = await result.records.map(function(record) {
|
||||
const [currentUser] = await result.records.map(record => {
|
||||
return record.get('user')
|
||||
})
|
||||
|
||||
if (
|
||||
currentUser &&
|
||||
(await bcrypt.compareSync(password, currentUser.password)) &&
|
||||
(await bcrypt.compareSync(password, currentUser.encryptedPassword)) &&
|
||||
!currentUser.disabled
|
||||
) {
|
||||
delete currentUser.password
|
||||
delete currentUser.encryptedPassword
|
||||
return encode(currentUser)
|
||||
} else if (currentUser && currentUser.disabled) {
|
||||
throw new AuthenticationError('Your account has been disabled.')
|
||||
@ -57,41 +49,24 @@ export default {
|
||||
}
|
||||
},
|
||||
changePassword: async (_, { oldPassword, newPassword }, { driver, user }) => {
|
||||
const session = driver.session()
|
||||
let result = await session.run(
|
||||
`MATCH (user:User {email: $userEmail})
|
||||
RETURN user {.id, .email, .password}`,
|
||||
{
|
||||
userEmail: user.email,
|
||||
},
|
||||
)
|
||||
let currentUser = await instance.find('User', user.id)
|
||||
|
||||
const [currentUser] = result.records.map(function(record) {
|
||||
return record.get('user')
|
||||
})
|
||||
|
||||
if (!(await bcrypt.compareSync(oldPassword, currentUser.password))) {
|
||||
const encryptedPassword = currentUser.get('encryptedPassword')
|
||||
if (!(await bcrypt.compareSync(oldPassword, encryptedPassword))) {
|
||||
throw new AuthenticationError('Old password is not correct')
|
||||
}
|
||||
|
||||
if (await bcrypt.compareSync(newPassword, currentUser.password)) {
|
||||
if (await bcrypt.compareSync(newPassword, encryptedPassword)) {
|
||||
throw new AuthenticationError('Old password and new password should be different')
|
||||
} else {
|
||||
const newHashedPassword = await bcrypt.hashSync(newPassword, 10)
|
||||
session.run(
|
||||
`MATCH (user:User {email: $userEmail})
|
||||
SET user.password = $newHashedPassword
|
||||
RETURN user
|
||||
`,
|
||||
{
|
||||
userEmail: user.email,
|
||||
newHashedPassword,
|
||||
},
|
||||
)
|
||||
session.close()
|
||||
|
||||
return encode(currentUser)
|
||||
}
|
||||
|
||||
const newEncryptedPassword = await bcrypt.hashSync(newPassword, 10)
|
||||
await currentUser.update({
|
||||
encryptedPassword: newEncryptedPassword,
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
return encode(await currentUser.toJson())
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
@ -1,4 +1,3 @@
|
||||
import gql from 'graphql-tag'
|
||||
import { GraphQLClient, request } from 'graphql-request'
|
||||
import jwt from 'jsonwebtoken'
|
||||
import CONFIG from './../../config'
|
||||
@ -311,121 +310,3 @@ describe('change password', () => {
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('do not expose private RSA key', () => {
|
||||
let headers
|
||||
let client
|
||||
let authenticatedClient
|
||||
|
||||
const queryUserPuplicKey = gql`
|
||||
query($queriedUserSlug: String) {
|
||||
User(slug: $queriedUserSlug) {
|
||||
id
|
||||
publicKey
|
||||
}
|
||||
}
|
||||
`
|
||||
const queryUserPrivateKey = gql`
|
||||
query($queriedUserSlug: String) {
|
||||
User(slug: $queriedUserSlug) {
|
||||
id
|
||||
privateKey
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
const generateUserWithKeys = async authenticatedClient => {
|
||||
// Generate user with "privateKey" via 'CreateUser' mutation instead of using the factories "factory.create('User', {...})", see above.
|
||||
const variables = {
|
||||
id: 'bcb2d923-f3af-479e-9f00-61b12e864667',
|
||||
password: 'xYz',
|
||||
slug: 'apfel-strudel',
|
||||
name: 'Apfel Strudel',
|
||||
email: 'apfel-strudel@test.org',
|
||||
}
|
||||
await authenticatedClient.request(
|
||||
gql`
|
||||
mutation($id: ID, $password: String!, $slug: String, $name: String, $email: String!) {
|
||||
CreateUser(id: $id, password: $password, slug: $slug, name: $name, email: $email) {
|
||||
id
|
||||
}
|
||||
}
|
||||
`,
|
||||
variables,
|
||||
)
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
const adminParams = {
|
||||
role: 'admin',
|
||||
email: 'admin@example.org',
|
||||
password: '1234',
|
||||
}
|
||||
// create an admin user who has enough permissions to create other users
|
||||
await factory.create('User', adminParams)
|
||||
const headers = await login(adminParams)
|
||||
authenticatedClient = new GraphQLClient(host, { headers })
|
||||
// but also create an unauthenticated client to issue the `User` query
|
||||
client = new GraphQLClient(host)
|
||||
})
|
||||
|
||||
describe('unauthenticated query of "publicKey" (does the RSA key pair get generated at all?)', () => {
|
||||
it('returns publicKey', async () => {
|
||||
await generateUserWithKeys(authenticatedClient)
|
||||
await expect(
|
||||
await client.request(queryUserPuplicKey, { queriedUserSlug: 'apfel-strudel' }),
|
||||
).toEqual(
|
||||
expect.objectContaining({
|
||||
User: [
|
||||
{
|
||||
id: 'bcb2d923-f3af-479e-9f00-61b12e864667',
|
||||
publicKey: expect.any(String),
|
||||
},
|
||||
],
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('unauthenticated query of "privateKey"', () => {
|
||||
it('throws "Not Authorised!"', async () => {
|
||||
await generateUserWithKeys(authenticatedClient)
|
||||
await expect(
|
||||
client.request(queryUserPrivateKey, { queriedUserSlug: 'apfel-strudel' }),
|
||||
).rejects.toThrow('Not Authorised')
|
||||
})
|
||||
})
|
||||
|
||||
// authenticate
|
||||
beforeEach(async () => {
|
||||
headers = await login({ email: 'test@example.org', password: '1234' })
|
||||
client = new GraphQLClient(host, { headers })
|
||||
})
|
||||
|
||||
describe('authenticated query of "publicKey"', () => {
|
||||
it('returns publicKey', async () => {
|
||||
await generateUserWithKeys(authenticatedClient)
|
||||
await expect(
|
||||
await client.request(queryUserPuplicKey, { queriedUserSlug: 'apfel-strudel' }),
|
||||
).toEqual(
|
||||
expect.objectContaining({
|
||||
User: [
|
||||
{
|
||||
id: 'bcb2d923-f3af-479e-9f00-61b12e864667',
|
||||
publicKey: expect.any(String),
|
||||
},
|
||||
],
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('authenticated query of "privateKey"', () => {
|
||||
it('throws "Not Authorised!"', async () => {
|
||||
await generateUserWithKeys(authenticatedClient)
|
||||
await expect(
|
||||
client.request(queryUserPrivateKey, { queriedUserSlug: 'apfel-strudel' }),
|
||||
).rejects.toThrow('Not Authorised')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@ -1,15 +1,91 @@
|
||||
import { neo4jgraphql } from 'neo4j-graphql-js'
|
||||
import fileUpload from './fileUpload'
|
||||
import { neode } from '../../bootstrap/neo4j'
|
||||
import { UserInputError } from 'apollo-server'
|
||||
|
||||
const instance = neode()
|
||||
|
||||
const _has = (resolvers, { key, connection }, { returnType }) => {
|
||||
return async (parent, params, context, resolveInfo) => {
|
||||
if (typeof parent[key] !== 'undefined') return parent[key]
|
||||
const { id } = parent
|
||||
const statement = `MATCH(u:User {id: {id}})${connection} RETURN related`
|
||||
const result = await instance.cypher(statement, { id })
|
||||
let response = result.records.map(r => r.get('related').properties)
|
||||
if (returnType === 'object') response = response[0] || null
|
||||
return response
|
||||
}
|
||||
}
|
||||
|
||||
const count = obj => {
|
||||
const resolvers = {}
|
||||
for (const [key, connection] of Object.entries(obj)) {
|
||||
resolvers[key] = async (parent, params, context, resolveInfo) => {
|
||||
if (typeof parent[key] !== 'undefined') return parent[key]
|
||||
const { id } = parent
|
||||
const statement = `
|
||||
MATCH(u:User {id: {id}})${connection}
|
||||
WHERE NOT related.deleted = true AND NOT related.disabled = true
|
||||
RETURN COUNT(DISTINCT(related)) as count
|
||||
`
|
||||
const result = await instance.cypher(statement, { id })
|
||||
const [response] = result.records.map(r => r.get('count').toNumber())
|
||||
return response
|
||||
}
|
||||
}
|
||||
return resolvers
|
||||
}
|
||||
|
||||
const undefinedToNull = list => {
|
||||
const resolvers = {}
|
||||
list.forEach(key => {
|
||||
resolvers[key] = async (parent, params, context, resolveInfo) => {
|
||||
return typeof parent[key] === 'undefined' ? null : parent[key]
|
||||
}
|
||||
})
|
||||
return resolvers
|
||||
}
|
||||
|
||||
export const hasMany = obj => {
|
||||
const resolvers = {}
|
||||
for (const [key, connection] of Object.entries(obj)) {
|
||||
resolvers[key] = _has(resolvers, { key, connection }, { returnType: 'iterable' })
|
||||
}
|
||||
return resolvers
|
||||
}
|
||||
|
||||
export const hasOne = obj => {
|
||||
const resolvers = {}
|
||||
for (const [key, connection] of Object.entries(obj)) {
|
||||
resolvers[key] = _has(resolvers, { key, connection }, { returnType: 'object' })
|
||||
}
|
||||
return resolvers
|
||||
}
|
||||
|
||||
export default {
|
||||
Mutation: {
|
||||
UpdateUser: async (object, params, context, resolveInfo) => {
|
||||
params = await fileUpload(params, { file: 'avatarUpload', url: 'avatar' })
|
||||
return neo4jgraphql(object, params, context, resolveInfo, false)
|
||||
Query: {
|
||||
User: async (object, args, context, resolveInfo) => {
|
||||
const { email } = args
|
||||
if (email) {
|
||||
const e = await instance.first('EmailAddress', { email })
|
||||
let user = e.get('belongsTo')
|
||||
user = await user.toJson()
|
||||
return [user.node]
|
||||
}
|
||||
return neo4jgraphql(object, args, context, resolveInfo, false)
|
||||
},
|
||||
CreateUser: async (object, params, context, resolveInfo) => {
|
||||
params = await fileUpload(params, { file: 'avatarUpload', url: 'avatar' })
|
||||
return neo4jgraphql(object, params, context, resolveInfo, false)
|
||||
},
|
||||
Mutation: {
|
||||
UpdateUser: async (object, args, context, resolveInfo) => {
|
||||
args = await fileUpload(args, { file: 'avatarUpload', url: 'avatar' })
|
||||
try {
|
||||
let user = await instance.find('User', args.id)
|
||||
if (!user) return null
|
||||
await user.update(args)
|
||||
return user.toJson()
|
||||
} catch (e) {
|
||||
throw new UserInputError(e.message)
|
||||
}
|
||||
},
|
||||
DeleteUser: async (object, params, context, resolveInfo) => {
|
||||
const { resource } = params
|
||||
@ -34,4 +110,51 @@ export default {
|
||||
return neo4jgraphql(object, params, context, resolveInfo, false)
|
||||
},
|
||||
},
|
||||
User: {
|
||||
email: async (parent, params, context, resolveInfo) => {
|
||||
if (typeof parent.email !== 'undefined') return parent.email
|
||||
const { id } = parent
|
||||
const statement = `MATCH(u:User {id: {id}})-[:PRIMARY_EMAIL]->(e:EmailAddress) RETURN e`
|
||||
const result = await instance.cypher(statement, { id })
|
||||
let [{ email }] = result.records.map(r => r.get('e').properties)
|
||||
return email
|
||||
},
|
||||
...undefinedToNull([
|
||||
'actorId',
|
||||
'avatar',
|
||||
'coverImg',
|
||||
'deleted',
|
||||
'disabled',
|
||||
'locationName',
|
||||
'about',
|
||||
]),
|
||||
...count({
|
||||
contributionsCount: '-[:WROTE]->(related:Post)',
|
||||
friendsCount: '<-[:FRIENDS]->(related:User)',
|
||||
followingCount: '-[:FOLLOWS]->(related:User)',
|
||||
followedByCount: '<-[:FOLLOWS]-(related:User)',
|
||||
commentsCount: '-[:WROTE]->(r:Comment)',
|
||||
commentedCount: '-[:WROTE]->(:Comment)-[:COMMENTS]->(related:Post)',
|
||||
shoutedCount: '-[:SHOUTED]->(related:Post)',
|
||||
badgesCount: '<-[:REWARDED]-(related:Badge)',
|
||||
}),
|
||||
...hasOne({
|
||||
invitedBy: '<-[:INVITED]-(related:User)',
|
||||
disabledBy: '<-[:DISABLED]-(related:User)',
|
||||
}),
|
||||
...hasMany({
|
||||
followedBy: '<-[:FOLLOWS]-(related:User)',
|
||||
following: '-[:FOLLOWS]->(related:User)',
|
||||
friends: '-[:FRIENDS]-(related:User)',
|
||||
blacklisted: '-[:BLACKLISTED]->(related:User)',
|
||||
socialMedia: '-[:OWNED]->(related:SocialMedia)',
|
||||
contributions: '-[:WROTE]->(related:Post)',
|
||||
comments: '-[:WROTE]->(related:Comment)',
|
||||
shouted: '-[:SHOUTED]->(related:Post)',
|
||||
organizationsCreated: '-[:CREATED_ORGA]->(related:Organization)',
|
||||
organizationsOwned: '-[:OWNING_ORGA]->(related:Organization)',
|
||||
categories: '-[:CATEGORIZED]->(related:Category)',
|
||||
badges: '<-[:REWARDED]-(related:Badge)',
|
||||
}),
|
||||
},
|
||||
}
|
||||
|
||||
@ -1,7 +1,6 @@
|
||||
import { GraphQLClient } from 'graphql-request'
|
||||
import { login, host } from '../../jest/helpers'
|
||||
import Factory from '../../seed/factories'
|
||||
import gql from 'graphql-tag'
|
||||
import { host, login, gql } from '../../jest/helpers'
|
||||
|
||||
const factory = Factory()
|
||||
let client
|
||||
@ -11,50 +10,39 @@ afterEach(async () => {
|
||||
})
|
||||
|
||||
describe('users', () => {
|
||||
describe('CreateUser', () => {
|
||||
const mutation = `
|
||||
mutation($name: String, $password: String!, $email: String!) {
|
||||
CreateUser(name: $name, password: $password, email: $email) {
|
||||
id
|
||||
}
|
||||
}
|
||||
`
|
||||
describe('given valid password and email', () => {
|
||||
const variables = {
|
||||
name: 'John Doe',
|
||||
password: '123',
|
||||
email: '123@123.de',
|
||||
}
|
||||
|
||||
describe('unauthenticated', () => {
|
||||
beforeEach(async () => {
|
||||
client = new GraphQLClient(host)
|
||||
})
|
||||
|
||||
it('is not allowed to create users', async () => {
|
||||
await expect(client.request(mutation, variables)).rejects.toThrow('Not Authorised')
|
||||
})
|
||||
describe('User', () => {
|
||||
describe('query by email address', () => {
|
||||
beforeEach(async () => {
|
||||
await factory.create('User', { name: 'Johnny', email: 'any-email-address@example.org' })
|
||||
})
|
||||
|
||||
describe('authenticated admin', () => {
|
||||
const query = `query($email: String) { User(email: $email) { name } }`
|
||||
const variables = { email: 'any-email-address@example.org' }
|
||||
beforeEach(() => {
|
||||
client = new GraphQLClient(host)
|
||||
})
|
||||
|
||||
it('is forbidden', async () => {
|
||||
await expect(client.request(query, variables)).rejects.toThrow('Not Authorised')
|
||||
})
|
||||
|
||||
describe('as admin', () => {
|
||||
beforeEach(async () => {
|
||||
const adminParams = {
|
||||
const userParams = {
|
||||
role: 'admin',
|
||||
email: 'admin@example.org',
|
||||
password: '1234',
|
||||
}
|
||||
await factory.create('User', adminParams)
|
||||
const headers = await login(adminParams)
|
||||
const factory = Factory()
|
||||
await factory.create('User', userParams)
|
||||
const headers = await login(userParams)
|
||||
client = new GraphQLClient(host, { headers })
|
||||
})
|
||||
|
||||
it('is allowed to create new users', async () => {
|
||||
const expected = {
|
||||
CreateUser: {
|
||||
id: expect.any(String),
|
||||
},
|
||||
}
|
||||
await expect(client.request(mutation, variables)).resolves.toEqual(expected)
|
||||
it('is permitted', async () => {
|
||||
await expect(client.request(query, variables)).resolves.toEqual({
|
||||
User: [{ name: 'Johnny' }],
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
@ -88,7 +76,7 @@ describe('users', () => {
|
||||
describe('as another user', () => {
|
||||
beforeEach(async () => {
|
||||
const someoneElseParams = {
|
||||
email: 'someoneElse@example.org',
|
||||
email: 'someone-else@example.org',
|
||||
password: '1234',
|
||||
name: 'James Doe',
|
||||
}
|
||||
@ -119,12 +107,12 @@ describe('users', () => {
|
||||
await expect(client.request(mutation, variables)).resolves.toEqual(expected)
|
||||
})
|
||||
|
||||
it('with no name', async () => {
|
||||
it('with `null` as name', async () => {
|
||||
const variables = {
|
||||
id: 'u47',
|
||||
name: null,
|
||||
}
|
||||
const expected = 'Username must be at least 3 characters long!'
|
||||
const expected = '"name" must be a string'
|
||||
await expect(client.request(mutation, variables)).rejects.toThrow(expected)
|
||||
})
|
||||
|
||||
@ -133,7 +121,7 @@ describe('users', () => {
|
||||
id: 'u47',
|
||||
name: ' ',
|
||||
}
|
||||
const expected = 'Username must be at least 3 characters long!'
|
||||
const expected = '"name" length must be at least 3 characters long'
|
||||
await expect(client.request(mutation, variables)).rejects.toThrow(expected)
|
||||
})
|
||||
})
|
||||
@ -143,7 +131,7 @@ describe('users', () => {
|
||||
let deleteUserVariables
|
||||
let asAuthor
|
||||
const deleteUserMutation = gql`
|
||||
mutation($id: ID!, $resource: [String]) {
|
||||
mutation($id: ID!, $resource: [Deletable]) {
|
||||
DeleteUser(id: $id, resource: $resource) {
|
||||
id
|
||||
contributions {
|
||||
@ -158,13 +146,13 @@ describe('users', () => {
|
||||
}
|
||||
`
|
||||
beforeEach(async () => {
|
||||
asAuthor = await factory.create('User', {
|
||||
await factory.create('User', {
|
||||
email: 'test@example.org',
|
||||
password: '1234',
|
||||
id: 'u343',
|
||||
})
|
||||
await factory.create('User', {
|
||||
email: 'friendsAccount@example.org',
|
||||
email: 'friends-account@example.org',
|
||||
password: '1234',
|
||||
id: 'u565',
|
||||
})
|
||||
@ -202,6 +190,7 @@ describe('users', () => {
|
||||
describe('attempting to delete my own account', () => {
|
||||
let expectedResponse
|
||||
beforeEach(async () => {
|
||||
asAuthor = Factory()
|
||||
await asAuthor.authenticateAs({
|
||||
email: 'test@example.org',
|
||||
password: '1234',
|
||||
|
||||
@ -1,4 +0,0 @@
|
||||
enum BadgeStatus {
|
||||
permanent
|
||||
temporary
|
||||
}
|
||||
@ -1,4 +0,0 @@
|
||||
enum BadgeType {
|
||||
role
|
||||
crowdfunding
|
||||
}
|
||||
7
backend/src/schema/types/enum/Emotion.gql
Normal file
7
backend/src/schema/types/enum/Emotion.gql
Normal file
@ -0,0 +1,7 @@
|
||||
enum Emotion {
|
||||
surprised
|
||||
cry
|
||||
happy
|
||||
angry
|
||||
funny
|
||||
}
|
||||
@ -1 +1 @@
|
||||
scalar Upload
|
||||
scalar Upload
|
||||
|
||||
@ -17,21 +17,17 @@ type Query {
|
||||
LIMIT $limit
|
||||
"""
|
||||
)
|
||||
CommentByPost(postId: ID!): [Comment]!
|
||||
}
|
||||
|
||||
type Mutation {
|
||||
# Get a JWT Token for the given Email and password
|
||||
login(email: String!, password: String!): String!
|
||||
signup(email: String!, password: String!): Boolean!
|
||||
changePassword(oldPassword: String!, newPassword: String!): String!
|
||||
requestPasswordReset(email: String!): Boolean!
|
||||
resetPassword(email: String!, code: String!, newPassword: String!): Boolean!
|
||||
report(id: ID!, description: String): Report
|
||||
disable(id: ID!): ID
|
||||
enable(id: ID!): ID
|
||||
reward(fromBadgeId: ID!, toUserId: ID!): ID
|
||||
unreward(fromBadgeId: ID!, toUserId: ID!): ID
|
||||
# Shout the given Type and ID
|
||||
shout(id: ID!, type: ShoutTypeEnum): Boolean!
|
||||
# Unshout the given Type and ID
|
||||
@ -40,7 +36,6 @@ type Mutation {
|
||||
follow(id: ID!, type: FollowTypeEnum): Boolean!
|
||||
# Unfollow the given Type and ID
|
||||
unfollow(id: ID!, type: FollowTypeEnum): Boolean!
|
||||
DeleteUser(id: ID!, resource: [String]): User
|
||||
}
|
||||
|
||||
type Statistics {
|
||||
@ -92,6 +87,11 @@ type Report {
|
||||
user: User @relation(name: "REPORTED", direction: "OUT")
|
||||
}
|
||||
|
||||
enum Deletable {
|
||||
Post
|
||||
Comment
|
||||
}
|
||||
|
||||
enum ShoutTypeEnum {
|
||||
Post
|
||||
Organization
|
||||
|
||||
@ -1,324 +0,0 @@
|
||||
scalar Upload
|
||||
|
||||
type Query {
|
||||
isLoggedIn: Boolean!
|
||||
# Get the currently logged in User based on the given JWT Token
|
||||
currentUser: User
|
||||
# Get the latest Network Statistics
|
||||
statistics: Statistics!
|
||||
findPosts(filter: String!, limit: Int = 10): [Post]! @cypher(
|
||||
statement: """
|
||||
CALL db.index.fulltext.queryNodes('full_text_search', $filter)
|
||||
YIELD node as post, score
|
||||
MATCH (post)<-[:WROTE]-(user:User)
|
||||
WHERE score >= 0.2
|
||||
AND NOT user.deleted = true AND NOT user.disabled = true
|
||||
AND NOT post.deleted = true AND NOT post.disabled = true
|
||||
RETURN post
|
||||
LIMIT $limit
|
||||
"""
|
||||
)
|
||||
CommentByPost(postId: ID!): [Comment]!
|
||||
}
|
||||
|
||||
type Mutation {
|
||||
# Get a JWT Token for the given Email and password
|
||||
login(email: String!, password: String!): String!
|
||||
signup(email: String!, password: String!): Boolean!
|
||||
changePassword(oldPassword:String!, newPassword: String!): String!
|
||||
report(id: ID!, description: String): Report
|
||||
disable(id: ID!): ID
|
||||
enable(id: ID!): ID
|
||||
reward(fromBadgeId: ID!, toUserId: ID!): ID
|
||||
unreward(fromBadgeId: ID!, toUserId: ID!): ID
|
||||
# Shout the given Type and ID
|
||||
shout(id: ID!, type: ShoutTypeEnum): Boolean!
|
||||
# Unshout the given Type and ID
|
||||
unshout(id: ID!, type: ShoutTypeEnum): Boolean!
|
||||
# Follow the given Type and ID
|
||||
follow(id: ID!, type: FollowTypeEnum): Boolean!
|
||||
# Unfollow the given Type and ID
|
||||
unfollow(id: ID!, type: FollowTypeEnum): Boolean!
|
||||
}
|
||||
|
||||
type Statistics {
|
||||
countUsers: Int!
|
||||
countPosts: Int!
|
||||
countComments: Int!
|
||||
countNotifications: Int!
|
||||
countOrganizations: Int!
|
||||
countProjects: Int!
|
||||
countInvites: Int!
|
||||
countFollows: Int!
|
||||
countShouts: Int!
|
||||
}
|
||||
|
||||
type Notification {
|
||||
id: ID!
|
||||
read: Boolean,
|
||||
user: User @relation(name: "NOTIFIED", direction: "OUT")
|
||||
post: Post @relation(name: "NOTIFIED", direction: "IN")
|
||||
createdAt: String
|
||||
}
|
||||
|
||||
scalar Date
|
||||
scalar Time
|
||||
scalar DateTime
|
||||
|
||||
enum VisibilityEnum {
|
||||
public
|
||||
friends
|
||||
private
|
||||
}
|
||||
|
||||
enum UserGroupEnum {
|
||||
admin
|
||||
moderator
|
||||
user
|
||||
}
|
||||
|
||||
type Location {
|
||||
id: ID!
|
||||
name: String!
|
||||
nameEN: String
|
||||
nameDE: String
|
||||
nameFR: String
|
||||
nameNL: String
|
||||
nameIT: String
|
||||
nameES: String
|
||||
namePT: String
|
||||
namePL: String
|
||||
type: String!
|
||||
lat: Float
|
||||
lng: Float
|
||||
parent: Location @cypher(statement: "MATCH (this)-[:IS_IN]->(l:Location) RETURN l")
|
||||
}
|
||||
|
||||
type User {
|
||||
id: ID!
|
||||
actorId: String
|
||||
name: String
|
||||
email: String!
|
||||
slug: String
|
||||
password: String!
|
||||
avatar: String
|
||||
avatarUpload: Upload
|
||||
deleted: Boolean
|
||||
disabled: Boolean
|
||||
disabledBy: User @relation(name: "DISABLED", direction: "IN")
|
||||
role: UserGroupEnum
|
||||
publicKey: String
|
||||
privateKey: String
|
||||
|
||||
location: Location @cypher(statement: "MATCH (this)-[:IS_IN]->(l:Location) RETURN l")
|
||||
locationName: String
|
||||
about: String
|
||||
socialMedia: [SocialMedia]! @relation(name: "OWNED", direction: "OUT")
|
||||
|
||||
createdAt: String
|
||||
updatedAt: String
|
||||
|
||||
notifications(read: Boolean): [Notification]! @relation(name: "NOTIFIED", direction: "IN")
|
||||
|
||||
friends: [User]! @relation(name: "FRIENDS", direction: "BOTH")
|
||||
friendsCount: Int! @cypher(statement: "MATCH (this)<-[:FRIENDS]->(r:User) RETURN COUNT(DISTINCT r)")
|
||||
|
||||
following: [User]! @relation(name: "FOLLOWS", direction: "OUT")
|
||||
followingCount: Int! @cypher(statement: "MATCH (this)-[:FOLLOWS]->(r:User) RETURN COUNT(DISTINCT r)")
|
||||
|
||||
followedBy: [User]! @relation(name: "FOLLOWS", direction: "IN")
|
||||
followedByCount: Int! @cypher(statement: "MATCH (this)<-[:FOLLOWS]-(r:User) RETURN COUNT(DISTINCT r)")
|
||||
|
||||
# Is the currently logged in user following that user?
|
||||
followedByCurrentUser: Boolean! @cypher(
|
||||
statement: """
|
||||
MATCH (this)<-[:FOLLOWS]-(u:User {id: $cypherParams.currentUserId})
|
||||
RETURN COUNT(u) >= 1
|
||||
"""
|
||||
)
|
||||
|
||||
#contributions: [WrittenPost]!
|
||||
#contributions2(first: Int = 10, offset: Int = 0): [WrittenPost2]!
|
||||
# @cypher(
|
||||
# statement: "MATCH (this)-[w:WROTE]->(p:Post) RETURN p as Post, w.timestamp as timestamp"
|
||||
# )
|
||||
contributions: [Post]! @relation(name: "WROTE", direction: "OUT")
|
||||
contributionsCount: Int! @cypher(
|
||||
statement: """
|
||||
MATCH (this)-[:WROTE]->(r:Post)
|
||||
WHERE (NOT exists(r.deleted) OR r.deleted = false)
|
||||
AND (NOT exists(r.disabled) OR r.disabled = false)
|
||||
RETURN COUNT(r)
|
||||
"""
|
||||
)
|
||||
|
||||
comments: [Comment]! @relation(name: "WROTE", direction: "OUT")
|
||||
commentsCount: Int! @cypher(statement: "MATCH (this)-[:WROTE]->(r:Comment) WHERE NOT r.deleted = true AND NOT r.disabled = true RETURN COUNT(r)")
|
||||
|
||||
shouted: [Post]! @relation(name: "SHOUTED", direction: "OUT")
|
||||
shoutedCount: Int! @cypher(statement: "MATCH (this)-[:SHOUTED]->(r:Post) WHERE NOT r.deleted = true AND NOT r.disabled = true RETURN COUNT(DISTINCT r)")
|
||||
|
||||
organizationsCreated: [Organization] @relation(name: "CREATED_ORGA", direction: "OUT")
|
||||
organizationsOwned: [Organization] @relation(name: "OWNING_ORGA", direction: "OUT")
|
||||
|
||||
blacklisted: [User]! @relation(name: "BLACKLISTED", direction: "OUT")
|
||||
|
||||
categories: [Category]! @relation(name: "CATEGORIZED", direction: "OUT")
|
||||
|
||||
badges: [Badge]! @relation(name: "REWARDED", direction: "IN")
|
||||
badgesCount: Int! @cypher(statement: "MATCH (this)<-[:REWARDED]-(r:Badge) RETURN COUNT(r)")
|
||||
}
|
||||
|
||||
type Post {
|
||||
id: ID!
|
||||
activityId: String
|
||||
objectId: String
|
||||
author: User @relation(name: "WROTE", direction: "IN")
|
||||
title: String!
|
||||
slug: String
|
||||
content: String!
|
||||
contentExcerpt: String
|
||||
image: String
|
||||
imageUpload: Upload
|
||||
visibility: VisibilityEnum
|
||||
deleted: Boolean
|
||||
disabled: Boolean
|
||||
disabledBy: User @relation(name: "DISABLED", direction: "IN")
|
||||
createdAt: String
|
||||
updatedAt: String
|
||||
|
||||
relatedContributions: [Post]! @cypher(
|
||||
statement: """
|
||||
MATCH (this)-[:TAGGED|CATEGORIZED]->(categoryOrTag)<-[:TAGGED|CATEGORIZED]-(post:Post)
|
||||
RETURN DISTINCT post
|
||||
LIMIT 10
|
||||
"""
|
||||
)
|
||||
|
||||
tags: [Tag]! @relation(name: "TAGGED", direction: "OUT")
|
||||
categories: [Category]! @relation(name: "CATEGORIZED", direction: "OUT")
|
||||
|
||||
comments: [Comment]! @relation(name: "COMMENTS", direction: "IN")
|
||||
commentsCount: Int! @cypher(statement: "MATCH (this)<-[:COMMENTS]-(r:Comment) WHERE NOT r.deleted = true AND NOT r.disabled = true RETURN COUNT(r)")
|
||||
|
||||
shoutedBy: [User]! @relation(name: "SHOUTED", direction: "IN")
|
||||
shoutedCount: Int! @cypher(statement: "MATCH (this)<-[:SHOUTED]-(r:User) WHERE NOT r.deleted = true AND NOT r.disabled = true RETURN COUNT(DISTINCT r)")
|
||||
|
||||
# Has the currently logged in user shouted that post?
|
||||
shoutedByCurrentUser: Boolean! @cypher(
|
||||
statement: """
|
||||
MATCH (this)<-[:SHOUTED]-(u:User {id: $cypherParams.currentUserId})
|
||||
RETURN COUNT(u) >= 1
|
||||
"""
|
||||
)
|
||||
}
|
||||
|
||||
type Comment {
|
||||
id: ID!
|
||||
activityId: String
|
||||
postId: ID
|
||||
author: User @relation(name: "WROTE", direction: "IN")
|
||||
content: String!
|
||||
contentExcerpt: String
|
||||
post: Post @relation(name: "COMMENTS", direction: "OUT")
|
||||
createdAt: String
|
||||
updatedAt: String
|
||||
deleted: Boolean
|
||||
disabled: Boolean
|
||||
disabledBy: User @relation(name: "DISABLED", direction: "IN")
|
||||
}
|
||||
|
||||
type Report {
|
||||
id: ID!
|
||||
submitter: User @relation(name: "REPORTED", direction: "IN")
|
||||
description: String
|
||||
type: String! @cypher(statement: "MATCH (resource)<-[:REPORTED]-(this) RETURN labels(resource)[0]")
|
||||
createdAt: String
|
||||
comment: Comment @relation(name: "REPORTED", direction: "OUT")
|
||||
post: Post @relation(name: "REPORTED", direction: "OUT")
|
||||
user: User @relation(name: "REPORTED", direction: "OUT")
|
||||
}
|
||||
|
||||
type Category {
|
||||
id: ID!
|
||||
name: String!
|
||||
slug: String
|
||||
icon: String!
|
||||
posts: [Post]! @relation(name: "CATEGORIZED", direction: "IN")
|
||||
postCount: Int! @cypher(statement: "MATCH (this)<-[:CATEGORIZED]-(r:Post) RETURN COUNT(r)")
|
||||
}
|
||||
|
||||
type Badge {
|
||||
id: ID!
|
||||
key: String!
|
||||
type: BadgeTypeEnum!
|
||||
status: BadgeStatusEnum!
|
||||
icon: String!
|
||||
|
||||
rewarded: [User]! @relation(name: "REWARDED", direction: "OUT")
|
||||
}
|
||||
|
||||
enum BadgeTypeEnum {
|
||||
role
|
||||
crowdfunding
|
||||
}
|
||||
enum BadgeStatusEnum {
|
||||
permanent
|
||||
temporary
|
||||
}
|
||||
enum ShoutTypeEnum {
|
||||
Post
|
||||
Organization
|
||||
Project
|
||||
}
|
||||
enum FollowTypeEnum {
|
||||
User
|
||||
Organization
|
||||
Project
|
||||
}
|
||||
|
||||
type Reward {
|
||||
id: ID!
|
||||
user: User @relation(name: "REWARDED", direction: "IN")
|
||||
rewarderId: ID
|
||||
createdAt: String
|
||||
badge: Badge @relation(name: "REWARDED", direction: "OUT")
|
||||
}
|
||||
|
||||
type Organization {
|
||||
id: ID!
|
||||
createdBy: User @relation(name: "CREATED_ORGA", direction: "IN")
|
||||
ownedBy: [User] @relation(name: "OWNING_ORGA", direction: "IN")
|
||||
name: String!
|
||||
slug: String
|
||||
description: String!
|
||||
descriptionExcerpt: String
|
||||
deleted: Boolean
|
||||
disabled: Boolean
|
||||
|
||||
tags: [Tag]! @relation(name: "TAGGED", direction: "OUT")
|
||||
categories: [Category]! @relation(name: "CATEGORIZED", direction: "OUT")
|
||||
}
|
||||
|
||||
type Tag {
|
||||
id: ID!
|
||||
name: String!
|
||||
taggedPosts: [Post]! @relation(name: "TAGGED", direction: "IN")
|
||||
taggedOrganizations: [Organization]! @relation(name: "TAGGED", direction: "IN")
|
||||
taggedCount: Int! @cypher(statement: "MATCH (this)<-[:TAGGED]-(p) RETURN COUNT(DISTINCT p)")
|
||||
taggedCountUnique: Int! @cypher(statement: "MATCH (this)<-[:TAGGED]-(p)<-[:WROTE]-(u:User) RETURN COUNT(DISTINCT u)")
|
||||
deleted: Boolean
|
||||
disabled: Boolean
|
||||
}
|
||||
|
||||
type SharedInboxEndpoint {
|
||||
id: ID!
|
||||
uri: String
|
||||
}
|
||||
|
||||
type SocialMedia {
|
||||
id: ID!
|
||||
url: String
|
||||
ownedBy: [User]! @relation(name: "OWNED", direction: "IN")
|
||||
}
|
||||
|
||||
@ -1,6 +1,5 @@
|
||||
type Badge {
|
||||
id: ID!
|
||||
key: String!
|
||||
type: BadgeType!
|
||||
status: BadgeStatus!
|
||||
icon: String!
|
||||
@ -10,4 +9,23 @@ type Badge {
|
||||
updatedAt: String
|
||||
|
||||
rewarded: [User]! @relation(name: "REWARDED", direction: "OUT")
|
||||
}
|
||||
}
|
||||
|
||||
enum BadgeStatus {
|
||||
permanent
|
||||
temporary
|
||||
}
|
||||
|
||||
enum BadgeType {
|
||||
role
|
||||
crowdfunding
|
||||
}
|
||||
|
||||
type Query {
|
||||
Badge: [Badge]
|
||||
}
|
||||
|
||||
type Mutation {
|
||||
reward(badgeKey: ID!, userId: ID!): User
|
||||
unreward(badgeKey: ID!, userId: ID!): User
|
||||
}
|
||||
|
||||
@ -1,7 +1,6 @@
|
||||
type Comment {
|
||||
id: ID!
|
||||
activityId: String
|
||||
postId: ID
|
||||
author: User @relation(name: "WROTE", direction: "IN")
|
||||
content: String!
|
||||
contentExcerpt: String
|
||||
@ -11,4 +10,24 @@ type Comment {
|
||||
deleted: Boolean
|
||||
disabled: Boolean
|
||||
disabledBy: User @relation(name: "DISABLED", direction: "IN")
|
||||
}
|
||||
}
|
||||
|
||||
type Mutation {
|
||||
CreateComment(
|
||||
id: ID
|
||||
postId: ID!
|
||||
content: String!
|
||||
contentExcerpt: String
|
||||
deleted: Boolean
|
||||
disabled: Boolean
|
||||
createdAt: String
|
||||
): Comment
|
||||
UpdateComment(
|
||||
id: ID!
|
||||
content: String!
|
||||
contentExcerpt: String
|
||||
deleted: Boolean
|
||||
disabled: Boolean
|
||||
): Comment
|
||||
DeleteComment(id: ID!): Comment
|
||||
}
|
||||
|
||||
10
backend/src/schema/types/type/EMOTED.gql
Normal file
10
backend/src/schema/types/type/EMOTED.gql
Normal file
@ -0,0 +1,10 @@
|
||||
type EMOTED @relation(name: "EMOTED") {
|
||||
from: User
|
||||
to: Post
|
||||
|
||||
emotion: Emotion
|
||||
#createdAt: DateTime
|
||||
#updatedAt: DateTime
|
||||
createdAt: String
|
||||
updatedAt: String
|
||||
}
|
||||
23
backend/src/schema/types/type/EmailAddress.gql
Normal file
23
backend/src/schema/types/type/EmailAddress.gql
Normal file
@ -0,0 +1,23 @@
|
||||
type EmailAddress {
|
||||
id: ID!
|
||||
email: String!
|
||||
verifiedAt: String
|
||||
createdAt: String
|
||||
}
|
||||
|
||||
type Mutation {
|
||||
Signup(email: String!): EmailAddress
|
||||
SignupByInvitation(email: String!, token: String!): EmailAddress
|
||||
SignupVerification(
|
||||
nonce: String!
|
||||
name: String!
|
||||
email: String!
|
||||
password: String!
|
||||
slug: String
|
||||
avatar: String
|
||||
coverImg: String
|
||||
avatarUpload: Upload
|
||||
locationName: String
|
||||
about: String
|
||||
): User
|
||||
}
|
||||
13
backend/src/schema/types/type/InvitationCode.gql
Normal file
13
backend/src/schema/types/type/InvitationCode.gql
Normal file
@ -0,0 +1,13 @@
|
||||
type InvitationCode {
|
||||
id: ID!
|
||||
token: String
|
||||
generatedBy: User @relation(name: "GENERATED", direction: "IN")
|
||||
|
||||
#createdAt: DateTime
|
||||
#usedAt: DateTime
|
||||
createdAt: String
|
||||
}
|
||||
|
||||
type Mutation {
|
||||
CreateInvitationCode: InvitationCode
|
||||
}
|
||||
@ -48,4 +48,45 @@ type Post {
|
||||
RETURN COUNT(u) >= 1
|
||||
"""
|
||||
)
|
||||
|
||||
emotions: [EMOTED]
|
||||
}
|
||||
|
||||
type Mutation {
|
||||
CreatePost(
|
||||
id: ID
|
||||
activityId: String
|
||||
objectId: String
|
||||
title: String!
|
||||
slug: String
|
||||
content: String!
|
||||
image: String
|
||||
imageUpload: Upload
|
||||
visibility: Visibility
|
||||
deleted: Boolean
|
||||
disabled: Boolean
|
||||
createdAt: String
|
||||
updatedAt: String
|
||||
language: String
|
||||
categoryIds: [ID]
|
||||
contentExcerpt: String
|
||||
): Post
|
||||
UpdatePost(
|
||||
id: ID!
|
||||
activityId: String
|
||||
objectId: String
|
||||
title: String!
|
||||
slug: String
|
||||
content: String!
|
||||
contentExcerpt: String
|
||||
image: String
|
||||
imageUpload: Upload
|
||||
visibility: Visibility
|
||||
deleted: Boolean
|
||||
disabled: Boolean
|
||||
createdAt: String
|
||||
updatedAt: String
|
||||
language: String
|
||||
categoryIds: [ID]
|
||||
): Post
|
||||
}
|
||||
|
||||
@ -2,21 +2,17 @@ type User {
|
||||
id: ID!
|
||||
actorId: String
|
||||
name: String
|
||||
email: String!
|
||||
slug: String
|
||||
password: String!
|
||||
email: String! @cypher(statement: "MATCH (this)-[:PRIMARY_EMAIL]->(e:EmailAddress) RETURN e.email")
|
||||
slug: String!
|
||||
avatar: String
|
||||
coverImg: String
|
||||
avatarUpload: Upload
|
||||
deleted: Boolean
|
||||
disabled: Boolean
|
||||
disabledBy: User @relation(name: "DISABLED", direction: "IN")
|
||||
role: UserGroup
|
||||
role: UserGroup!
|
||||
publicKey: String
|
||||
privateKey: String
|
||||
|
||||
wasInvited: Boolean
|
||||
wasSeeded: Boolean
|
||||
invitedBy: User @relation(name: "INVITED", direction: "IN")
|
||||
invited: [User] @relation(name: "INVITED", direction: "OUT")
|
||||
|
||||
location: Location @cypher(statement: "MATCH (this)-[:IS_IN]->(l:Location) RETURN l")
|
||||
locationName: String
|
||||
@ -77,4 +73,95 @@ type User {
|
||||
|
||||
badges: [Badge]! @relation(name: "REWARDED", direction: "IN")
|
||||
badgesCount: Int! @cypher(statement: "MATCH (this)<-[:REWARDED]-(r:Badge) RETURN COUNT(r)")
|
||||
|
||||
emotions: [EMOTED]
|
||||
}
|
||||
|
||||
|
||||
input _UserFilter {
|
||||
AND: [_UserFilter!]
|
||||
OR: [_UserFilter!]
|
||||
name_contains: String
|
||||
about_contains: String
|
||||
slug_contains: String
|
||||
id: ID
|
||||
id_not: ID
|
||||
id_in: [ID!]
|
||||
id_not_in: [ID!]
|
||||
id_contains: ID
|
||||
id_not_contains: ID
|
||||
id_starts_with: ID
|
||||
id_not_starts_with: ID
|
||||
id_ends_with: ID
|
||||
id_not_ends_with: ID
|
||||
friends: _UserFilter
|
||||
friends_not: _UserFilter
|
||||
friends_in: [_UserFilter!]
|
||||
friends_not_in: [_UserFilter!]
|
||||
friends_some: _UserFilter
|
||||
friends_none: _UserFilter
|
||||
friends_single: _UserFilter
|
||||
friends_every: _UserFilter
|
||||
following: _UserFilter
|
||||
following_not: _UserFilter
|
||||
following_in: [_UserFilter!]
|
||||
following_not_in: [_UserFilter!]
|
||||
following_some: _UserFilter
|
||||
following_none: _UserFilter
|
||||
following_single: _UserFilter
|
||||
following_every: _UserFilter
|
||||
followedBy: _UserFilter
|
||||
followedBy_not: _UserFilter
|
||||
followedBy_in: [_UserFilter!]
|
||||
followedBy_not_in: [_UserFilter!]
|
||||
followedBy_some: _UserFilter
|
||||
followedBy_none: _UserFilter
|
||||
followedBy_single: _UserFilter
|
||||
followedBy_every: _UserFilter
|
||||
}
|
||||
|
||||
type Query {
|
||||
User(
|
||||
id: ID
|
||||
email: String
|
||||
actorId: String
|
||||
name: String
|
||||
slug: String
|
||||
avatar: String
|
||||
coverImg: String
|
||||
role: UserGroup
|
||||
locationName: String
|
||||
about: String
|
||||
createdAt: String
|
||||
updatedAt: String
|
||||
friendsCount: Int
|
||||
followingCount: Int
|
||||
followedByCount: Int
|
||||
followedByCurrentUser: Boolean
|
||||
contributionsCount: Int
|
||||
commentsCount: Int
|
||||
commentedCount: Int
|
||||
shoutedCount: Int
|
||||
badgesCount: Int
|
||||
first: Int
|
||||
offset: Int
|
||||
orderBy: [_UserOrdering]
|
||||
filter: _UserFilter
|
||||
): [User]
|
||||
}
|
||||
|
||||
type Mutation {
|
||||
UpdateUser (
|
||||
id: ID!
|
||||
name: String
|
||||
email: String
|
||||
slug: String
|
||||
avatar: String
|
||||
coverImg: String
|
||||
avatarUpload: Upload
|
||||
locationName: String
|
||||
about: String
|
||||
): User
|
||||
|
||||
DeleteUser(id: ID!, resource: [Deletable]): User
|
||||
}
|
||||
|
||||
@ -1,28 +1,15 @@
|
||||
import uuid from 'uuid/v4'
|
||||
|
||||
export default function(params) {
|
||||
const {
|
||||
id = uuid(),
|
||||
key = '',
|
||||
type = 'crowdfunding',
|
||||
status = 'permanent',
|
||||
icon = '/img/badges/indiegogo_en_panda.svg',
|
||||
} = params
|
||||
|
||||
export default function create() {
|
||||
return {
|
||||
mutation: `
|
||||
mutation(
|
||||
$id: ID
|
||||
$key: String!
|
||||
$type: BadgeType!
|
||||
$status: BadgeStatus!
|
||||
$icon: String!
|
||||
) {
|
||||
CreateBadge(id: $id, key: $key, type: $type, status: $status, icon: $icon) {
|
||||
id
|
||||
}
|
||||
factory: async ({ args, neodeInstance }) => {
|
||||
const defaults = {
|
||||
type: 'crowdfunding',
|
||||
status: 'permanent',
|
||||
}
|
||||
`,
|
||||
variables: { id, key, type, status, icon },
|
||||
args = {
|
||||
...defaults,
|
||||
...args,
|
||||
}
|
||||
return neodeInstance.create('Badge', args)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@ -10,7 +10,7 @@ export default function(params) {
|
||||
|
||||
return {
|
||||
mutation: `
|
||||
mutation($id: ID!, $postId: ID, $content: String!) {
|
||||
mutation($id: ID!, $postId: ID!, $content: String!) {
|
||||
CreateComment(id: $id, postId: $postId, content: $content) {
|
||||
id
|
||||
}
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import { GraphQLClient, request } from 'graphql-request'
|
||||
import { getDriver } from '../../bootstrap/neo4j'
|
||||
import { getDriver, neode } from '../../bootstrap/neo4j'
|
||||
import createBadge from './badges.js'
|
||||
import createUser from './users.js'
|
||||
import createOrganization from './organizations.js'
|
||||
@ -48,7 +48,11 @@ export const cleanDatabase = async (options = {}) => {
|
||||
}
|
||||
|
||||
export default function Factory(options = {}) {
|
||||
const { neo4jDriver = getDriver(), seedServerHost = 'http://127.0.0.1:4001' } = options
|
||||
let {
|
||||
seedServerHost = 'http://127.0.0.1:4001',
|
||||
neo4jDriver = getDriver(),
|
||||
neodeInstance = neode(),
|
||||
} = options
|
||||
|
||||
const graphQLClient = new GraphQLClient(seedServerHost)
|
||||
|
||||
@ -58,19 +62,24 @@ export default function Factory(options = {}) {
|
||||
graphQLClient,
|
||||
factories,
|
||||
lastResponse: null,
|
||||
neodeInstance,
|
||||
async authenticateAs({ email, password }) {
|
||||
const headers = await authenticatedHeaders({ email, password }, seedServerHost)
|
||||
this.lastResponse = headers
|
||||
this.graphQLClient = new GraphQLClient(seedServerHost, { headers })
|
||||
return this
|
||||
},
|
||||
async create(node, properties) {
|
||||
const { mutation, variables } = this.factories[node](properties)
|
||||
this.lastResponse = await this.graphQLClient.request(mutation, variables)
|
||||
async create(node, args = {}) {
|
||||
const { factory, mutation, variables } = this.factories[node](args)
|
||||
if (factory) {
|
||||
this.lastResponse = await factory({ args, neodeInstance })
|
||||
return this.lastResponse
|
||||
} else {
|
||||
this.lastResponse = await this.graphQLClient.request(mutation, variables)
|
||||
}
|
||||
return this
|
||||
},
|
||||
async relate(node, relationship, properties) {
|
||||
const { from, to } = properties
|
||||
async relate(node, relationship, { from, to }) {
|
||||
const mutation = `
|
||||
mutation {
|
||||
Add${node}${relationship}(
|
||||
@ -112,6 +121,11 @@ export default function Factory(options = {}) {
|
||||
this.lastResponse = await this.graphQLClient.request(mutation)
|
||||
return this
|
||||
},
|
||||
async invite({ email }) {
|
||||
const mutation = ` mutation($email: String!) { invite( email: $email) } `
|
||||
this.lastResponse = await this.graphQLClient.request(mutation, { email })
|
||||
return this
|
||||
},
|
||||
async cleanDatabase() {
|
||||
this.lastResponse = await cleanDatabase({ driver: this.neo4jDriver })
|
||||
return this
|
||||
@ -121,6 +135,9 @@ export default function Factory(options = {}) {
|
||||
result.create.bind(result)
|
||||
result.relate.bind(result)
|
||||
result.mutate.bind(result)
|
||||
result.shout.bind(result)
|
||||
result.follow.bind(result)
|
||||
result.invite.bind(result)
|
||||
result.cleanDatabase.bind(result)
|
||||
return result
|
||||
}
|
||||
|
||||
@ -13,7 +13,7 @@ export default function(params) {
|
||||
faker.lorem.sentence(),
|
||||
faker.lorem.sentence(),
|
||||
].join('. '),
|
||||
image = faker.image.image(),
|
||||
image = faker.image.unsplash.imageUrl(),
|
||||
visibility = 'public',
|
||||
deleted = false,
|
||||
} = params
|
||||
|
||||
@ -8,10 +8,12 @@ export default function create(params) {
|
||||
mutation($id: ID!, $description: String!) {
|
||||
report(description: $description, id: $id) {
|
||||
id
|
||||
createdAt
|
||||
}
|
||||
}
|
||||
`,
|
||||
variables: { id, description },
|
||||
variables: {
|
||||
id,
|
||||
description,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,51 +1,31 @@
|
||||
import faker from 'faker'
|
||||
import uuid from 'uuid/v4'
|
||||
import encryptPassword from '../../helpers/encryptPassword'
|
||||
import slugify from 'slug'
|
||||
|
||||
export default function create(params) {
|
||||
const {
|
||||
id = uuid(),
|
||||
name = faker.name.findName(),
|
||||
slug = '',
|
||||
email = faker.internet.email(),
|
||||
password = '1234',
|
||||
role = 'user',
|
||||
avatar = faker.internet.avatar(),
|
||||
about = faker.lorem.paragraph(),
|
||||
} = params
|
||||
|
||||
export default function create() {
|
||||
return {
|
||||
mutation: `
|
||||
mutation(
|
||||
$id: ID!
|
||||
$name: String
|
||||
$slug: String
|
||||
$password: String!
|
||||
$email: String!
|
||||
$avatar: String
|
||||
$about: String
|
||||
$role: UserGroup
|
||||
) {
|
||||
CreateUser(
|
||||
id: $id
|
||||
name: $name
|
||||
slug: $slug
|
||||
password: $password
|
||||
email: $email
|
||||
avatar: $avatar
|
||||
about: $about
|
||||
role: $role
|
||||
) {
|
||||
id
|
||||
name
|
||||
slug
|
||||
email
|
||||
avatar
|
||||
role
|
||||
deleted
|
||||
disabled
|
||||
}
|
||||
factory: async ({ args, neodeInstance }) => {
|
||||
const defaults = {
|
||||
id: uuid(),
|
||||
name: faker.name.findName(),
|
||||
email: faker.internet.email(),
|
||||
password: '1234',
|
||||
role: 'user',
|
||||
avatar: faker.internet.avatar(),
|
||||
about: faker.lorem.paragraph(),
|
||||
}
|
||||
`,
|
||||
variables: { id, name, slug, password, email, avatar, about, role },
|
||||
defaults.slug = slugify(defaults.name, { lower: true })
|
||||
args = {
|
||||
...defaults,
|
||||
...args,
|
||||
}
|
||||
args = await encryptPassword(args)
|
||||
const user = await neodeInstance.create('User', args)
|
||||
const email = await neodeInstance.create('EmailAddress', { email: args.email })
|
||||
await user.relateTo(email, 'primaryEmail')
|
||||
await email.relateTo(user, 'belongsTo')
|
||||
return user
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@ -5,52 +5,42 @@ import Factory from './factories'
|
||||
;(async function() {
|
||||
try {
|
||||
const f = Factory()
|
||||
await Promise.all([
|
||||
const [racoon, rabbit, wolf, bear, turtle, rhino] = await Promise.all([
|
||||
f.create('Badge', {
|
||||
id: 'b1',
|
||||
key: 'indiegogo_en_racoon',
|
||||
type: 'crowdfunding',
|
||||
status: 'permanent',
|
||||
id: 'indiegogo_en_racoon',
|
||||
icon: '/img/badges/indiegogo_en_racoon.svg',
|
||||
}),
|
||||
f.create('Badge', {
|
||||
id: 'b2',
|
||||
key: 'indiegogo_en_rabbit',
|
||||
type: 'crowdfunding',
|
||||
status: 'permanent',
|
||||
id: 'indiegogo_en_rabbit',
|
||||
icon: '/img/badges/indiegogo_en_rabbit.svg',
|
||||
}),
|
||||
f.create('Badge', {
|
||||
id: 'b3',
|
||||
key: 'indiegogo_en_wolf',
|
||||
type: 'crowdfunding',
|
||||
status: 'permanent',
|
||||
id: 'indiegogo_en_wolf',
|
||||
icon: '/img/badges/indiegogo_en_wolf.svg',
|
||||
}),
|
||||
f.create('Badge', {
|
||||
id: 'b4',
|
||||
key: 'indiegogo_en_bear',
|
||||
type: 'crowdfunding',
|
||||
status: 'permanent',
|
||||
id: 'indiegogo_en_bear',
|
||||
icon: '/img/badges/indiegogo_en_bear.svg',
|
||||
}),
|
||||
f.create('Badge', {
|
||||
id: 'b5',
|
||||
key: 'indiegogo_en_turtle',
|
||||
type: 'crowdfunding',
|
||||
status: 'permanent',
|
||||
id: 'indiegogo_en_turtle',
|
||||
icon: '/img/badges/indiegogo_en_turtle.svg',
|
||||
}),
|
||||
f.create('Badge', {
|
||||
id: 'b6',
|
||||
key: 'indiegogo_en_rhino',
|
||||
type: 'crowdfunding',
|
||||
status: 'permanent',
|
||||
id: 'indiegogo_en_rhino',
|
||||
icon: '/img/badges/indiegogo_en_rhino.svg',
|
||||
}),
|
||||
])
|
||||
|
||||
await Promise.all([
|
||||
const [
|
||||
peterLustig,
|
||||
bobDerBaumeister,
|
||||
jennyRostock,
|
||||
tick, // eslint-disable-line no-unused-vars
|
||||
trick, // eslint-disable-line no-unused-vars
|
||||
track, // eslint-disable-line no-unused-vars
|
||||
dagobert,
|
||||
] = await Promise.all([
|
||||
f.create('User', {
|
||||
id: 'u1',
|
||||
name: 'Peter Lustig',
|
||||
@ -69,47 +59,130 @@ import Factory from './factories'
|
||||
role: 'user',
|
||||
email: 'user@example.org',
|
||||
}),
|
||||
f.create('User', { id: 'u4', name: 'Tick', role: 'user', email: 'tick@example.org' }),
|
||||
f.create('User', { id: 'u5', name: 'Trick', role: 'user', email: 'trick@example.org' }),
|
||||
f.create('User', { id: 'u6', name: 'Track', role: 'user', email: 'track@example.org' }),
|
||||
f.create('User', { id: 'u7', name: 'Dagobert', role: 'user', email: 'dagobert@example.org' }),
|
||||
f.create('User', {
|
||||
id: 'u4',
|
||||
name: 'Tick',
|
||||
role: 'user',
|
||||
email: 'tick@example.org',
|
||||
}),
|
||||
f.create('User', {
|
||||
id: 'u5',
|
||||
name: 'Trick',
|
||||
role: 'user',
|
||||
email: 'trick@example.org',
|
||||
}),
|
||||
f.create('User', {
|
||||
id: 'u6',
|
||||
name: 'Track',
|
||||
role: 'user',
|
||||
email: 'track@example.org',
|
||||
}),
|
||||
f.create('User', {
|
||||
id: 'u7',
|
||||
name: 'Dagobert',
|
||||
role: 'user',
|
||||
email: 'dagobert@example.org',
|
||||
}),
|
||||
])
|
||||
|
||||
const [asAdmin, asModerator, asUser, asTick, asTrick, asTrack] = await Promise.all([
|
||||
Factory().authenticateAs({ email: 'admin@example.org', password: '1234' }),
|
||||
Factory().authenticateAs({ email: 'moderator@example.org', password: '1234' }),
|
||||
Factory().authenticateAs({ email: 'user@example.org', password: '1234' }),
|
||||
Factory().authenticateAs({ email: 'tick@example.org', password: '1234' }),
|
||||
Factory().authenticateAs({ email: 'trick@example.org', password: '1234' }),
|
||||
Factory().authenticateAs({ email: 'track@example.org', password: '1234' }),
|
||||
Factory().authenticateAs({
|
||||
email: 'admin@example.org',
|
||||
password: '1234',
|
||||
}),
|
||||
Factory().authenticateAs({
|
||||
email: 'moderator@example.org',
|
||||
password: '1234',
|
||||
}),
|
||||
Factory().authenticateAs({
|
||||
email: 'user@example.org',
|
||||
password: '1234',
|
||||
}),
|
||||
Factory().authenticateAs({
|
||||
email: 'tick@example.org',
|
||||
password: '1234',
|
||||
}),
|
||||
Factory().authenticateAs({
|
||||
email: 'trick@example.org',
|
||||
password: '1234',
|
||||
}),
|
||||
Factory().authenticateAs({
|
||||
email: 'track@example.org',
|
||||
password: '1234',
|
||||
}),
|
||||
])
|
||||
|
||||
await Promise.all([
|
||||
f.relate('User', 'Badges', { from: 'b6', to: 'u1' }),
|
||||
f.relate('User', 'Badges', { from: 'b5', to: 'u2' }),
|
||||
f.relate('User', 'Badges', { from: 'b4', to: 'u3' }),
|
||||
f.relate('User', 'Badges', { from: 'b3', to: 'u4' }),
|
||||
f.relate('User', 'Badges', { from: 'b2', to: 'u5' }),
|
||||
f.relate('User', 'Badges', { from: 'b1', to: 'u6' }),
|
||||
f.relate('User', 'Friends', { from: 'u1', to: 'u2' }),
|
||||
f.relate('User', 'Friends', { from: 'u1', to: 'u3' }),
|
||||
f.relate('User', 'Friends', { from: 'u2', to: 'u3' }),
|
||||
f.relate('User', 'Blacklisted', { from: 'u7', to: 'u4' }),
|
||||
f.relate('User', 'Blacklisted', { from: 'u7', to: 'u5' }),
|
||||
f.relate('User', 'Blacklisted', { from: 'u7', to: 'u6' }),
|
||||
peterLustig.relateTo(racoon, 'rewarded'),
|
||||
peterLustig.relateTo(rhino, 'rewarded'),
|
||||
peterLustig.relateTo(wolf, 'rewarded'),
|
||||
bobDerBaumeister.relateTo(racoon, 'rewarded'),
|
||||
bobDerBaumeister.relateTo(turtle, 'rewarded'),
|
||||
jennyRostock.relateTo(bear, 'rewarded'),
|
||||
dagobert.relateTo(rabbit, 'rewarded'),
|
||||
])
|
||||
|
||||
await Promise.all([
|
||||
asAdmin.follow({ id: 'u3', type: 'User' }),
|
||||
asModerator.follow({ id: 'u4', type: 'User' }),
|
||||
asUser.follow({ id: 'u4', type: 'User' }),
|
||||
asTick.follow({ id: 'u6', type: 'User' }),
|
||||
asTrick.follow({ id: 'u4', type: 'User' }),
|
||||
asTrack.follow({ id: 'u3', type: 'User' }),
|
||||
f.relate('User', 'Friends', {
|
||||
from: 'u1',
|
||||
to: 'u2',
|
||||
}),
|
||||
f.relate('User', 'Friends', {
|
||||
from: 'u1',
|
||||
to: 'u3',
|
||||
}),
|
||||
f.relate('User', 'Friends', {
|
||||
from: 'u2',
|
||||
to: 'u3',
|
||||
}),
|
||||
f.relate('User', 'Blacklisted', {
|
||||
from: 'u7',
|
||||
to: 'u4',
|
||||
}),
|
||||
f.relate('User', 'Blacklisted', {
|
||||
from: 'u7',
|
||||
to: 'u5',
|
||||
}),
|
||||
f.relate('User', 'Blacklisted', {
|
||||
from: 'u7',
|
||||
to: 'u6',
|
||||
}),
|
||||
])
|
||||
|
||||
await Promise.all([
|
||||
f.create('Category', { id: 'cat1', name: 'Just For Fun', slug: 'justforfun', icon: 'smile' }),
|
||||
asAdmin.follow({
|
||||
id: 'u3',
|
||||
type: 'User',
|
||||
}),
|
||||
asModerator.follow({
|
||||
id: 'u4',
|
||||
type: 'User',
|
||||
}),
|
||||
asUser.follow({
|
||||
id: 'u4',
|
||||
type: 'User',
|
||||
}),
|
||||
asTick.follow({
|
||||
id: 'u6',
|
||||
type: 'User',
|
||||
}),
|
||||
asTrick.follow({
|
||||
id: 'u4',
|
||||
type: 'User',
|
||||
}),
|
||||
asTrack.follow({
|
||||
id: 'u3',
|
||||
type: 'User',
|
||||
}),
|
||||
])
|
||||
|
||||
await Promise.all([
|
||||
f.create('Category', {
|
||||
id: 'cat1',
|
||||
name: 'Just For Fun',
|
||||
slug: 'justforfun',
|
||||
icon: 'smile',
|
||||
}),
|
||||
f.create('Category', {
|
||||
id: 'cat2',
|
||||
name: 'Happyness & Values',
|
||||
@ -203,10 +276,22 @@ import Factory from './factories'
|
||||
])
|
||||
|
||||
await Promise.all([
|
||||
f.create('Tag', { id: 't1', name: 'Umwelt' }),
|
||||
f.create('Tag', { id: 't2', name: 'Naturschutz' }),
|
||||
f.create('Tag', { id: 't3', name: 'Demokratie' }),
|
||||
f.create('Tag', { id: 't4', name: 'Freiheit' }),
|
||||
f.create('Tag', {
|
||||
id: 'Umwelt',
|
||||
name: 'Umwelt',
|
||||
}),
|
||||
f.create('Tag', {
|
||||
id: 'Naturschutz',
|
||||
name: 'Naturschutz',
|
||||
}),
|
||||
f.create('Tag', {
|
||||
id: 'Demokratie',
|
||||
name: 'Demokratie',
|
||||
}),
|
||||
f.create('Tag', {
|
||||
id: 'Freiheit',
|
||||
name: 'Freiheit',
|
||||
}),
|
||||
])
|
||||
|
||||
const mention1 = 'Hey <a class="mention" href="/profile/u3">@jenny-rostock</a>, what\'s up?'
|
||||
@ -214,108 +299,347 @@ import Factory from './factories'
|
||||
'Hey <a class="mention" href="/profile/u3">@jenny-rostock</a>, here is another notification for you!'
|
||||
|
||||
await Promise.all([
|
||||
asAdmin.create('Post', { id: 'p0' }),
|
||||
asModerator.create('Post', { id: 'p1' }),
|
||||
asUser.create('Post', { id: 'p2' }),
|
||||
asTick.create('Post', { id: 'p3' }),
|
||||
asTrick.create('Post', { id: 'p4' }),
|
||||
asTrack.create('Post', { id: 'p5' }),
|
||||
asAdmin.create('Post', { id: 'p6' }),
|
||||
asModerator.create('Post', { id: 'p7', content: `${mention1} ${faker.lorem.paragraph()}` }),
|
||||
asUser.create('Post', { id: 'p8' }),
|
||||
asTick.create('Post', { id: 'p9' }),
|
||||
asTrick.create('Post', { id: 'p10' }),
|
||||
asTrack.create('Post', { id: 'p11' }),
|
||||
asAdmin.create('Post', { id: 'p12', content: `${mention2} ${faker.lorem.paragraph()}` }),
|
||||
asModerator.create('Post', { id: 'p13' }),
|
||||
asUser.create('Post', { id: 'p14' }),
|
||||
asTick.create('Post', { id: 'p15' }),
|
||||
asAdmin.create('Post', {
|
||||
id: 'p0',
|
||||
image: faker.image.unsplash.food(),
|
||||
}),
|
||||
asModerator.create('Post', {
|
||||
id: 'p1',
|
||||
image: faker.image.unsplash.technology(),
|
||||
}),
|
||||
asUser.create('Post', {
|
||||
id: 'p2',
|
||||
}),
|
||||
asTick.create('Post', {
|
||||
id: 'p3',
|
||||
}),
|
||||
asTrick.create('Post', {
|
||||
id: 'p4',
|
||||
}),
|
||||
asTrack.create('Post', {
|
||||
id: 'p5',
|
||||
}),
|
||||
asAdmin.create('Post', {
|
||||
id: 'p6',
|
||||
image: faker.image.unsplash.buildings(),
|
||||
}),
|
||||
asModerator.create('Post', {
|
||||
id: 'p7',
|
||||
content: `${mention1} ${faker.lorem.paragraph()}`,
|
||||
}),
|
||||
asUser.create('Post', {
|
||||
id: 'p8',
|
||||
image: faker.image.unsplash.nature(),
|
||||
}),
|
||||
asTick.create('Post', {
|
||||
id: 'p9',
|
||||
}),
|
||||
asTrick.create('Post', {
|
||||
id: 'p10',
|
||||
}),
|
||||
asTrack.create('Post', {
|
||||
id: 'p11',
|
||||
image: faker.image.unsplash.people(),
|
||||
}),
|
||||
asAdmin.create('Post', {
|
||||
id: 'p12',
|
||||
content: `${mention2} ${faker.lorem.paragraph()}`,
|
||||
}),
|
||||
asModerator.create('Post', {
|
||||
id: 'p13',
|
||||
}),
|
||||
asUser.create('Post', {
|
||||
id: 'p14',
|
||||
image: faker.image.unsplash.objects(),
|
||||
}),
|
||||
asTick.create('Post', {
|
||||
id: 'p15',
|
||||
}),
|
||||
])
|
||||
|
||||
await Promise.all([
|
||||
f.relate('Post', 'Categories', { from: 'p0', to: 'cat16' }),
|
||||
f.relate('Post', 'Categories', { from: 'p1', to: 'cat1' }),
|
||||
f.relate('Post', 'Categories', { from: 'p2', to: 'cat2' }),
|
||||
f.relate('Post', 'Categories', { from: 'p3', to: 'cat3' }),
|
||||
f.relate('Post', 'Categories', { from: 'p4', to: 'cat4' }),
|
||||
f.relate('Post', 'Categories', { from: 'p5', to: 'cat5' }),
|
||||
f.relate('Post', 'Categories', { from: 'p6', to: 'cat6' }),
|
||||
f.relate('Post', 'Categories', { from: 'p7', to: 'cat7' }),
|
||||
f.relate('Post', 'Categories', { from: 'p8', to: 'cat8' }),
|
||||
f.relate('Post', 'Categories', { from: 'p9', to: 'cat9' }),
|
||||
f.relate('Post', 'Categories', { from: 'p10', to: 'cat10' }),
|
||||
f.relate('Post', 'Categories', { from: 'p11', to: 'cat11' }),
|
||||
f.relate('Post', 'Categories', { from: 'p12', to: 'cat12' }),
|
||||
f.relate('Post', 'Categories', { from: 'p13', to: 'cat13' }),
|
||||
f.relate('Post', 'Categories', { from: 'p14', to: 'cat14' }),
|
||||
f.relate('Post', 'Categories', { from: 'p15', to: 'cat15' }),
|
||||
f.relate('Post', 'Categories', {
|
||||
from: 'p0',
|
||||
to: 'cat16',
|
||||
}),
|
||||
f.relate('Post', 'Categories', {
|
||||
from: 'p1',
|
||||
to: 'cat1',
|
||||
}),
|
||||
f.relate('Post', 'Categories', {
|
||||
from: 'p2',
|
||||
to: 'cat2',
|
||||
}),
|
||||
f.relate('Post', 'Categories', {
|
||||
from: 'p3',
|
||||
to: 'cat3',
|
||||
}),
|
||||
f.relate('Post', 'Categories', {
|
||||
from: 'p4',
|
||||
to: 'cat4',
|
||||
}),
|
||||
f.relate('Post', 'Categories', {
|
||||
from: 'p5',
|
||||
to: 'cat5',
|
||||
}),
|
||||
f.relate('Post', 'Categories', {
|
||||
from: 'p6',
|
||||
to: 'cat6',
|
||||
}),
|
||||
f.relate('Post', 'Categories', {
|
||||
from: 'p7',
|
||||
to: 'cat7',
|
||||
}),
|
||||
f.relate('Post', 'Categories', {
|
||||
from: 'p8',
|
||||
to: 'cat8',
|
||||
}),
|
||||
f.relate('Post', 'Categories', {
|
||||
from: 'p9',
|
||||
to: 'cat9',
|
||||
}),
|
||||
f.relate('Post', 'Categories', {
|
||||
from: 'p10',
|
||||
to: 'cat10',
|
||||
}),
|
||||
f.relate('Post', 'Categories', {
|
||||
from: 'p11',
|
||||
to: 'cat11',
|
||||
}),
|
||||
f.relate('Post', 'Categories', {
|
||||
from: 'p12',
|
||||
to: 'cat12',
|
||||
}),
|
||||
f.relate('Post', 'Categories', {
|
||||
from: 'p13',
|
||||
to: 'cat13',
|
||||
}),
|
||||
f.relate('Post', 'Categories', {
|
||||
from: 'p14',
|
||||
to: 'cat14',
|
||||
}),
|
||||
f.relate('Post', 'Categories', {
|
||||
from: 'p15',
|
||||
to: 'cat15',
|
||||
}),
|
||||
|
||||
f.relate('Post', 'Tags', { from: 'p0', to: 't4' }),
|
||||
f.relate('Post', 'Tags', { from: 'p1', to: 't1' }),
|
||||
f.relate('Post', 'Tags', { from: 'p2', to: 't2' }),
|
||||
f.relate('Post', 'Tags', { from: 'p3', to: 't3' }),
|
||||
f.relate('Post', 'Tags', { from: 'p4', to: 't4' }),
|
||||
f.relate('Post', 'Tags', { from: 'p5', to: 't1' }),
|
||||
f.relate('Post', 'Tags', { from: 'p6', to: 't2' }),
|
||||
f.relate('Post', 'Tags', { from: 'p7', to: 't3' }),
|
||||
f.relate('Post', 'Tags', { from: 'p8', to: 't4' }),
|
||||
f.relate('Post', 'Tags', { from: 'p9', to: 't1' }),
|
||||
f.relate('Post', 'Tags', { from: 'p10', to: 't2' }),
|
||||
f.relate('Post', 'Tags', { from: 'p11', to: 't3' }),
|
||||
f.relate('Post', 'Tags', { from: 'p12', to: 't4' }),
|
||||
f.relate('Post', 'Tags', { from: 'p13', to: 't1' }),
|
||||
f.relate('Post', 'Tags', { from: 'p14', to: 't2' }),
|
||||
f.relate('Post', 'Tags', { from: 'p15', to: 't3' }),
|
||||
f.relate('Post', 'Tags', {
|
||||
from: 'p0',
|
||||
to: 'Freiheit',
|
||||
}),
|
||||
f.relate('Post', 'Tags', {
|
||||
from: 'p1',
|
||||
to: 'Umwelt',
|
||||
}),
|
||||
f.relate('Post', 'Tags', {
|
||||
from: 'p2',
|
||||
to: 'Naturschutz',
|
||||
}),
|
||||
f.relate('Post', 'Tags', {
|
||||
from: 'p3',
|
||||
to: 'Demokratie',
|
||||
}),
|
||||
f.relate('Post', 'Tags', {
|
||||
from: 'p4',
|
||||
to: 'Freiheit',
|
||||
}),
|
||||
f.relate('Post', 'Tags', {
|
||||
from: 'p5',
|
||||
to: 'Umwelt',
|
||||
}),
|
||||
f.relate('Post', 'Tags', {
|
||||
from: 'p6',
|
||||
to: 'Naturschutz',
|
||||
}),
|
||||
f.relate('Post', 'Tags', {
|
||||
from: 'p7',
|
||||
to: 'Demokratie',
|
||||
}),
|
||||
f.relate('Post', 'Tags', {
|
||||
from: 'p8',
|
||||
to: 'Freiheit',
|
||||
}),
|
||||
f.relate('Post', 'Tags', {
|
||||
from: 'p9',
|
||||
to: 'Umwelt',
|
||||
}),
|
||||
f.relate('Post', 'Tags', {
|
||||
from: 'p10',
|
||||
to: 'Naturschutz',
|
||||
}),
|
||||
f.relate('Post', 'Tags', {
|
||||
from: 'p11',
|
||||
to: 'Demokratie',
|
||||
}),
|
||||
f.relate('Post', 'Tags', {
|
||||
from: 'p12',
|
||||
to: 'Freiheit',
|
||||
}),
|
||||
f.relate('Post', 'Tags', {
|
||||
from: 'p13',
|
||||
to: 'Umwelt',
|
||||
}),
|
||||
f.relate('Post', 'Tags', {
|
||||
from: 'p14',
|
||||
to: 'Naturschutz',
|
||||
}),
|
||||
f.relate('Post', 'Tags', {
|
||||
from: 'p15',
|
||||
to: 'Demokratie',
|
||||
}),
|
||||
])
|
||||
|
||||
await Promise.all([
|
||||
asAdmin.shout({ id: 'p2', type: 'Post' }),
|
||||
asAdmin.shout({ id: 'p6', type: 'Post' }),
|
||||
asModerator.shout({ id: 'p0', type: 'Post' }),
|
||||
asModerator.shout({ id: 'p6', type: 'Post' }),
|
||||
asUser.shout({ id: 'p6', type: 'Post' }),
|
||||
asUser.shout({ id: 'p7', type: 'Post' }),
|
||||
asTick.shout({ id: 'p8', type: 'Post' }),
|
||||
asTick.shout({ id: 'p9', type: 'Post' }),
|
||||
asTrack.shout({ id: 'p10', type: 'Post' }),
|
||||
asAdmin.shout({
|
||||
id: 'p2',
|
||||
type: 'Post',
|
||||
}),
|
||||
asAdmin.shout({
|
||||
id: 'p6',
|
||||
type: 'Post',
|
||||
}),
|
||||
asModerator.shout({
|
||||
id: 'p0',
|
||||
type: 'Post',
|
||||
}),
|
||||
asModerator.shout({
|
||||
id: 'p6',
|
||||
type: 'Post',
|
||||
}),
|
||||
asUser.shout({
|
||||
id: 'p6',
|
||||
type: 'Post',
|
||||
}),
|
||||
asUser.shout({
|
||||
id: 'p7',
|
||||
type: 'Post',
|
||||
}),
|
||||
asTick.shout({
|
||||
id: 'p8',
|
||||
type: 'Post',
|
||||
}),
|
||||
asTick.shout({
|
||||
id: 'p9',
|
||||
type: 'Post',
|
||||
}),
|
||||
asTrack.shout({
|
||||
id: 'p10',
|
||||
type: 'Post',
|
||||
}),
|
||||
])
|
||||
await Promise.all([
|
||||
asAdmin.shout({ id: 'p2', type: 'Post' }),
|
||||
asAdmin.shout({ id: 'p6', type: 'Post' }),
|
||||
asModerator.shout({ id: 'p0', type: 'Post' }),
|
||||
asModerator.shout({ id: 'p6', type: 'Post' }),
|
||||
asUser.shout({ id: 'p6', type: 'Post' }),
|
||||
asUser.shout({ id: 'p7', type: 'Post' }),
|
||||
asTick.shout({ id: 'p8', type: 'Post' }),
|
||||
asTick.shout({ id: 'p9', type: 'Post' }),
|
||||
asTrack.shout({ id: 'p10', type: 'Post' }),
|
||||
asAdmin.shout({
|
||||
id: 'p2',
|
||||
type: 'Post',
|
||||
}),
|
||||
asAdmin.shout({
|
||||
id: 'p6',
|
||||
type: 'Post',
|
||||
}),
|
||||
asModerator.shout({
|
||||
id: 'p0',
|
||||
type: 'Post',
|
||||
}),
|
||||
asModerator.shout({
|
||||
id: 'p6',
|
||||
type: 'Post',
|
||||
}),
|
||||
asUser.shout({
|
||||
id: 'p6',
|
||||
type: 'Post',
|
||||
}),
|
||||
asUser.shout({
|
||||
id: 'p7',
|
||||
type: 'Post',
|
||||
}),
|
||||
asTick.shout({
|
||||
id: 'p8',
|
||||
type: 'Post',
|
||||
}),
|
||||
asTick.shout({
|
||||
id: 'p9',
|
||||
type: 'Post',
|
||||
}),
|
||||
asTrack.shout({
|
||||
id: 'p10',
|
||||
type: 'Post',
|
||||
}),
|
||||
])
|
||||
|
||||
await Promise.all([
|
||||
asUser.create('Comment', { id: 'c1', postId: 'p1' }),
|
||||
asTick.create('Comment', { id: 'c2', postId: 'p1' }),
|
||||
asTrack.create('Comment', { id: 'c3', postId: 'p3' }),
|
||||
asTrick.create('Comment', { id: 'c4', postId: 'p2' }),
|
||||
asModerator.create('Comment', { id: 'c5', postId: 'p3' }),
|
||||
asAdmin.create('Comment', { id: 'c6', postId: 'p4' }),
|
||||
asUser.create('Comment', { id: 'c7', postId: 'p2' }),
|
||||
asTick.create('Comment', { id: 'c8', postId: 'p15' }),
|
||||
asTrick.create('Comment', { id: 'c9', postId: 'p15' }),
|
||||
asTrack.create('Comment', { id: 'c10', postId: 'p15' }),
|
||||
asUser.create('Comment', { id: 'c11', postId: 'p15' }),
|
||||
asUser.create('Comment', { id: 'c12', postId: 'p15' }),
|
||||
asUser.create('Comment', {
|
||||
id: 'c1',
|
||||
postId: 'p1',
|
||||
}),
|
||||
asTick.create('Comment', {
|
||||
id: 'c2',
|
||||
postId: 'p1',
|
||||
}),
|
||||
asTrack.create('Comment', {
|
||||
id: 'c3',
|
||||
postId: 'p3',
|
||||
}),
|
||||
asTrick.create('Comment', {
|
||||
id: 'c4',
|
||||
postId: 'p2',
|
||||
}),
|
||||
asModerator.create('Comment', {
|
||||
id: 'c5',
|
||||
postId: 'p3',
|
||||
}),
|
||||
asAdmin.create('Comment', {
|
||||
id: 'c6',
|
||||
postId: 'p4',
|
||||
}),
|
||||
asUser.create('Comment', {
|
||||
id: 'c7',
|
||||
postId: 'p2',
|
||||
}),
|
||||
asTick.create('Comment', {
|
||||
id: 'c8',
|
||||
postId: 'p15',
|
||||
}),
|
||||
asTrick.create('Comment', {
|
||||
id: 'c9',
|
||||
postId: 'p15',
|
||||
}),
|
||||
asTrack.create('Comment', {
|
||||
id: 'c10',
|
||||
postId: 'p15',
|
||||
}),
|
||||
asUser.create('Comment', {
|
||||
id: 'c11',
|
||||
postId: 'p15',
|
||||
}),
|
||||
asUser.create('Comment', {
|
||||
id: 'c12',
|
||||
postId: 'p15',
|
||||
}),
|
||||
])
|
||||
|
||||
const disableMutation = 'mutation($id: ID!) { disable(id: $id) }'
|
||||
await Promise.all([
|
||||
asModerator.mutate(disableMutation, { id: 'p11' }),
|
||||
asModerator.mutate(disableMutation, { id: 'c5' }),
|
||||
asModerator.mutate(disableMutation, {
|
||||
id: 'p11',
|
||||
}),
|
||||
asModerator.mutate(disableMutation, {
|
||||
id: 'c5',
|
||||
}),
|
||||
])
|
||||
|
||||
await Promise.all([
|
||||
asTick.create('Report', { description: "I don't like this comment", id: 'c1' }),
|
||||
asTrick.create('Report', { description: "I don't like this post", id: 'p1' }),
|
||||
asTrack.create('Report', { description: "I don't like this user", id: 'u1' }),
|
||||
asTick.create('Report', {
|
||||
description: "I don't like this comment",
|
||||
id: 'c1',
|
||||
}),
|
||||
asTrick.create('Report', {
|
||||
description: "I don't like this post",
|
||||
id: 'p1',
|
||||
}),
|
||||
asTrack.create('Report', {
|
||||
description: "I don't like this user",
|
||||
id: 'u1',
|
||||
}),
|
||||
])
|
||||
|
||||
await Promise.all([
|
||||
@ -342,13 +666,33 @@ import Factory from './factories'
|
||||
])
|
||||
|
||||
await Promise.all([
|
||||
f.relate('Organization', 'CreatedBy', { from: 'u1', to: 'o1' }),
|
||||
f.relate('Organization', 'CreatedBy', { from: 'u1', to: 'o2' }),
|
||||
f.relate('Organization', 'OwnedBy', { from: 'u2', to: 'o2' }),
|
||||
f.relate('Organization', 'OwnedBy', { from: 'u2', to: 'o3' }),
|
||||
f.relate('Organization', 'CreatedBy', {
|
||||
from: 'u1',
|
||||
to: 'o1',
|
||||
}),
|
||||
f.relate('Organization', 'CreatedBy', {
|
||||
from: 'u1',
|
||||
to: 'o2',
|
||||
}),
|
||||
f.relate('Organization', 'OwnedBy', {
|
||||
from: 'u2',
|
||||
to: 'o2',
|
||||
}),
|
||||
f.relate('Organization', 'OwnedBy', {
|
||||
from: 'u2',
|
||||
to: 'o3',
|
||||
}),
|
||||
])
|
||||
|
||||
await Promise.all(
|
||||
[...Array(30).keys()].map(i => {
|
||||
return f.create('User')
|
||||
}),
|
||||
)
|
||||
|
||||
/* eslint-disable-next-line no-console */
|
||||
console.log('Seeded Data...')
|
||||
process.exit(0)
|
||||
} catch (err) {
|
||||
/* eslint-disable-next-line no-console */
|
||||
console.error(err)
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import express from 'express'
|
||||
import helmet from 'helmet'
|
||||
import { GraphQLServer } from 'graphql-yoga'
|
||||
import { ApolloServer } from 'apollo-server-express'
|
||||
import CONFIG, { requiredConfigs } from './config'
|
||||
import mocks from './mocks'
|
||||
import middleware from './middleware'
|
||||
@ -20,28 +20,30 @@ const driver = getDriver()
|
||||
|
||||
const createServer = options => {
|
||||
const defaults = {
|
||||
context: async ({ request }) => {
|
||||
const user = await decode(driver, request.headers.authorization)
|
||||
context: async ({ req }) => {
|
||||
const user = await decode(driver, req.headers.authorization)
|
||||
return {
|
||||
driver,
|
||||
user,
|
||||
req: request,
|
||||
req,
|
||||
cypherParams: {
|
||||
currentUserId: user ? user.id : null,
|
||||
},
|
||||
}
|
||||
},
|
||||
schema,
|
||||
schema: middleware(schema),
|
||||
debug: CONFIG.DEBUG,
|
||||
tracing: CONFIG.DEBUG,
|
||||
middlewares: middleware(schema),
|
||||
mocks: CONFIG.MOCKS ? mocks : false,
|
||||
}
|
||||
const server = new GraphQLServer(Object.assign({}, defaults, options))
|
||||
const server = new ApolloServer(Object.assign({}, defaults, options))
|
||||
|
||||
server.express.use(helmet())
|
||||
server.express.use(express.static('public'))
|
||||
return server
|
||||
const app = express()
|
||||
app.use(helmet())
|
||||
app.use(express.static('public'))
|
||||
server.applyMiddleware({ app, path: '/' })
|
||||
|
||||
return { server, app }
|
||||
}
|
||||
|
||||
export default createServer
|
||||
|
||||
43
backend/src/server.spec.js
Normal file
43
backend/src/server.spec.js
Normal file
@ -0,0 +1,43 @@
|
||||
import { createTestClient } from 'apollo-server-testing'
|
||||
import createServer from './server'
|
||||
|
||||
/**
|
||||
* This file is for demonstration purposes. It does not really test the
|
||||
* `isLoggedIn` query but demonstrates how we can use `apollo-server-testing`.
|
||||
* All we need to do is to get an instance of `ApolloServer` and maybe we want
|
||||
* stub out `context` as shown below.
|
||||
*
|
||||
*/
|
||||
|
||||
let user
|
||||
let action
|
||||
describe('isLoggedIn', () => {
|
||||
beforeEach(() => {
|
||||
action = async () => {
|
||||
const { server } = createServer({
|
||||
context: () => {
|
||||
return {
|
||||
user,
|
||||
}
|
||||
},
|
||||
})
|
||||
const { query } = createTestClient(server)
|
||||
|
||||
const isLoggedIn = `{ isLoggedIn }`
|
||||
return query({ query: isLoggedIn })
|
||||
}
|
||||
})
|
||||
|
||||
it('returns false', async () => {
|
||||
const expected = expect.objectContaining({ data: { isLoggedIn: false } })
|
||||
await expect(action()).resolves.toEqual(expected)
|
||||
})
|
||||
|
||||
describe('when authenticated', () => {
|
||||
it('returns true', async () => {
|
||||
user = { id: '123' }
|
||||
const expected = expect.objectContaining({ data: { isLoggedIn: true } })
|
||||
await expect(action()).resolves.toEqual(expected)
|
||||
})
|
||||
})
|
||||
})
|
||||
1146
backend/yarn.lock
1146
backend/yarn.lock
File diff suppressed because it is too large
Load Diff
@ -16,7 +16,7 @@ The following features will be implemented. This gets done in three steps:
|
||||
|
||||
### User Account
|
||||
|
||||
[Cucumber Features](./integration/user_account)
|
||||
[Cucumber Features](https://github.com/Human-Connection/Human-Connection/tree/master/cypress/integration/user_account)
|
||||
|
||||
* Sign-up
|
||||
* Agree to Data Privacy Statement
|
||||
@ -34,7 +34,7 @@ The following features will be implemented. This gets done in three steps:
|
||||
|
||||
### User Profile
|
||||
|
||||
[Cucumber Features](./integration/user_profile)
|
||||
[Cucumber Features](https://github.com/Human-Connection/Human-Connection/tree/master/cypress/integration/user_profile)
|
||||
|
||||
* Upload and Change Avatar
|
||||
* Upload and Change Profile Picture
|
||||
@ -59,7 +59,7 @@ The following features will be implemented. This gets done in three steps:
|
||||
|
||||
### Posts
|
||||
|
||||
[Cucumber Features](./integration/post/)
|
||||
[Cucumber Features](https://github.com/Human-Connection/Human-Connection/tree/master/cypress/integration/post)
|
||||
|
||||
* Creating Posts
|
||||
* Persistent Links
|
||||
@ -78,13 +78,13 @@ The following features will be implemented. This gets done in three steps:
|
||||
|
||||
### Comments
|
||||
|
||||
* Creating Comments
|
||||
* Creating Comments
|
||||
* Deleting Comments
|
||||
* Editing Comments
|
||||
* Upvote comments of others
|
||||
|
||||
### Notifications
|
||||
[Cucumber features](./integration/notifications)
|
||||
[Cucumber features](https://github.com/Human-Connection/Human-Connection/tree/master/cypress/integration/notifications)
|
||||
|
||||
* User @-mentionings
|
||||
* Notify authors for comments
|
||||
@ -94,12 +94,12 @@ The following features will be implemented. This gets done in three steps:
|
||||
|
||||
* Show Posts by Tiles
|
||||
* Show Posts as List
|
||||
* Filter by Category \(Health and Wellbeing, Global Peace & Non-Violence, ...\)
|
||||
* Filter by Category \(Health and Wellbeing, Global Peace & Non-Violence, ...\)
|
||||
* Filter by Mood \(Funny, Happy, Surprised, Cry, Angry, ...\)
|
||||
* Filter by Source \(Connections, Following, Individuals, Non-Profits, ...\)
|
||||
* Filter by Posts & Tools \(Post, Events, CanDos, ...\)
|
||||
* Filter by Format Type \(Text, Pictures, Video, ...\)
|
||||
* Extended Filter \(Continent, Country, Language, ...\)
|
||||
* Extended Filter \(Continent, Country, Language, ...\)
|
||||
* Sort Posts by Date
|
||||
* Sort Posts by Shouts
|
||||
* Sort Posts by most Comments
|
||||
@ -116,7 +116,7 @@ The following features will be implemented. This gets done in three steps:
|
||||
|
||||
### Search
|
||||
|
||||
[Cucumber Features](./integration/search)
|
||||
[Cucumber Features](https://github.com/Human-Connection/Human-Connection/tree/master/cypress/integration/search)
|
||||
|
||||
* Search for Categories
|
||||
* Search for Tags
|
||||
@ -186,13 +186,13 @@ The following features will be implemented. This gets done in three steps:
|
||||
|
||||
### More Info
|
||||
|
||||
Shows autmatically releated information for existing post.
|
||||
Shows automatically related information for existing post.
|
||||
|
||||
* Show related Posts
|
||||
* Show Pros and Cons
|
||||
* Show Bestlist
|
||||
* Show Votes
|
||||
* Link to corresponding Chatroom
|
||||
* Link to corresponding Chatroom
|
||||
|
||||
### Take Action
|
||||
|
||||
@ -237,7 +237,7 @@ Shows automatically related actions for existing post.
|
||||
|
||||
### Moderation
|
||||
|
||||
[Cucumber Features](./integration/moderation)
|
||||
[Cucumber Features](https://github.com/Human-Connection/Human-Connection/tree/master/cypress/integration/moderation)
|
||||
|
||||
* Report Button for users for doubtful Content
|
||||
* Moderator Panel
|
||||
@ -262,7 +262,7 @@ Shows automatically related actions for existing post.
|
||||
|
||||
### Internationalization
|
||||
|
||||
[Cucumber Features](./integration/internationalization)
|
||||
[Cucumber Features](https://github.com/Human-Connection/Human-Connection/tree/master/cypress/integration/internationalization)
|
||||
|
||||
* Frontend UI
|
||||
* Backend Error Messages
|
||||
@ -276,4 +276,3 @@ Shows automatically related actions for existing post.
|
||||
* Receiving Undo and Delete Activities for Articles and Notes
|
||||
* Serving Webfinger records and Actor Objects
|
||||
* Serving Followers, Following and Outbox collections
|
||||
|
||||
|
||||
@ -22,16 +22,16 @@ Feature: Tags and Categories
|
||||
When I navigate to the administration dashboard
|
||||
And I click on the menu item "Categories"
|
||||
Then I can see the following table:
|
||||
| | Name | Posts |
|
||||
| | Just For Fun | 2 |
|
||||
| | Happyness & Values | 1 |
|
||||
| | Health & Wellbeing | 0 |
|
||||
| | Name | Posts |
|
||||
| | Just For Fun | 2 |
|
||||
| | Happyness & Values | 1 |
|
||||
| | Health & Wellbeing | 0 |
|
||||
|
||||
Scenario: See an overview of tags
|
||||
When I navigate to the administration dashboard
|
||||
And I click on the menu item "Tags"
|
||||
Then I can see the following table:
|
||||
| | Name | Users | Posts |
|
||||
| 1 | Democracy | 3 | 4 |
|
||||
| 2 | Nature | 2 | 3 |
|
||||
| 3 | Ecology | 1 | 1 |
|
||||
| | Name | Users | Posts |
|
||||
| 1 | Democracy | 3 | 4 |
|
||||
| 2 | Nature | 2 | 3 |
|
||||
| 3 | Ecology | 1 | 1 |
|
||||
|
||||
@ -1,36 +1,36 @@
|
||||
import { When, Then } from 'cypress-cucumber-preprocessor/steps'
|
||||
import { When, Then } from "cypress-cucumber-preprocessor/steps";
|
||||
|
||||
/* global cy */
|
||||
|
||||
When('I visit my profile page', () => {
|
||||
cy.openPage('profile/peter-pan')
|
||||
})
|
||||
When("I visit my profile page", () => {
|
||||
cy.openPage("profile/peter-pan");
|
||||
});
|
||||
|
||||
Then('I should be able to change my profile picture', () => {
|
||||
const avatarUpload = 'onourjourney.png'
|
||||
Then("I should be able to change my profile picture", () => {
|
||||
const avatarUpload = "onourjourney.png";
|
||||
|
||||
cy.fixture(avatarUpload, 'base64').then(fileContent => {
|
||||
cy.get('#customdropzone').upload(
|
||||
{ fileContent, fileName: avatarUpload, mimeType: 'image/png' },
|
||||
{ subjectType: 'drag-n-drop' }
|
||||
)
|
||||
})
|
||||
cy.get('.profile-avatar img')
|
||||
.should('have.attr', 'src')
|
||||
.and('contains', 'onourjourney')
|
||||
cy.contains('.iziToast-message', 'Upload successful').should(
|
||||
'have.length',
|
||||
cy.fixture(avatarUpload, "base64").then(fileContent => {
|
||||
cy.get("#customdropzone").upload(
|
||||
{ fileContent, fileName: avatarUpload, mimeType: "image/png" },
|
||||
{ subjectType: "drag-n-drop", force: true }
|
||||
);
|
||||
});
|
||||
cy.get(".profile-avatar img")
|
||||
.should("have.attr", "src")
|
||||
.and("contains", "onourjourney");
|
||||
cy.contains(".iziToast-message", "Upload successful").should(
|
||||
"have.length",
|
||||
1
|
||||
)
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
When("I visit another user's profile page", () => {
|
||||
cy.openPage('profile/peter-pan')
|
||||
})
|
||||
cy.openPage("profile/peter-pan");
|
||||
});
|
||||
|
||||
Then('I cannot upload a picture', () => {
|
||||
cy.get('.ds-card-content')
|
||||
Then("I cannot upload a picture", () => {
|
||||
cy.get(".ds-card-content")
|
||||
.children()
|
||||
.should('not.have.id', 'customdropzone')
|
||||
.should('have.class', 'ds-avatar')
|
||||
})
|
||||
.should("not.have.id", "customdropzone")
|
||||
.should("have.class", "ds-avatar");
|
||||
});
|
||||
|
||||
@ -1,347 +1,364 @@
|
||||
import { Given, When, Then } from 'cypress-cucumber-preprocessor/steps'
|
||||
import { getLangByName } from '../../support/helpers'
|
||||
import { Given, When, Then } from "cypress-cucumber-preprocessor/steps";
|
||||
import { getLangByName } from "../../support/helpers";
|
||||
import slugify from 'slug'
|
||||
|
||||
/* global cy */
|
||||
|
||||
let lastPost = {}
|
||||
let lastPost = {};
|
||||
|
||||
let loginCredentials = {
|
||||
email: 'peterpan@example.org',
|
||||
password: '1234'
|
||||
}
|
||||
email: "peterpan@example.org",
|
||||
password: "1234"
|
||||
};
|
||||
const narratorParams = {
|
||||
name: 'Peter Pan',
|
||||
avatar: 'https://s3.amazonaws.com/uifaces/faces/twitter/nerrsoft/128.jpg',
|
||||
name: "Peter Pan",
|
||||
slug: 'peter-pan',
|
||||
avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/nerrsoft/128.jpg",
|
||||
...loginCredentials
|
||||
}
|
||||
};
|
||||
|
||||
Given('I am logged in', () => {
|
||||
cy.login(loginCredentials)
|
||||
})
|
||||
Given("I am logged in", () => {
|
||||
cy.login(loginCredentials);
|
||||
});
|
||||
|
||||
Given('we have a selection of tags and categories as well as posts', () => {
|
||||
Given("we have a selection of tags and categories as well as posts", () => {
|
||||
cy.factory()
|
||||
.authenticateAs(loginCredentials)
|
||||
.create('Category', {
|
||||
id: 'cat1',
|
||||
name: 'Just For Fun',
|
||||
slug: 'justforfun',
|
||||
icon: 'smile'
|
||||
.create("Category", {
|
||||
id: "cat1",
|
||||
name: "Just For Fun",
|
||||
slug: "justforfun",
|
||||
icon: "smile"
|
||||
})
|
||||
.create('Category', {
|
||||
id: 'cat2',
|
||||
name: 'Happyness & Values',
|
||||
slug: 'happyness-values',
|
||||
icon: 'heart-o'
|
||||
.create("Category", {
|
||||
id: "cat2",
|
||||
name: "Happyness & Values",
|
||||
slug: "happyness-values",
|
||||
icon: "heart-o"
|
||||
})
|
||||
.create('Category', {
|
||||
id: 'cat3',
|
||||
name: 'Health & Wellbeing',
|
||||
slug: 'health-wellbeing',
|
||||
icon: 'medkit'
|
||||
.create("Category", {
|
||||
id: "cat3",
|
||||
name: "Health & Wellbeing",
|
||||
slug: "health-wellbeing",
|
||||
icon: "medkit"
|
||||
})
|
||||
.create('Tag', { id: 't1', name: 'Ecology' })
|
||||
.create('Tag', { id: 't2', name: 'Nature' })
|
||||
.create('Tag', { id: 't3', name: 'Democracy' })
|
||||
.create("Tag", { id: "t1", name: "Ecology" })
|
||||
.create("Tag", { id: "t2", name: "Nature" })
|
||||
.create("Tag", { id: "t3", name: "Democracy" });
|
||||
|
||||
const someAuthor = {
|
||||
id: 'authorId',
|
||||
email: 'author@example.org',
|
||||
password: '1234'
|
||||
}
|
||||
id: "authorId",
|
||||
email: "author@example.org",
|
||||
password: "1234"
|
||||
};
|
||||
const yetAnotherAuthor = {
|
||||
id: 'yetAnotherAuthor',
|
||||
email: 'yet-another-author@example.org',
|
||||
password: '1234'
|
||||
}
|
||||
id: "yetAnotherAuthor",
|
||||
email: "yet-another-author@example.org",
|
||||
password: "1234"
|
||||
};
|
||||
cy.factory()
|
||||
.create('User', someAuthor)
|
||||
.create("User", someAuthor)
|
||||
.authenticateAs(someAuthor)
|
||||
.create('Post', { id: 'p0' })
|
||||
.create('Post', { id: 'p1' })
|
||||
.create("Post", { id: "p0" })
|
||||
.create("Post", { id: "p1" });
|
||||
cy.factory()
|
||||
.create('User', yetAnotherAuthor)
|
||||
.create("User", yetAnotherAuthor)
|
||||
.authenticateAs(yetAnotherAuthor)
|
||||
.create('Post', { id: 'p2' })
|
||||
.create("Post", { id: "p2" });
|
||||
cy.factory()
|
||||
.authenticateAs(loginCredentials)
|
||||
.create('Post', { id: 'p3' })
|
||||
.relate('Post', 'Categories', { from: 'p0', to: 'cat1' })
|
||||
.relate('Post', 'Categories', { from: 'p1', to: 'cat2' })
|
||||
.relate('Post', 'Categories', { from: 'p2', to: 'cat1' })
|
||||
.relate('Post', 'Tags', { from: 'p0', to: 't1' })
|
||||
.relate('Post', 'Tags', { from: 'p0', to: 't2' })
|
||||
.relate('Post', 'Tags', { from: 'p0', to: 't3' })
|
||||
.relate('Post', 'Tags', { from: 'p1', to: 't2' })
|
||||
.relate('Post', 'Tags', { from: 'p1', to: 't3' })
|
||||
.relate('Post', 'Tags', { from: 'p2', to: 't2' })
|
||||
.relate('Post', 'Tags', { from: 'p2', to: 't3' })
|
||||
.relate('Post', 'Tags', { from: 'p3', to: 't3' })
|
||||
})
|
||||
.create("Post", { id: "p3" })
|
||||
.relate("Post", "Categories", { from: "p0", to: "cat1" })
|
||||
.relate("Post", "Categories", { from: "p1", to: "cat2" })
|
||||
.relate("Post", "Categories", { from: "p2", to: "cat1" })
|
||||
.relate("Post", "Tags", { from: "p0", to: "t1" })
|
||||
.relate("Post", "Tags", { from: "p0", to: "t2" })
|
||||
.relate("Post", "Tags", { from: "p0", to: "t3" })
|
||||
.relate("Post", "Tags", { from: "p1", to: "t2" })
|
||||
.relate("Post", "Tags", { from: "p1", to: "t3" })
|
||||
.relate("Post", "Tags", { from: "p2", to: "t2" })
|
||||
.relate("Post", "Tags", { from: "p2", to: "t3" })
|
||||
.relate("Post", "Tags", { from: "p3", to: "t3" });
|
||||
});
|
||||
|
||||
Given('we have the following user accounts:', table => {
|
||||
Given("we have the following user accounts:", table => {
|
||||
table.hashes().forEach(params => {
|
||||
cy.factory().create('User', params)
|
||||
})
|
||||
})
|
||||
cy.factory().create("User", params);
|
||||
});
|
||||
});
|
||||
|
||||
Given('I have a user account', () => {
|
||||
cy.factory().create('User', narratorParams)
|
||||
})
|
||||
Given("I have a user account", () => {
|
||||
cy.factory().create("User", narratorParams);
|
||||
});
|
||||
|
||||
Given('my user account has the role {string}', role => {
|
||||
cy.factory().create('User', {
|
||||
Given("my user account has the role {string}", role => {
|
||||
cy.factory().create("User", {
|
||||
role,
|
||||
...loginCredentials
|
||||
})
|
||||
})
|
||||
});
|
||||
});
|
||||
|
||||
When('I log out', cy.logout)
|
||||
When("I log out", cy.logout);
|
||||
|
||||
When('I visit {string}', page => {
|
||||
cy.openPage(page)
|
||||
})
|
||||
When("I visit {string}", page => {
|
||||
cy.openPage(page);
|
||||
});
|
||||
|
||||
When('I visit the {string} page', page => {
|
||||
cy.openPage(page)
|
||||
})
|
||||
When("I visit the {string} page", page => {
|
||||
cy.openPage(page);
|
||||
});
|
||||
|
||||
Given('I am on the {string} page', page => {
|
||||
cy.openPage(page)
|
||||
})
|
||||
Given("I am on the {string} page", page => {
|
||||
cy.openPage(page);
|
||||
});
|
||||
|
||||
When('I fill in my email and password combination and click submit', () => {
|
||||
cy.login(loginCredentials)
|
||||
})
|
||||
When("I fill in my email and password combination and click submit", () => {
|
||||
cy.login(loginCredentials);
|
||||
});
|
||||
|
||||
When(/(?:when )?I refresh the page/, () => {
|
||||
cy.reload()
|
||||
})
|
||||
cy.reload();
|
||||
});
|
||||
|
||||
When('I log out through the menu in the top right corner', () => {
|
||||
cy.get('.avatar-menu').click()
|
||||
cy.get('.avatar-menu-popover')
|
||||
When("I log out through the menu in the top right corner", () => {
|
||||
cy.get(".avatar-menu").click();
|
||||
cy.get(".avatar-menu-popover")
|
||||
.find('a[href="/logout"]')
|
||||
.click()
|
||||
})
|
||||
.click();
|
||||
});
|
||||
|
||||
Then('I can see my name {string} in the dropdown menu', () => {
|
||||
cy.get('.avatar-menu-popover').should('contain', narratorParams.name)
|
||||
})
|
||||
Then("I can see my name {string} in the dropdown menu", () => {
|
||||
cy.get(".avatar-menu-popover").should("contain", narratorParams.name);
|
||||
});
|
||||
|
||||
Then('I see the login screen again', () => {
|
||||
cy.location('pathname').should('contain', '/login')
|
||||
})
|
||||
Then("I see the login screen again", () => {
|
||||
cy.location("pathname").should("contain", "/login");
|
||||
});
|
||||
|
||||
Then('I can click on my profile picture in the top right corner', () => {
|
||||
cy.get('.avatar-menu').click()
|
||||
cy.get('.avatar-menu-popover')
|
||||
})
|
||||
Then("I can click on my profile picture in the top right corner", () => {
|
||||
cy.get(".avatar-menu").click();
|
||||
cy.get(".avatar-menu-popover");
|
||||
});
|
||||
|
||||
Then('I am still logged in', () => {
|
||||
cy.get('.avatar-menu').click()
|
||||
cy.get('.avatar-menu-popover').contains(narratorParams.name)
|
||||
})
|
||||
Then("I am still logged in", () => {
|
||||
cy.get(".avatar-menu").click();
|
||||
cy.get(".avatar-menu-popover").contains(narratorParams.name);
|
||||
});
|
||||
|
||||
When('I select {string} in the language menu', name => {
|
||||
cy.switchLanguage(name, true)
|
||||
})
|
||||
Given('I previously switched the language to {string}', name => {
|
||||
cy.switchLanguage(name, true)
|
||||
})
|
||||
Then('the whole user interface appears in {string}', name => {
|
||||
const lang = getLangByName(name)
|
||||
cy.get(`html[lang=${lang.code}]`)
|
||||
cy.getCookie('locale').should('have.property', 'value', lang.code)
|
||||
})
|
||||
Then('I see a button with the label {string}', label => {
|
||||
cy.contains('button', label)
|
||||
})
|
||||
When("I select {string} in the language menu", name => {
|
||||
cy.switchLanguage(name, true);
|
||||
});
|
||||
Given("I previously switched the language to {string}", name => {
|
||||
cy.switchLanguage(name, true);
|
||||
});
|
||||
Then("the whole user interface appears in {string}", name => {
|
||||
const lang = getLangByName(name);
|
||||
cy.get(`html[lang=${lang.code}]`);
|
||||
cy.getCookie("locale").should("have.property", "value", lang.code);
|
||||
});
|
||||
Then("I see a button with the label {string}", label => {
|
||||
cy.contains("button", label);
|
||||
});
|
||||
|
||||
When(`I click on {string}`, linkOrButton => {
|
||||
cy.contains(linkOrButton).click()
|
||||
})
|
||||
cy.contains(linkOrButton).click();
|
||||
});
|
||||
|
||||
When(`I click on the menu item {string}`, linkOrButton => {
|
||||
cy.contains('.ds-menu-item', linkOrButton).click()
|
||||
})
|
||||
cy.contains(".ds-menu-item", linkOrButton).click();
|
||||
});
|
||||
|
||||
When('I press {string}', label => {
|
||||
cy.contains(label).click()
|
||||
})
|
||||
When("I press {string}", label => {
|
||||
cy.contains(label).click();
|
||||
});
|
||||
|
||||
Given('we have the following posts in our database:', table => {
|
||||
table.hashes().forEach(({ Author, ...postAttributes }) => {
|
||||
Given("we have the following posts in our database:", table => {
|
||||
table.hashes().forEach(({ Author, ...postAttributes }, i) => {
|
||||
Author = Author || `author-${i}`
|
||||
const userAttributes = {
|
||||
name: Author,
|
||||
email: `${Author}@example.org`,
|
||||
password: '1234'
|
||||
}
|
||||
postAttributes.deleted = Boolean(postAttributes.deleted)
|
||||
const disabled = Boolean(postAttributes.disabled)
|
||||
email: `${slugify(Author, {lower: true})}@example.org`,
|
||||
password: "1234"
|
||||
};
|
||||
postAttributes.deleted = Boolean(postAttributes.deleted);
|
||||
const disabled = Boolean(postAttributes.disabled);
|
||||
cy.factory()
|
||||
.create('User', userAttributes)
|
||||
.create("User", userAttributes)
|
||||
.authenticateAs(userAttributes)
|
||||
.create('Post', postAttributes)
|
||||
.create("Post", postAttributes);
|
||||
if (disabled) {
|
||||
const moderatorParams = {
|
||||
email: 'moderator@example.org',
|
||||
role: 'moderator',
|
||||
password: '1234'
|
||||
}
|
||||
email: "moderator@example.org",
|
||||
role: "moderator",
|
||||
password: "1234"
|
||||
};
|
||||
cy.factory()
|
||||
.create('User', moderatorParams)
|
||||
.create("User", moderatorParams)
|
||||
.authenticateAs(moderatorParams)
|
||||
.mutate('mutation($id: ID!) { disable(id: $id) }', postAttributes)
|
||||
.mutate("mutation($id: ID!) { disable(id: $id) }", postAttributes);
|
||||
}
|
||||
})
|
||||
})
|
||||
});
|
||||
});
|
||||
|
||||
Then('I see a success message:', message => {
|
||||
cy.contains(message)
|
||||
})
|
||||
Then("I see a success message:", message => {
|
||||
cy.contains(message);
|
||||
});
|
||||
|
||||
When('I click on the avatar menu in the top right corner', () => {
|
||||
cy.get('.avatar-menu').click()
|
||||
})
|
||||
When("I click on the avatar menu in the top right corner", () => {
|
||||
cy.get(".avatar-menu").click();
|
||||
});
|
||||
|
||||
When(
|
||||
'I click on the big plus icon in the bottom right corner to create post',
|
||||
"I click on the big plus icon in the bottom right corner to create post",
|
||||
() => {
|
||||
cy.get('.post-add-button').click()
|
||||
cy.get(".post-add-button").click();
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
Given('I previously created a post', () => {
|
||||
Given("I previously created a post", () => {
|
||||
lastPost.title = "previously created post";
|
||||
lastPost.content = "with some content";
|
||||
cy.factory()
|
||||
.authenticateAs(loginCredentials)
|
||||
.create('Post', lastPost)
|
||||
})
|
||||
.create("Post", lastPost);
|
||||
});
|
||||
|
||||
When('I choose {string} as the title of the post', title => {
|
||||
lastPost.title = title.replace('\n', ' ')
|
||||
cy.get('input[name="title"]').type(lastPost.title)
|
||||
})
|
||||
When("I choose {string} as the title of the post", title => {
|
||||
lastPost.title = title.replace("\n", " ");
|
||||
cy.get('input[name="title"]').type(lastPost.title);
|
||||
});
|
||||
|
||||
When('I type in the following text:', text => {
|
||||
lastPost.content = text.replace('\n', ' ')
|
||||
cy.get('.ProseMirror').type(lastPost.content)
|
||||
})
|
||||
When("I type in the following text:", text => {
|
||||
lastPost.content = text.replace("\n", " ");
|
||||
cy.get(".ProseMirror").type(lastPost.content);
|
||||
});
|
||||
|
||||
Then('the post shows up on the landing page at position {int}', index => {
|
||||
cy.openPage('landing')
|
||||
const selector = `.post-card:nth-child(${index}) > .ds-card-content`
|
||||
cy.get(selector).should('contain', lastPost.title)
|
||||
cy.get(selector).should('contain', lastPost.content)
|
||||
})
|
||||
Then("the post shows up on the landing page at position {int}", index => {
|
||||
cy.openPage("landing");
|
||||
const selector = `.post-card:nth-child(${index}) > .ds-card-content`;
|
||||
cy.get(selector).should("contain", lastPost.title);
|
||||
cy.get(selector).should("contain", lastPost.content);
|
||||
});
|
||||
|
||||
Then('I get redirected to {string}', route => {
|
||||
cy.location('pathname').should('contain', route.replace('...', ''))
|
||||
})
|
||||
Then("I get redirected to {string}", route => {
|
||||
cy.location("pathname").should("contain", route.replace("...", ""));
|
||||
});
|
||||
|
||||
Then('the post was saved successfully', () => {
|
||||
cy.get('.ds-card-content > .ds-heading').should('contain', lastPost.title)
|
||||
cy.get('.content').should('contain', lastPost.content)
|
||||
})
|
||||
Then("the post was saved successfully", () => {
|
||||
cy.get(".ds-card-content > .ds-heading").should("contain", lastPost.title);
|
||||
cy.get(".content").should("contain", lastPost.content);
|
||||
});
|
||||
|
||||
Then(/^I should see only ([0-9]+) posts? on the landing page/, postCount => {
|
||||
cy.get('.post-card').should('have.length', postCount)
|
||||
})
|
||||
cy.get(".post-card").should("have.length", postCount);
|
||||
});
|
||||
|
||||
Then('the first post on the landing page has the title:', title => {
|
||||
cy.get('.post-card:first').should('contain', title)
|
||||
})
|
||||
Then("the first post on the landing page has the title:", title => {
|
||||
cy.get(".post-card:first").should("contain", title);
|
||||
});
|
||||
|
||||
Then(
|
||||
'the page {string} returns a 404 error with a message:',
|
||||
"the page {string} returns a 404 error with a message:",
|
||||
(route, message) => {
|
||||
// TODO: how can we check HTTP codes with cypress?
|
||||
cy.visit(route, { failOnStatusCode: false })
|
||||
cy.get('.error').should('contain', message)
|
||||
cy.visit(route, { failOnStatusCode: false });
|
||||
cy.get(".error").should("contain", message);
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
Given('my user account has the following login credentials:', table => {
|
||||
loginCredentials = table.hashes()[0]
|
||||
cy.debug()
|
||||
cy.factory().create('User', loginCredentials)
|
||||
})
|
||||
Given("my user account has the following login credentials:", table => {
|
||||
loginCredentials = table.hashes()[0];
|
||||
cy.debug();
|
||||
cy.factory().create("User", loginCredentials);
|
||||
});
|
||||
|
||||
When('I fill the password form with:', table => {
|
||||
table = table.rowsHash()
|
||||
cy.get('input[id=oldPassword]')
|
||||
.type(table['Your old password'])
|
||||
.get('input[id=newPassword]')
|
||||
.type(table['Your new passsword'])
|
||||
.get('input[id=confirmPassword]')
|
||||
.type(table['Confirm new password'])
|
||||
})
|
||||
When("I fill the password form with:", table => {
|
||||
table = table.rowsHash();
|
||||
cy.get("input[id=oldPassword]")
|
||||
.type(table["Your old password"])
|
||||
.get("input[id=password]")
|
||||
.type(table["Your new passsword"])
|
||||
.get("input[id=passwordConfirmation]")
|
||||
.type(table["Confirm new password"]);
|
||||
});
|
||||
|
||||
When('submit the form', () => {
|
||||
cy.get('form').submit()
|
||||
})
|
||||
When("submit the form", () => {
|
||||
cy.get("form").submit();
|
||||
});
|
||||
|
||||
Then('I cannot login anymore with password {string}', password => {
|
||||
cy.reload()
|
||||
const { email } = loginCredentials
|
||||
cy.visit(`/login`)
|
||||
cy.get('input[name=email]')
|
||||
.trigger('focus')
|
||||
.type(email)
|
||||
cy.get('input[name=password]')
|
||||
.trigger('focus')
|
||||
.type(password)
|
||||
cy.get('button[name=submit]')
|
||||
.as('submitButton')
|
||||
.click()
|
||||
cy.get('.iziToast-wrapper').should('contain', 'Incorrect email address or password.')
|
||||
})
|
||||
Then("I cannot login anymore with password {string}", password => {
|
||||
cy.reload();
|
||||
const { email } = loginCredentials;
|
||||
cy.visit(`/login`);
|
||||
cy.get("input[name=email]")
|
||||
.trigger("focus")
|
||||
.type(email);
|
||||
cy.get("input[name=password]")
|
||||
.trigger("focus")
|
||||
.type(password);
|
||||
cy.get("button[name=submit]")
|
||||
.as("submitButton")
|
||||
.click();
|
||||
cy.get(".iziToast-wrapper").should(
|
||||
"contain",
|
||||
"Incorrect email address or password."
|
||||
);
|
||||
});
|
||||
|
||||
Then('I can login successfully with password {string}', password => {
|
||||
cy.reload()
|
||||
Then("I can login successfully with password {string}", password => {
|
||||
cy.reload();
|
||||
cy.login({
|
||||
...loginCredentials,
|
||||
...{password}
|
||||
})
|
||||
cy.get('.iziToast-wrapper').should('contain', "You are logged in!")
|
||||
})
|
||||
...{ password }
|
||||
});
|
||||
cy.get(".iziToast-wrapper").should("contain", "You are logged in!");
|
||||
});
|
||||
|
||||
When('I log in with the following credentials:', table => {
|
||||
const { email, password } = table.hashes()[0]
|
||||
cy.login({ email, password })
|
||||
})
|
||||
When("I log in with the following credentials:", table => {
|
||||
const { email, password } = table.hashes()[0];
|
||||
cy.login({ email, password });
|
||||
});
|
||||
|
||||
When('open the notification menu and click on the first item', () => {
|
||||
cy.get('.notifications-menu').click()
|
||||
cy.get('.notification-mention-post').first().click()
|
||||
})
|
||||
When("open the notification menu and click on the first item", () => {
|
||||
cy.get(".notifications-menu").click();
|
||||
cy.get(".notification-mention-post")
|
||||
.first()
|
||||
.click();
|
||||
});
|
||||
|
||||
Then('see {int} unread notifications in the top menu', count => {
|
||||
cy.get('.notifications-menu').should('contain', count)
|
||||
})
|
||||
Then("see {int} unread notifications in the top menu", count => {
|
||||
cy.get(".notifications-menu").should("contain", count);
|
||||
});
|
||||
|
||||
Then('I get to the post page of {string}', path => {
|
||||
path = path.replace('...', '')
|
||||
cy.url().should('contain', '/post/')
|
||||
cy.url().should('contain', path)
|
||||
})
|
||||
Then("I get to the post page of {string}", path => {
|
||||
path = path.replace("...", "");
|
||||
cy.url().should("contain", "/post/");
|
||||
cy.url().should("contain", path);
|
||||
});
|
||||
|
||||
When('I start to write a new post with the title {string} beginning with:', (title, intro) => {
|
||||
cy.get('.post-add-button').click()
|
||||
cy.get('input[name="title"]').type(title)
|
||||
cy.get('.ProseMirror').type(intro)
|
||||
})
|
||||
When(
|
||||
"I start to write a new post with the title {string} beginning with:",
|
||||
(title, intro) => {
|
||||
cy.get(".post-add-button").click();
|
||||
cy.get('input[name="title"]').type(title);
|
||||
cy.get(".ProseMirror").type(intro);
|
||||
}
|
||||
);
|
||||
|
||||
When('mention {string} in the text', (mention) => {
|
||||
cy.get('.ProseMirror').type(' @')
|
||||
cy.get('.suggestion-list__item').contains(mention).click()
|
||||
cy.debug()
|
||||
})
|
||||
When("mention {string} in the text", mention => {
|
||||
cy.get(".ProseMirror").type(" @");
|
||||
cy.get(".suggestion-list__item")
|
||||
.contains(mention)
|
||||
.click();
|
||||
cy.debug();
|
||||
});
|
||||
|
||||
Then('the notification gets marked as read', () => {
|
||||
cy.get('.notification').first().should('have.class', 'read')
|
||||
})
|
||||
Then("the notification gets marked as read", () => {
|
||||
cy.get(".notification")
|
||||
.first()
|
||||
.should("have.class", "read");
|
||||
});
|
||||
|
||||
Then('there are no notifications in the top menu', () => {
|
||||
cy.get('.notifications-menu').should('contain', '0')
|
||||
})
|
||||
Then("there are no notifications in the top menu", () => {
|
||||
cy.get(".notifications-menu").should("contain", "0");
|
||||
});
|
||||
|
||||
@ -12,10 +12,10 @@ Feature: Create a post
|
||||
When I click on the big plus icon in the bottom right corner to create post
|
||||
And I choose "My first post" as the title of the post
|
||||
And I type in the following text:
|
||||
"""
|
||||
Human Connection is a free and open-source social network
|
||||
for active citizenship.
|
||||
"""
|
||||
"""
|
||||
Human Connection is a free and open-source social network
|
||||
for active citizenship.
|
||||
"""
|
||||
And I click on "Save"
|
||||
Then I get redirected to ".../my-first-post"
|
||||
And the post was saved successfully
|
||||
|
||||
@ -6,9 +6,9 @@ Feature: Search
|
||||
Background:
|
||||
Given I have a user account
|
||||
And we have the following posts in our database:
|
||||
| Author | id | title | content |
|
||||
| Brianna Wiest | p1 | 101 Essays that will change the way you think | 101 Essays, of course! |
|
||||
| Brianna Wiest | p2 | No searched for content | will be found in this post, I guarantee |
|
||||
| id | title | content |
|
||||
| p1 | 101 Essays that will change the way you think | 101 Essays, of course! |
|
||||
| p2 | No searched for content | will be found in this post, I guarantee |
|
||||
Given I am logged in
|
||||
|
||||
Scenario: Search for specific words
|
||||
|
||||
@ -1,12 +1,15 @@
|
||||
import Factory from '../../backend/src/seed/factories'
|
||||
import { getDriver } from '../../backend/src/bootstrap/neo4j'
|
||||
import setupNeode from '../../backend/src/bootstrap/neode'
|
||||
import neode from 'neode'
|
||||
|
||||
const neo4jDriver = getDriver({
|
||||
const neo4jConfigs = {
|
||||
uri: Cypress.env('NEO4J_URI'),
|
||||
username: Cypress.env('NEO4J_USERNAME'),
|
||||
password: Cypress.env('NEO4J_PASSWORD')
|
||||
})
|
||||
const factory = Factory({ neo4jDriver })
|
||||
}
|
||||
const neo4jDriver = getDriver(neo4jConfigs)
|
||||
const factory = Factory({ seedServerHost, neo4jDriver, neodeInstance: setupNeode(neo4jConfigs)})
|
||||
const seedServerHost = Cypress.env('SEED_SERVER_HOST')
|
||||
|
||||
beforeEach(async () => {
|
||||
@ -14,30 +17,33 @@ beforeEach(async () => {
|
||||
})
|
||||
|
||||
Cypress.Commands.add('factory', () => {
|
||||
return Factory({ seedServerHost })
|
||||
return Factory({ seedServerHost, neo4jDriver, neodeInstance: setupNeode(neo4jConfigs) })
|
||||
})
|
||||
|
||||
Cypress.Commands.add(
|
||||
'create',
|
||||
{ prevSubject: true },
|
||||
(factory, node, properties) => {
|
||||
return factory.create(node, properties)
|
||||
async (factory, node, properties) => {
|
||||
await factory.create(node, properties)
|
||||
return factory
|
||||
}
|
||||
)
|
||||
|
||||
Cypress.Commands.add(
|
||||
'relate',
|
||||
{ prevSubject: true },
|
||||
(factory, node, relationship, properties) => {
|
||||
return factory.relate(node, relationship, properties)
|
||||
async (factory, node, relationship, properties) => {
|
||||
await factory.relate(node, relationship, properties)
|
||||
return factory
|
||||
}
|
||||
)
|
||||
|
||||
Cypress.Commands.add(
|
||||
'mutate',
|
||||
{ prevSubject: true },
|
||||
(factory, mutation, variables) => {
|
||||
return factory.mutate(mutation, variables)
|
||||
async (factory, mutation, variables) => {
|
||||
await factory.mutate(mutation, variables)
|
||||
return factory
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@ -10,6 +10,7 @@ metadata:
|
||||
spec:
|
||||
tls:
|
||||
- hosts:
|
||||
# - nitro-mailserver.human-connection.org
|
||||
- nitro-staging.human-connection.org
|
||||
secretName: tls
|
||||
rules:
|
||||
@ -20,3 +21,10 @@ spec:
|
||||
backend:
|
||||
serviceName: nitro-web
|
||||
servicePort: 3000
|
||||
# - host: nitro-mailserver.human-connection.org
|
||||
# http:
|
||||
# paths:
|
||||
# - path: /
|
||||
# backend:
|
||||
# serviceName: mailserver
|
||||
# servicePort: 80
|
||||
|
||||
@ -32,21 +32,9 @@
|
||||
value: 1G
|
||||
- name: NEO4J_dbms_memory_heap_max__size
|
||||
value: 1G
|
||||
- name: NEO4J_URI
|
||||
valueFrom:
|
||||
configMapKeyRef:
|
||||
name: configmap
|
||||
key: NEO4J_URI
|
||||
- name: NEO4J_USER
|
||||
valueFrom:
|
||||
configMapKeyRef:
|
||||
name: configmap
|
||||
key: NEO4J_USER
|
||||
- name: NEO4J_AUTH
|
||||
valueFrom:
|
||||
configMapKeyRef:
|
||||
name: configmap
|
||||
key: NEO4J_AUTH
|
||||
envFrom:
|
||||
- configMapRef:
|
||||
name: configmap
|
||||
ports:
|
||||
- containerPort: 7687
|
||||
- containerPort: 7474
|
||||
|
||||
18
deployment/human-connection/mailserver/README.md
Normal file
18
deployment/human-connection/mailserver/README.md
Normal file
@ -0,0 +1,18 @@
|
||||
# Development Mail Server
|
||||
|
||||
You can deploy a fake smtp server which captures all send mails and displays
|
||||
them in a web interface. The [sample configuration](../templates/configmap.template.yml)
|
||||
is assuming such a dummy server in the `SMTP_HOST` configuration and points to
|
||||
a cluster-internal SMTP server.
|
||||
|
||||
To deploy the SMTP server just uncomment the relevant code in the
|
||||
[ingress server configuration](../../https/templates/ingress.template.yaml) and
|
||||
run the following:
|
||||
|
||||
```bash
|
||||
# in folder deployment/human-connection
|
||||
kubectl apply -f mailserver/
|
||||
```
|
||||
|
||||
You might need to refresh the TLS secret to enable HTTPS on the publicly
|
||||
available web interface.
|
||||
@ -0,0 +1,34 @@
|
||||
---
|
||||
apiVersion: extensions/v1beta1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: mailserver
|
||||
namespace: human-connection
|
||||
spec:
|
||||
replicas: 1
|
||||
minReadySeconds: 15
|
||||
progressDeadlineSeconds: 60
|
||||
selector:
|
||||
matchLabels:
|
||||
human-connection.org/selector: deployment-human-connection-mailserver
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
human-connection.org/selector: deployment-human-connection-mailserver
|
||||
name: "mailserver"
|
||||
spec:
|
||||
containers:
|
||||
- name: mailserver
|
||||
image: djfarrelly/maildev
|
||||
imagePullPolicy: Always
|
||||
ports:
|
||||
- containerPort: 80
|
||||
- containerPort: 25
|
||||
envFrom:
|
||||
- configMapRef:
|
||||
name: configmap
|
||||
- secretRef:
|
||||
name: human-connection
|
||||
restartPolicy: Always
|
||||
terminationGracePeriodSeconds: 30
|
||||
status: {}
|
||||
@ -0,0 +1,17 @@
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: mailserver
|
||||
namespace: human-connection
|
||||
labels:
|
||||
human-connection.org/selector: deployment-human-connection-mailserver
|
||||
spec:
|
||||
ports:
|
||||
- name: web
|
||||
port: 80
|
||||
targetPort: 80
|
||||
- name: smtp
|
||||
port: 25
|
||||
targetPort: 25
|
||||
selector:
|
||||
human-connection.org/selector: deployment-human-connection-mailserver
|
||||
@ -2,11 +2,12 @@
|
||||
apiVersion: v1
|
||||
kind: ConfigMap
|
||||
data:
|
||||
SMTP_HOST: "mailserver.human-connection"
|
||||
SMTP_PORT: "25"
|
||||
GRAPHQL_PORT: "4000"
|
||||
GRAPHQL_URI: "http://nitro-backend.human-connection:4000"
|
||||
MOCKS: "false"
|
||||
NEO4J_URI: "bolt://nitro-neo4j.human-connection:7687"
|
||||
NEO4J_USER: "neo4j"
|
||||
NEO4J_AUTH: "none"
|
||||
CLIENT_URI: "https://nitro-staging.human-connection.org"
|
||||
metadata:
|
||||
|
||||
@ -5,11 +5,10 @@ data:
|
||||
MONGODB_PASSWORD: "TU9OR09EQl9QQVNTV09SRA=="
|
||||
PRIVATE_KEY_PASSPHRASE: "YTdkc2Y3OHNhZGc4N2FkODdzZmFnc2FkZzc4"
|
||||
MAPBOX_TOKEN: "cGsuZXlKMUlqb2lhSFZ0WVc0dFkyOXVibVZqZEdsdmJpSXNJbUVpT2lKamFqbDBjbkJ1Ykdvd2VUVmxNM1Z3WjJsek5UTnVkM1p0SW4wLktaOEtLOWw3MG9talhiRWtrYkhHc1EK"
|
||||
SMTP_HOST:
|
||||
SMTP_PORT: 587
|
||||
SMTP_USERNAME:
|
||||
SMTP_PASSWORD:
|
||||
SMTP_IGNORE_TLS:
|
||||
NEO4J_USERNAME:
|
||||
NEO4J_PASSWORD:
|
||||
metadata:
|
||||
name: human-connection
|
||||
namespace: human-connection
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user