-
-
Notifications
You must be signed in to change notification settings - Fork 33
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix(auth): correctly return user ctx
- Loading branch information
Showing
23 changed files
with
450 additions
and
456 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
|
||
|
@@ -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() | ||
|
@@ -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 | ||
}) | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
|
@@ -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() | ||
|
@@ -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 | ||
|
@@ -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 | ||
|
@@ -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 | ||
}) | ||
|
@@ -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 | ||
}) | ||
|
@@ -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 | ||
}) | ||
|
@@ -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 | ||
}) | ||
|
@@ -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 | ||
}) | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
|
@@ -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.') | ||
|
Oops, something went wrong.