Skip to content

Commit

Permalink
fix(auth): correctly return user ctx
Browse files Browse the repository at this point in the history
  • Loading branch information
Silthus committed Feb 7, 2024
1 parent bfa9252 commit d1a297c
Show file tree
Hide file tree
Showing 23 changed files with 450 additions and 456 deletions.
30 changes: 15 additions & 15 deletions src/__tests__/areas.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import {ApolloServer} from 'apollo-server-express'
import { ApolloServer } from 'apollo-server-express'
import muuid from 'uuid-mongodb'
import {jest} from '@jest/globals'
import { jest } from '@jest/globals'
import MutableAreaDataSource from '../model/MutableAreaDataSource.js'
import MutableOrganizationDataSource from '../model/MutableOrganizationDataSource.js'
import {AreaType} from '../db/AreaTypes.js'
import {OrganizationEditableFieldsType, OrganizationType, OrgType} from '../db/OrganizationTypes.js'
import {queryAPI, setUpServer} from '../utils/testUtils.js'
import {muuidToString} from '../utils/helpers.js'
import {InMemoryDB} from "../utils/inMemoryDB.js";
import express from "express";
import { AreaType } from '../db/AreaTypes.js'
import { OrganizationEditableFieldsType, OrganizationType, OrgType } from '../db/OrganizationTypes.js'
import { queryAPI, setUpServer } from '../utils/testUtils.js'
import { muuidToString } from '../utils/helpers.js'
import { InMemoryDB } from '../utils/inMemoryDB.js'
import express from 'express'

jest.setTimeout(60000)

