Server: Fix Mutation authorization

This commit is contained in:
Barry Low committed 2018-09-13 23:55:57 -07:00
1 parent f7c5e9cc70
commit 758e5bdb83
9 files changed
+88 -93

No files matched your search

+2 -2
View File
@@ -1,7 +1,7 @@
const _get = require('lodash.get')
const { validateIdToken } = require('./validateIdToken')
const memberLocationOnContext = 'request.member'
const memberLocationOnContext = 'request.user'
const bearerAccessToken = 'request.headers.authorization'
const ctxMember = ctx => _get(ctx, memberLocationOnContext)
@@ -29,7 +29,7 @@ const isLoggedIn = async ctx => {
let member = ctxMember(ctx, memberLocationOnContext)
let token = ctxToken(ctx, bearerAccessToken)
let memberToken
console.log('isLoggedIn: ', member, token)
console.log('isLoggedIn: ', ctx, member, token)
if (!member && token) {
let scheme, credentials
const tokenParts = token.split(' ')
+2 -2
View File
@@ -1,9 +1,9 @@
const getMember = async (req, res, next, db) => {
if (!req.user) return next()
const member = await db.query.member({
where: { auth0id: req.user.sub }
where: { authId: req.user.sub }
})
req.user = { token: req.user, ...member }
req.user = { user: member }
next()
}
+1 -1
View File
@@ -21,4 +21,4 @@ const checkJwt = jwt({
algorithms: [`RS256`]
})
module.exports = { checkJwt }
module.exports = checkJwt
+37 -37
View File
@@ -7,7 +7,8 @@ const {
} = require('prisma-binding')
const { makeExecutableSchema } = require('graphql-tools')
const { importSchema } = require('graphql-import')
const { checkJwt } = require('./auth/middleware/jwt')
const checkJwt = require('./auth/middleware/jwt')
const { getMember } = require('./auth/middleware/getMember')
const { validateIdToken } = require('./auth/validateIdToken')
const { directiveResolvers } = require('./auth/authDirectives')
@@ -30,7 +31,7 @@ const createMember = async function (ctx, info, idToken) {
return member
}
const ctxMember = ctx => ctx.request.member
const ctxMember = ctx => ctx.request.user
const resolvers = {
Query: {
@@ -82,35 +83,32 @@ const resolvers = {
return ctx.db.query.team({ where: { name: name } }, `{ name }`)
},
async teamsByOwner(parent, { ownerId }, ctx, info) {
return ctx.db.query.teamsConnection({where: { owner: { authId: ownerId }}},
console.log('teamsByOwner: ', ctx.user)
return ctx.db.query.teams({where: { owner: ownerId }},
`{
edges {
node {
id
name
slug
owner
status {
status
reason
createdAt
}
id
name
slug
owner
status {
status
reason
createdAt
profile {
avatar
description
motto
updatedAt
}
members {
role
member {
alias
authId
}
}
createdAt
profile {
avatar
description
motto
updatedAt
}
members {
role
member {
alias
authId
}
}
}
}`)
},
async owner(parent, args, ctx, info) {
@@ -189,25 +187,27 @@ const schema = makeExecutableSchema({
const server = new GraphQLServer({
schema,
context: req => ({
...req,
db
token: req.headers,
user: req.user,
db,
...req
}),
})
server.express.use(
server.options.endpoint,
checkJwt,
(err, req, res, next) => {
console.log('checkJwt: ', err, req.user)
if (err) return res.status(401).send(err.message)
next()
function (err, req, res, next) {
console.log('checkJwt: ', err, req)
if (err) {
return res.status(201).send(err.message)
} else {
next()
}
}
)
server.express.post(server.options.endpoint, (err, req, res, done) => {
console.log('getMember: ', err, req.user)
getMember(req, res, done, db)
})
server.express.post(server.options.endpoint, (req, res, done) => getUser(req, res, done, db))
const whitelist = [
'http://localhost:3000',
+1 -1
View File
@@ -10,7 +10,7 @@ type Query {
teamDetails: [Team!]! @isAuthenticated
teamByName(name: String!): Team
teamById(teamId: String!): Team
teamsByOwner(ownerId: String!): TeamConnection
teamsByOwner(ownerId: String!): [Team!]! @isAuthenticated
owner: Member @isAuthenticated
currentMember: Member @isAuthenticated
member(authId: String!): Member @isAuthenticated
+4 -4
View File
@@ -103,7 +103,7 @@ class Auth {
this.cb(data)
console.log(authResult.idTokenPayload)
const user = {
authID: authResult.idTokenPayload.sub,
authId: authResult.idTokenPayload.sub,
alias: authResult.idTokenPayload.nickname
}
setItem('user', JSON.stringify(user))
@@ -131,8 +131,8 @@ class Auth {
console.log('signinOrCreateAccount auth: ', await data)
const user = {
authID: data.data.authenticate.authId,
alias: data.data.authenticate.authId.alias
authId: data.data.authenticate.authId,
alias: data.data.authenticate.alias
}
setItem('user', JSON.stringify(user))
if (window.location.href.includes(`callback`)) {
@@ -176,7 +176,7 @@ class Auth {
.then(result => {
console.log('handleAuth.checksessions: ', result)
const user = {
authID: result.idTokenPayload.sub,
authId: result.idTokenPayload.sub,
alias: result.idTokenPayload.nickname
}
setItem('user', JSON.stringify(user))
@@ -4,31 +4,27 @@ import gql from 'graphql-tag'
export const GET_TEAMS_BY_OWNER = gql`
query teamsByOwnerQuery($authId: String!) {
teamsByOwner(ownerId: $authId) {
edges {
node {
id
name
slug
owner
status {
status
reason
createdAt
}
createdAt
profile {
avatar
description
motto
updatedAt
}
members {
role
member {
alias
authId
}
}
id
name
slug
owner
status {
status
reason
createdAt
}
createdAt
profile {
avatar
description
motto
updatedAt
}
members {
role
member {
alias
authId
}
}
}
@@ -4,6 +4,7 @@ import { Mutation } from 'react-apollo'
import Typography from '@material-ui/core/Typography'
import { getItem } from '../../../utils/local-storage'
import { checkGraphQLError } from '../../../utils/graphql-errors'
import CREATE_TEAM from '../../../graphql/teams/CreateTeamMutation'
import GET_TEAMS_BY_OWNER from '../../../graphql/teams/GetTeamsByOwnerQuery'
@@ -15,11 +16,10 @@ const CreateTeam = () => {
<Mutation
mutation={CREATE_TEAM}
update={(cache, { data: { createTeam } }) => {
const { teamsByOwner } = cache.readQuery({ query: GET_TEAMS_BY_OWNER })
cache.writeQuery({
query: GET_TEAMS_BY_OWNER,
data: { teamsByOwner: teamsByOwner.concat([createTeam]) }
})
const data = cache.readQuery({ query: GET_TEAMS_BY_OWNER })
console.log('Mutation cache update: ', createTeam, data)
data.getTeamsByOwner.push(createTeam)
cache.writeQuery({ query: GET_TEAMS_BY_OWNER, data })
}}
>
{(createTeam, { loading, error, data }) => {
@@ -29,9 +29,13 @@ const CreateTeam = () => {
loader = (<Typography variant='caption'>Submitting team...</Typography>)
}
if (error) {
errors = error.graphQLErrors.map(({ message }, i) => (
<Typography key={i} variant='caption'>{message}</Typography>
))
errors = error.graphQLErrors.map(({ message }, i) => {
const displayMessage = checkGraphQLError(message)
console.log('createTeam error:', displayMessage)
return (
<Typography key={i} variant='caption'>{message}</Typography>
)
})
}
return (
<div>
@@ -60,7 +64,7 @@ const handleSubmit = async (e, createTeam, input) => {
e.preventDefault()
const currentUser = await getItem('user')
let authId = JSON.parse(currentUser)
authId = authId.sub
authId = authId.authId
const name = input.value
const slug = slugify(name)
await createTeam({ variables: { name, slug, owner: authId } })
@@ -5,15 +5,12 @@ import { withStateHandlers, lifecycle, compose } from 'recompose'
import Typography from '@material-ui/core/Typography'
import Grid from '@material-ui/core/Grid'
import Card from '@material-ui/core/Card'
import CardContent from '@material-ui/core/CardContent'
import GET_TEAMS_BY_OWNER from '../../../graphql/teams/GetTeamsByOwnerQuery'
import DashTeamItem from './DashTeamItem'
import CreateTeamWrapper from './CreateTeamWrapper'
import { checkGraphQLError } from '../../../utils/graphql-errors'
import { isDefined, isString } from '../../../utils/js-helpers'
import { getItem } from '../../../utils/local-storage'
@@ -21,12 +18,14 @@ export const DashTeam = ({ classes, user = null }) => {
let owner
let loader
let authId = null
console.log('DashTeam: ', user)
if (user !== null && isString(user)) {
owner = JSON.parse(user)
if (isDefined(owner.authId)) authId = owner.authId
} else {
loader = (<Typography variant='caption'>Loading...</Typography>)
}
console.log('DashTeam 2: ', owner, authId)
if (authId === null) {
return (
@@ -43,6 +42,7 @@ export const DashTeam = ({ classes, user = null }) => {
<Typography variant='display1' gutterBottom>
Teams
</Typography>
<CreateTeamWrapper />
<Query query={GET_TEAMS_BY_OWNER} variables={{ authId }}>
{({ loading, error, data }) => {
console.log('GET_TEAMS_BY_OWNER: ', loading, error, data)
@@ -50,17 +50,16 @@ export const DashTeam = ({ classes, user = null }) => {
let queryLoader
if (error) {
errors = error.graphQLErrors.map(({ message }, i) => {
const displayMessage = checkGraphQLError(message)
return (
<Typography key={i} variant='caption'>{displayMessage}</Typography>
<Typography key={i} variant='caption'>{message}</Typography>
)
})
}
if (!loading) {
if (data.teamsByOwner.edges.length > 0) {
if (!loading && !error) {
if (data.teamsByOwner.length > 0) {
return (
<Grid container spacing={24}>
{!loading && data.teamsByOwner.edges.map(team => (
{!loading && data.teamsByOwner.map(team => (
<DashTeamItem key={team.id} />
))}
{queryLoader}
@@ -68,10 +67,6 @@ export const DashTeam = ({ classes, user = null }) => {
{loader}
</Grid>
)
} else {
return (
<CreateTeamWrapper />
)
}
} else {
return (