Repackage Team Module

This commit is contained in:
Barry Low committed 2018-09-01 11:04:04 -07:00
commit a1b4bbe18c
203 files changed
+29564

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
PRISMA_SECRET="prisma-secret"
PRISMA_ENDPOINT="http://localhost:4466"
AUTH0_DOMAIN="auth0-domain"
AUTH0_AUDIENCE="auth0-audience"
AUTH0_ISSUER="auth0-issuer"
+9
View File
@@ -0,0 +1,9 @@
/.env
/database/.env
/database/docker-compose.prisma.prod.yml
/docker-compose.prisma.prod.yml
dist
node_modules
.idea
.vscode
*.log
+12
View File
@@ -0,0 +1,12 @@
projects:
app:
schemaPath: src/schema.graphql
extensions:
endpoints:
dev1:
url: http://localhost:4000/graphql
database:
schemaPath: src/generated/prisma.graphql
extensions:
prisma: database/prisma.yml
+25
View File
@@ -0,0 +1,25 @@
FROM mhart/alpine-node:8
ARG PORT=4000
ARG APP_PATH=/usr/src/app
RUN mkdir -p /usr && \
mkdir -p $APP_PATH && \
mkdir -p $APP_PATH /node_modules
# Use app directory as current workdir
WORKDIR $APP_PATH
# Copy package.json to workdir
COPY package.json .
# Install dependencies
RUN npm install
# Copy application code
COPY . .
RUN NODE_ENV=production npm run start
# Expose Port
EXPOSE $PORT
+114
View File
@@ -0,0 +1,114 @@
# Advance Algos Team GraphQL API Server
This is the Advanced Algos Team Module server-side GraphQL API server. We use Webpack 4 + Docker to develop locally, then build to a distribution bundle that can then be uploaded via FTP, git or used with a continuous integration workflow.
This modules client-side component is the [aateam-client package](../aateam-client#README).
For more information on the general architecture and related technology of this module, please visit this repos [main documenation](../../docs#README).
## Getting Started
Run
```
npm install
```
then
```
npm run dev
```
### Using Docker
Get latest Docker and Docker Compose: [https://docs.docker.com/compose/install/](https://docs.docker.com/compose/install/)
#### Using Docker container for Development
To run starter kit in development mode with hot code reload execute:
Run docker container in background:
```
docker-compose up -d
```
If image issues, try running:
```
docker-compose up --build
```
then run
```
docker-compose up -d
```
To view logs
```
docker-compose logs -f -t
```
Hit Ctrl + c to exit logs without stopping service
To stop service
```
docker-compose down
```
## Overview
The development architecture of the Algobots Community site is to allow both rapid initial development and ongoing rapid-evolution. As with any opinionated workflow, there's a learning curve, but the libraries and architecture of this application have been chosen to maximize collaboration, flexibility, and extensibility.
### Main Libraries
- [*Webpack 4*](https://webpack.js.org/):web application bundler. Allows us to us latest newer JS ECMA features that increase productivity and code clarity. Also allows additional libraries such as modular and programmable CSS via SASS/SCSS/LESS. Provides webserver for local development.
- [*Bulma CSS Framework*](https://bulma.io/documentation/): Bulma is a highly-customizable CSS-only framework allowing us to quickly prototype the layout of a webapp without being complicated by opinionated functionality represented in libraries such as Bootstrap or Material UI. Grants us the flexibility to create a custom look at top speed whilst minimizing baggage.
- [*HyperApp*](https://github.com/hyperapp/hyperapp): Allows a controlled Flux-styled approach to state-management and data-flow through components like React minus the excess boilerplate and learning curve.
- [*Docker*](https://www.docker.com/what-docker)
### File organization
```
. # Top level directory located at your choice
├── src
│ ├── actions # Actions are functions that change the app state
│ ├── assets # images, logos and other static assets
│ ├── state # Schema of state — the single source of truth concerning app state.
│ ├── styles # SASS/SCSS styles
│ ├── utils # Local storage and other utils
│ └── views # Main folder for editing site content
│ ├─ nav # Nav components — header, footer, etc.
│ ├─ pages # Nav components — header, footer, etc.
│ │ ├─ landing # Homepage
│ │ │ ├─ sections # Homepage sections. Collated in its own index.js
│ │ │ └─ index.js # Main homepage component. Pulls in sections
│ │ └─ ... # Other page/component folders
│ └─ index.js # Main view container. Main router
├── html
│ └── index.html # index.html template pulled in by Webpack to attach transpiled bundles
├── index.js # JS entry point to website
│
├── tools # utility scripts, mostly for webpack configuration
│
├── node_modules # created by running `npm install` in this packages root dir
├── dist # created by `npm run develop` - a cache of bundled files served by Webpack for local development
└── build # created by `npm run build` - location of deployable production bundle
```
## Deployment
The simplest deployment is compiling/transpiling the site to a distribution bundle and then uploading the files in the bundle to a web-accessible folder or storage.
For this application we use Webpack to transpile the application which combines and minimizes all code and assets into an optimized bundle without and of the development code and resources.
To build, run:
```
npm run build
```
Looking in this packages directory, there should be a ./build directory with the final built files that can be uploaded.
### Create Docker image
```
docker build -t aateamapi/prod .
```
### Deployment instructions
Coming soon...
@@ -0,0 +1,51 @@
enum Role {
OWNER
MANAGER
MEMBER
}
type Team {
id: ID! @unique
createdAt: DateTime!
name: String! @unique
slug: String! @unique
owner: Member! @relation (name: "TeamOwner", onDelete: CASCADE)
profile: TeamProfile
members: [TeamMembers!]! @relation (name: "TeamMembers", onDelete: SET_NULL)
anonymous: Boolean! @default(value: true)
}
type TeamMembers {
id: ID! @unique
member: Member @relation (name: "MemberOnTeam", onDelete: SET_NULL)
team: Team @relation (name: "TeamMembers", onDelete: SET_NULL)
role: Role @default(value: MEMBER)
}
type TeamProfile {
id: ID! @unique
createdAt: DateTime!
description: String
motto: String
avatar: String
}
type Member {
id: ID! @unique
nickname: String
teams: [TeamMembers!]! @relation (name: "MemberOnTeam", onDelete: SET_NULL)
profile: MemberProfile
auth0id: String! @unique
visible: Boolean! @default(value: false)
anonymous: Boolean! @default(value: true)
}
type MemberProfile {
id: ID! @unique
createdAt: DateTime!
bio: String
status: String
avatar: String
repo: String
email: String
}
+8
View File
@@ -0,0 +1,8 @@
secret: ${env:PRISMA_SECRET}
endpoint: ${env:PRISMA_ENDPOINT}
datamodel: datamodel.graphql
hooks:
post-deploy:
- graphql get-schema --project database
- graphql prepare
@@ -0,0 +1,29 @@
version: '3'
services:
prisma:
image: prismagraphql/prisma:1.15.1
restart: always
ports:
- "4466:4466"
environment:
PRISMA_CONFIG: |
managementApiSecret: PRISMA_SECRET
port: 4466
databases:
default:
connector: postgres
host: postgres
port: 5432
user: prisma
password: prisma
migrations: true
postgres:
image: postgres
restart: always
environment:
POSTGRES_USER: prisma
POSTGRES_PASSWORD: prisma
volumes:
- postgres:/var/lib/postgresql/data
volumes:
postgres:
@@ -0,0 +1,31 @@
version: '3'
services:
node:
image: aateamapi/prod
environment:
- NODE_ENV=production
- GENERATE_SOURCEMAP=false
- APP_PATH=/usr/src/app
- COMPOSE_HTTP_TIMEOUT=2000
- VIRTUAL_HOST=api.algocommunity.org
- LETSENCRYPT_HOST=api.algocommunity.org
- LETSENCRYPT_EMAIL=barry@algocommunity.org
- VIRTUAL_PORT=4000
container_name: aateamapi
tty: true
stdin_open: true
volumes:
- ./:${APP_PATH}
- ${APP_PATH}/build
- ${APP_PATH}/node_modules
working_dir: ${APP_PATH}
restart: always
command: npm run start
expose:
- 4000
- 80
network_mode: webproxy
networks:
default:
external:
name: webproxy
+16
View File
@@ -0,0 +1,16 @@
version: '3'
services:
app:
build:
context: .
dockerfile: Dockerfile
environment:
NODE_ENV: development
ports:
- "4000:4000"
- "3000:3000"
volumes:
- .:/var/www/application
- /var/www/application/node_modules
container_name: aateam-api
+26
View File
@@ -0,0 +1,26 @@
{
"name": "aa-team-api",
"scripts": {
"start": "nodemon -e js,graphql -x node -r dotenv/config src/index.js",
"debug": "nodemon -e js,graphql -x node --inspect -r dotenv/config src/index.js",
"playground": "graphql playground --dotenv dotenv/config",
"dev": "npm-run-all --parallel debug playground"
},
"dependencies": {
"cors": "^2.8.4",
"express-jwt": "^5.3.1",
"graphql-import": "^0.6.0",
"graphql-tools": "3.1.1",
"graphql-yoga": "^1.16.1",
"jsonwebtoken": "^8.3.0",
"jwks-rsa": "^1.3.0",
"lodash.get": "^4.4.2",
"nodemon": "^1.18.3",
"prisma-binding": "2.1.4"
},
"devDependencies": {
"graphql-cli": "^2.16.5",
"npm-run-all": "4.1.3",
"prisma": "^1.14.0"
}
}
+116
View File
@@ -0,0 +1,116 @@
const _get = require('lodash.get')
const validateAndParseIdToken = require('./helpers/validateAndParseIdToken')
const createPrismaMember = require('./index')
const memberLocationOnContext = 'request.member'
const bearerAccessToken = 'request.headers.authorization'
const ctxMember = ctx => _get(ctx, memberLocationOnContext)
const ctxToken = ctx => _get(ctx, bearerAccessToken)
const isLoggedIn = async ctx => {
let member = ctxMember(ctx, memberLocationOnContext)
let token = ctxToken(ctx, bearerAccessToken)
let memberToken
console.log('authenticate.member0: ', ctx.request.headers, member, token)
if (!member && token) {
let scheme, credentials
const tokenParts = token.split(' ')
if (tokenParts.length === 2) {
scheme = tokenParts[0]
credentials = tokenParts[1]
}
if (/^Bearer$/i.test(scheme)) {
token = credentials
//verify token
try {
memberToken = await validateAndParseIdToken(token)
const auth0id = memberToken.sub
console.log('authenticate.member1: ', memberToken, member)
member = await ctx.db.query.member({ where: { auth0id } })
console.log('authenticate.member2: ', memberToken, member)
if (!member) {
member = await createPrismaMember(ctx, memberToken)
}
} catch (err) {
console.log('authenticate.validateAndParseIdToken err: ', err)
memberToken = false
}
}
console.log('isLoggedIn token: ', await memberToken)
}
console.log('member: ', await member)
if (!token && !member) {
throw new Error(`Not logged in`)
}
return member
}
const isRequestingMemberAlsoOwner = ({ ctx, memberId, type, typeId }) =>
ctx.db.exists[type]({ id: typeId, member: { id: memberId } })
const isRequestingMember = ({ ctx, memberId }) => ctx.db.exists.Member({ id: memberId })
const directiveResolvers = {
isAuthenticated: async (next, source, args, ctx) => {
let result = await isLoggedIn(ctx)
console.log('isAuthenticated: ', result)
return next()
},
hasRole: (next, source, { roles }, ctx) => {
const { role } = isLoggedIn(ctx)
if (roles.includes(role)) {
return next()
}
throw new Error(`Unauthorized, incorrect role`)
},
isOwner: async (next, source, { type }, ctx) => {
const { id: typeId } =
source && source.id
? source
: ctx.request.body.variables ? ctx.request.body.variables : { id: null }
const { id: memberId } = isLoggedIn(ctx)
const isOwner =
type === `Member`
? memberId === typeId
: await isRequestingMemberAlsoOwner({ ctx, memberId, type, typeId })
if (isOwner) {
return next()
}
throw new Error(`Unauthorized, must be owner`)
},
isOwnerOrHasRole: async (next, source, { roles, type }, ctx, ...p) => {
const { id: memberId, role } = isLoggedIn(ctx)
if (roles.includes(role)) {
return next()
}
const { id: typeId } = ctx.request.body.variables
const isOwner = await isRequestingMemberAlsoOwner({
ctx,
memberId,
type,
typeId
})
if (isOwner) {
return next()
}
const hasRole = await isRequestingMember({
ctx,
memberId,
type,
typeId
})
if(hasRole){
return next()
}
throw new Error(`Unauthorized, not owner or incorrect role`)
}
}
module.exports = { directiveResolvers }
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,29 @@
const jwksClient = require('jwks-rsa')
const jwt = require('jsonwebtoken')
const jwks = jwksClient({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 1,
jwksUri: `https://${process.env.AUTH0_DOMAIN}/.well-known/jwks.json`
})
const validateAndParseIdToken = idToken =>
new Promise((resolve, reject) => {
const { header, payload } = jwt.decode(idToken, { complete: true })
if (!header || !header.kid || !payload) reject(new Error('Invalid Token'))
jwks.getSigningKey(header.kid, (err, key) => {
if (err) reject(new Error('Error getting signing key: ' + err.message))
jwt.verify(
idToken,
key.publicKey,
{ algorithms: ['RS256'] },
(err, decoded) => {
if (err) reject('jwt verify error: ' + err.message)
console.log('jwks-verify: ', decoded)
resolve(decoded)
}
)
})
})
module.exports = validateAndParseIdToken
+237
View File
@@ -0,0 +1,237 @@
const { GraphQLServer } = require('graphql-yoga')
const {
Prisma,
extractFragmentReplacements,
forwardTo
} = require('prisma-binding')
const { makeExecutableSchema } = require('graphql-tools')
const { importSchema } = require('graphql-import')
const { checkJwt } = require('./middleware/jwt')
const { getMember } = require('./middleware/getMember')
const validateAndParseIdToken = require('./helpers/validateAndParseIdToken')
const { directiveResolvers } = require('./directives')
const createPrismaMember = async function (ctx, info, idToken) {
console.log('createPrismaMember', idToken)
const member = await ctx.db.mutation.upsertMember({
where: {
auth0id: idToken.sub,
},
create: {
auth0id: idToken.sub,
nickname: idToken.nickname,
profile: {
create: {
email: idToken.email,
avatar: idToken.picture
}
}
},
update: {
auth0id: idToken.sub,
nickname: idToken.nickname,
profile: {
update: {
email: idToken.email,
avatar: idToken.picture
}
}
}
}, info)
return member
}
const ctxMember = ctx => ctx.request.member
const resolvers = {
Query: {
async member(parent, { auth0id }, ctx, info) {
return ctx.db.query.member({ where: { auth0id } }, info)
},
teams(parent, args, ctx, info) {
return ctx.db.query.teamsConnection({},
`{
edges {
node {
id
name
slug
profile {
avatar
description
motto
}
owner {
nickname
visible
profile {
avatar
}
}
members {
role
member {
nickname
visible
profile {
avatar
}
}
}
}
}
}`)
},
async teamById(parent, { id }, ctx, info) {
return ctx.db.query.team({ where: { id } }, info)
},
async teamByName(parent, { name }, ctx, info) {
return ctx.db.query.team({ where: { name: name } }, `{ name }`)
},
async teamByOwner(parent, { ownerId }, ctx, info) {
return ctx.db.query.teamsConnection({where: { owner: { auth0id: ownerId }}},
`{
edges {
node {
id
name
slug
profile {
avatar
description
motto
}
owner {
auth0id
nickname
visible
profile {
avatar
}
}
members {
role
member {
nickname
visible
profile {
avatar
}
}
}
}
}
}`)
},
async owner(parent, args, ctx, info) {
console.log('resolver.query.owner ctx: ', ctxMember(ctx))
return ctx.db.query.member({ where: { id: ctxMember(ctx).auth0id } }, info)
},
members: forwardTo('db')
},
Mutation: {
async authenticate(parent, { idToken }, ctx, info) {
let memberToken = null
try {
memberToken = await validateAndParseIdToken(idToken)
console.log('authenticate.memberToken: ', await memberToken)
} catch (err) {
console.log('authenticat.validateAndParseIdToken err: ', err)
throw new Error(err.message)
}
const auth0id = memberToken.sub
let member = await ctx.db.query.member({ where: { auth0id } }, info)
if (!member) {
try {
return createPrismaMember(ctx, info, memberToken)
} catch (error) {
try {
return createPrismaMember(ctx, info, memberToken)
} catch (error) {
throw new Error(error.message)
}
}
}
return member
},
async createTeam(parent, { name, slug, owner }, ctx, info) {
ctx.db.mutation.createTeam({
data: {
name: name,
slug: slug,
owner: {connect:{auth0id: owner}},
members: {create: {role: 'OWNER', member: {connect: {auth0id: owner}}}}
}
}, info)
},
async deleteTeam(parent, { id, owner }, ctx, info) {
ctx.db.mutation.deleteTeam({ where: { id, member: {where: { auth0id: owner } } } }, owner)
}
}
}
const db = new Prisma({
fragmentReplacements: extractFragmentReplacements(resolvers),
typeDefs: 'src/generated/prisma.graphql',
endpoint: process.env.PRISMA_ENDPOINT,
secret: process.env.PRISMA_SECRET,
debug: true
})
console.log(process.env.PRISMA_ENDPOINT)
const schema = makeExecutableSchema({
typeDefs: importSchema('src/schema.graphql'),
resolvers,
resolverValidationOptions :{ requireResolversForResolveType: false },
directiveResolvers
})
const server = new GraphQLServer({
schema,
context: req => ({
...req,
db
})
})
server.express.post(
server.options.endpoint,
checkJwt,
(err, req, res, next) => {
console.log('server.express.post:',err, req, res, next, req.token)
if (err) return res.status(401).send(err.message)
next()
}
)
server.express.post(server.options.endpoint, (req, res, done) =>
getMember(req, res, done, db)
)
const whitelist = [
'http://localhost:8000',
'http://localhost:1337',
'http://localhost:3000',
'http://localhost:4000',
'http://0.0.0.0:5000'
]
const corsOptionsDelegate = (req, callback) => {
var corsOptions
if (whitelist.indexOf(req.header('Origin')) !== -1) {
corsOptions = { origin: true, credentials: true } // reflect (enable) the requested origin in the CORS response
} else {
corsOptions = { origin: false, credentials: true } // disable CORS for this request
}
callback(null, corsOptions) // callback expects two parameters: error and options
}
const options = {
cors: corsOptionsDelegate,
endpoint: '/graphql',
subscriptions: '/graphql',
playground: '/playground'
}
server.start(options, () => console.log(`Server is running on http://localhost:4000${server.options.endpoint}`))
module.exports= { createPrismaMember }
@@ -0,0 +1,10 @@
const getMember = async (req, res, next, db) => {
if (!req.user) return next()
const member = await db.query.member({
where: { auth0id: req.user.sub }
})
req.user = { token: req.member, ...member }
next()
}
module.exports = { getMember }
+24
View File
@@ -0,0 +1,24 @@
const jwt = require('express-jwt')
const jwksRsa = require('jwks-rsa')
// Authentication middleware. When used, the
// if the access token exists, it be verified against
// the Auth0 JSON Web Key Set
const checkJwt = jwt({
// Dynamically provide a signing key
// based on the kid in the header and
// the signing keys provided by the JWKS endpoint.
secret: jwksRsa.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 1,
jwksUri: `https://${process.env.AUTH0_DOMAIN}/.well-known/jwks.json`
}),
// Validate the audience and the issuer.
credentialsRequired: false,
audience: process.env.AUTH0_AUDIENCE,
issuer: process.env.AUTH0_ISSUER,
algorithms: [`RS256`]
})
module.exports = { checkJwt }
+35
View File
@@ -0,0 +1,35 @@
# import Query.members, Query.TeamConnection, Team from "./generated/prisma.graphql"
directive @isAuthenticated on QUERY | FIELD | MUTATION
directive @hasRole(roles: [String]) on QUERY | FIELD | MUTATION
directive @isOwner(type: String) on QUERY | MUTATION
directive @isOwnerOrHasRole(type: String, roles: [String]) on QUERY | MUTATION
type Query {
teams: TeamConnection
teamDetails: [Team!]! @isAuthenticated
teamByName(name: String!): Team
teamById(teamId: String!): Team
teamByOwner(ownerId: String!): TeamConnection
owner: Member @isAuthenticated
member(auth0id: String!): Member @isAuthenticated
}
type Mutation {
authenticate(idToken: String!): Member
createTeam(name: String!, slug: String, owner: String): Team @isAuthenticated
deleteTeam(id: ID!, owner: String!): Team @isOwnerOrHasRole(type: "Member", roles: ["OWNER"])
updateProfile(data: MemberProfileInput): Member @isAuthenticated
}
input MemberProfileInput {
auth0id: String!
nickname: String!
anonymous: Boolean
visible: Boolean
avatar: String
email: String
repo: String
bio: String
status: String
}