Expand All @@ -27,7 +27,7 @@ describe('areas API', () => {
let wa: AreaType

beforeAll(async () => {
({server, inMemoryDB, app} = await setUpServer())
({ server, inMemoryDB, app } = await setUpServer())
// Auth0 serializes uuids in "relaxed" mode, resulting in this hex string format
// "59f1d95a-627d-4b8c-91b9-389c7424cb54" instead of base64 "WfHZWmJ9S4yRuTicdCTLVA==".
user = muuid.mode('relaxed').v4()
Expand Down Expand Up @@ -69,17 +69,17 @@ describe('areas API', () => {
excludedAreaIds: [ca.metadata.area_id]
}
alphaOrg = await organizations.addOrganization(user, OrgType.localClimbingOrganization, alphaFields)
.then((res: OrganizationType | null) => {
if (res === null) throw new Error('Failure mocking organization.')
return res
})
.then((res: OrganizationType | null) => {
if (res === null) throw new Error('Failure mocking organization.')
return res
})
})

it('retrieves an area and lists associated organizations', async () => {
const response = await queryAPI({
query: areaQuery,
operationName: 'area',
variables: {input: wa.metadata.area_id},
variables: { input: wa.metadata.area_id },
userUuid,
app
})
Expand All @@ -95,7 +95,7 @@ describe('areas API', () => {
const response = await queryAPI({
query: areaQuery,
operationName: 'area',
variables: {input: ca.metadata.area_id},
variables: { input: ca.metadata.area_id },
userUuid,
app
})
Expand Down
22 changes: 11 additions & 11 deletions src/__tests__/history.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import {ApolloServer} from 'apollo-server-express'
import { ApolloServer } from 'apollo-server-express'
import muuid from 'uuid-mongodb'
import {jest} from '@jest/globals'
import { jest } from '@jest/globals'
import MutableAreaDataSource from '../model/MutableAreaDataSource.js'
import MutableOrganizationDataSource from '../model/MutableOrganizationDataSource.js'
import MutableClimbDataSource from '../model/MutableClimbDataSource.js'
import {AreaType} from '../db/AreaTypes.js'
import {OrganizationType, OrgType} from '../db/OrganizationTypes.js'
import {muuidToString} from '../utils/helpers.js'
import {queryAPI, setUpServer} from '../utils/testUtils.js'
import {InMemoryDB} from "../utils/inMemoryDB.js";
import express from "express";
import { AreaType } from '../db/AreaTypes.js'
import { OrganizationType, OrgType } from '../db/OrganizationTypes.js'
import { muuidToString } from '../utils/helpers.js'
import { queryAPI, setUpServer } from '../utils/testUtils.js'
import { InMemoryDB } from '../utils/inMemoryDB.js'
import express from 'express'

jest.setTimeout(60000)

Expand All @@ -26,7 +26,7 @@ describe('history API', () => {
let climbs: MutableClimbDataSource

beforeAll(async () => {
({server, inMemoryDB, app} = await setUpServer())
({ server, inMemoryDB, app } = await setUpServer())
// Auth0 serializes uuids in "relaxed" mode, resulting in this hex string format
// "59f1d95a-627d-4b8c-91b9-389c7424cb54" instead of base64 "WfHZWmJ9S4yRuTicdCTLVA==".
user = muuid.mode('relaxed').v4()
Expand Down Expand Up @@ -104,12 +104,12 @@ describe('history API', () => {
email: '[email protected]'
}
alphaOrg = await organizations.addOrganization(user, OrgType.localClimbingOrganization, alphaFields)
climbIds = await climbs.addOrUpdateClimbs(user, ca.metadata.area_id, [{name: 'Alpha Climb'}])
climbIds = await climbs.addOrUpdateClimbs(user, ca.metadata.area_id, [{ name: 'Alpha Climb' }])

// Query for changes and ensure they are tracked.
const resp = await queryAPI({
query: QUERY_RECENT_CHANGE_HISTORY,
variables: {filter: {}},
variables: { filter: {} },
userUuid,
app
})
Expand Down
58 changes: 29 additions & 29 deletions src/__tests__/organizations.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import {ApolloServer} from 'apollo-server-express'
import { ApolloServer } from 'apollo-server-express'
import muuid from 'uuid-mongodb'
import MutableAreaDataSource from '../model/MutableAreaDataSource.js'
import MutableOrganizationDataSource from '../model/MutableOrganizationDataSource.js'
import {AreaType} from '../db/AreaTypes.js'
import {OperationType, OrganizationEditableFieldsType, OrganizationType, OrgType} from '../db/OrganizationTypes.js'
import {changelogDataSource} from '../model/ChangeLogDataSource.js'
import {queryAPI, setUpServer} from '../utils/testUtils.js'
import {muuidToString} from '../utils/helpers.js'
import {validate as validateMuuid} from 'uuid'
import {InMemoryDB} from "../utils/inMemoryDB.js";
import express from "express";
import { AreaType } from '../db/AreaTypes.js'
import { OperationType, OrganizationEditableFieldsType, OrganizationType, OrgType } from '../db/OrganizationTypes.js'
import { changelogDataSource } from '../model/ChangeLogDataSource.js'
import { queryAPI, setUpServer } from '../utils/testUtils.js'
import { muuidToString } from '../utils/helpers.js'
import { validate as validateMuuid } from 'uuid'
import { InMemoryDB } from '../utils/inMemoryDB.js'
import express from 'express'

describe('organizations API', () => {
let server: ApolloServer
Expand All @@ -26,7 +26,7 @@ describe('organizations API', () => {
let wa: AreaType

beforeAll(async () => {
({server, inMemoryDB, app} = await setUpServer())
({ server, inMemoryDB, app } = await setUpServer())
// Auth0 serializes uuids in "relaxed" mode, resulting in this hex string format
// "59f1d95a-627d-4b8c-91b9-389c7424cb54" instead of base64 "WfHZWmJ9S4yRuTicdCTLVA==".
user = muuid.mode('relaxed').v4()
Expand Down Expand Up @@ -85,7 +85,7 @@ describe('organizations API', () => {
const createResponse = await queryAPI({
query: createQuery,
operationName: 'addOrganization',
variables: {input: {displayName: 'Friends of Openbeta', orgType: 'LOCAL_CLIMBING_ORGANIZATION'}},
variables: { input: { displayName: 'Friends of Openbeta', orgType: 'LOCAL_CLIMBING_ORGANIZATION' } },
userUuid,
roles: ['user_admin'],
app
Expand Down Expand Up @@ -165,7 +165,7 @@ describe('organizations API', () => {
const response = await queryAPI({
query: createQuery,
operationName: 'addOrganization',
variables: {input: {displayName: 'Friends of Openbeta', orgType: 'LOCAL_CLIMBING_ORGANIZATION'}},
variables: { input: { displayName: 'Friends of Openbeta', orgType: 'LOCAL_CLIMBING_ORGANIZATION' } },
userUuid,
roles: ['editor'],
app
Expand Down Expand Up @@ -222,38 +222,38 @@ describe('organizations API', () => {
hardwareReportLink: 'https://alphaopenbeta.com/reporthardware'
}
alphaOrg = await organizations.addOrganization(user, OrgType.localClimbingOrganization, alphaFields)
.then((res: OrganizationType | null) => {
if (res === null) throw new Error('Failure mocking organization.')
return res
})
.then((res: OrganizationType | null) => {
if (res === null) throw new Error('Failure mocking organization.')
return res
})

deltaFields = {
displayName: 'Delta OpenBeta Club',
email: '[email protected]'
}
deltaOrg = await organizations.addOrganization(user, OrgType.localClimbingOrganization, deltaFields)
.then((res: OrganizationType | null) => {
if (res === null) throw new Error('Failure mocking organization.')
return res
})
.then((res: OrganizationType | null) => {
if (res === null) throw new Error('Failure mocking organization.')
return res
})

gammaFields = {
displayName: 'Delta Gamma OpenBeta Club',
description: 'We are an offshoot of the delta club.\nSee our website for more details.',
excludedAreaIds: [wa.metadata.area_id]
}
gammaOrg = await organizations.addOrganization(user, OrgType.localClimbingOrganization, gammaFields)
.then((res: OrganizationType | null) => {
if (res === null) throw new Error('Failure mocking organization.')
return res
})
.then((res: OrganizationType | null) => {
if (res === null) throw new Error('Failure mocking organization.')
return res
})
})

it('retrieves an organization with an MUUID', async () => {
const response = await queryAPI({
query: organizationQuery,
operationName: 'organization',
variables: {input: muuidToString(alphaOrg.orgId)},
variables: { input: muuidToString(alphaOrg.orgId) },
userUuid,
app
})
Expand All @@ -272,7 +272,7 @@ describe('organizations API', () => {
const response = await queryAPI({
query: organizationsQuery,
operationName: 'organizations',
variables: {filter: {displayName: {match: 'Delta OpenBeta Club', exactMatch: true}}},
variables: { filter: { displayName: { match: 'Delta OpenBeta Club', exactMatch: true } } },
userUuid,
app
})
Expand All @@ -287,7 +287,7 @@ describe('organizations API', () => {
const response = await queryAPI({
query: organizationsQuery,
operationName: 'organizations',
variables: {filter: {displayName: {match: 'delta', exactMatch: false}}},
variables: { filter: { displayName: { match: 'delta', exactMatch: false } } },
userUuid,
app
})
Expand Down Expand Up @@ -316,7 +316,7 @@ describe('organizations API', () => {
const response = await queryAPI({
query: organizationsQuery,
operationName: 'organizations',
variables: {filter: {associatedAreaIds: {includes: [muuidToString(ca.metadata.area_id)]}}},
variables: { filter: { associatedAreaIds: { includes: [muuidToString(ca.metadata.area_id)] } } },
userUuid,
app
})
Expand All @@ -331,7 +331,7 @@ describe('organizations API', () => {
const response = await queryAPI({
query: organizationsQuery,
operationName: 'organizations',
variables: {filter: {excludedAreaIds: {excludes: [muuidToString(wa.metadata.area_id)]}}},
variables: { filter: { excludedAreaIds: { excludes: [muuidToString(wa.metadata.area_id)] } } },
userUuid,
app
})
Expand Down
26 changes: 13 additions & 13 deletions src/__tests__/ticks.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import {ApolloServer} from 'apollo-server-express'
import { ApolloServer } from 'apollo-server-express'
import muuid from 'uuid-mongodb'
import {jest} from '@jest/globals'
import {queryAPI, setUpServer} from '../utils/testUtils.js'
import {muuidToString} from '../utils/helpers.js'
import {TickInput} from '../db/TickTypes.js'
import { jest } from '@jest/globals'
import { queryAPI, setUpServer } from '../utils/testUtils.js'
import { muuidToString } from '../utils/helpers.js'
import { TickInput } from '../db/TickTypes.js'
import TickDataSource from '../model/TickDataSource.js'
import UserDataSource from '../model/UserDataSource.js'
import {UpdateProfileGQLInput} from '../db/UserTypes.js'
import {InMemoryDB} from "../utils/inMemoryDB.js";
import express from "express";
import { UpdateProfileGQLInput } from '../db/UserTypes.js'
import { InMemoryDB } from '../utils/inMemoryDB.js'
import express from 'express'

jest.setTimeout(110000)

Expand All @@ -25,7 +25,7 @@ describe('ticks API', () => {
let tickOne: TickInput

beforeAll(async () => {
({server, inMemoryDB, app} = await setUpServer())
({ server, inMemoryDB, app } = await setUpServer())
user = muuid.v4()
userUuid = muuidToString(user)

Expand Down Expand Up @@ -95,7 +95,7 @@ describe('ticks API', () => {
await ticks.addTick(tickOne)
const response = await queryAPI({
query: userQuery,
variables: {userId: userUuid},
variables: { userId: userUuid },
userUuid,
app
})
Expand All @@ -115,7 +115,7 @@ describe('ticks API', () => {
await ticks.addTick(tickOne)
const response = await queryAPI({
query: userQuery,
variables: {username: 'cat.dog'},
variables: { username: 'cat.dog' },
userUuid,
app
})
Expand All @@ -129,7 +129,7 @@ describe('ticks API', () => {
await ticks.addTick(tickOne)
const response = await queryAPI({
query: userTickByClimbQuery,
variables: {userId: userUuid, climbId: tickOne.climbId},
variables: { userId: userUuid, climbId: tickOne.climbId },
userUuid,
app
})
Expand Down Expand Up @@ -176,7 +176,7 @@ describe('ticks API', () => {
it('creates and updates a tick', async () => {
const createResponse = await queryAPI({
query: createQuery,
variables: {input: tickOne},
variables: { input: tickOne },
userUuid,
roles: ['user_admin'],
app
Expand Down
25 changes: 9 additions & 16 deletions src/auth/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,23 @@
import muid from 'uuid-mongodb'
import {AuthUserType} from '../types.js'
import {verifyJWT} from './util.js'
import {logger} from '../logger.js'
import { AuthUserType } from '../types.js'
import { verifyJWT } from './util.js'
import { logger } from '../logger.js'

/**
* Create a middleware context for Apollo server
*/
export const createContext = async ({req}): Promise<any> => {
const user: AuthUserType = {
roles: [],
uuid: undefined,
isBuilder: false
}

export const createContext = async ({ req }): Promise<any> => {
try {
await validateTokenAndExtractUser(req)
return await validateTokenAndExtractUser(req)
} catch (e) {
logger.error(`Can't validate token and extract user ${e.toString() as string}`)
throw new Error('An unexpected error has occurred. Please notify us at [email protected].')
}

return {user}
}

export const authMiddleware = async (req, res, next): Promise<void> => {
try {
const {user, token} = await validateTokenAndExtractUser(req)
const { user, token } = await validateTokenAndExtractUser(req)
req.user = user
req.userId = user.uuid
req.token = token
Expand All @@ -36,8 +28,9 @@ export const authMiddleware = async (req, res, next): Promise<void> => {
}
}

async function validateTokenAndExtractUser(req: Request): Promise<{ user: AuthUserType, token: string }> {
const {headers} = req
async function validateTokenAndExtractUser (req: Request): Promise<{ user: AuthUserType, token: string }> {
const { headers } = req
// eslint-disable-next-line @typescript-eslint/dot-notation
const authHeader = String(headers?.['authorization'] ?? '')
if (!authHeader.startsWith('Bearer ')) {
throw new Error('Unauthorized. Please provide a valid JWT token in the Authorization header.')
Expand Down
Loading

0 comments on commit d1a297c

Please sign in to comment.