Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Backend/logic/UserLogicBackend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,8 @@ export async function RequireUser(token: string | null, userId: number | null):
const { rows } = await pool.query('SELECT user_id FROM users WHERE token = $1', [token])

if (rows.length === 0 || Number(rows[0].user_id) !== Number(userId)) {
throw new GraphQLError('Not allowed.', {
extensions: { code: 'FORBIDDEN' }
throw new GraphQLError('Your session is invalid or has expired.', {
extensions: { code: 'UNAUTHENTICATED' }
})
}
}
Expand Down
8 changes: 4 additions & 4 deletions Backend/tests/TokenBackend.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,24 +218,24 @@ describe('RequireUser', () => {

const error = await RejectionOf(RequireUser('unknown-token', 1))

expect(error.message).toBe('Not allowed.')
expect(error.extensions.code).toBe('FORBIDDEN')
expect(error.message).toBe('Your session is invalid or has expired.')
expect(error.extensions.code).toBe('UNAUTHENTICATED')
})

it("rejects a valid token that belongs to a different user's id", async () => {
Query.mockResolvedValue({ rows: [{ user_id: 2 }] })

const error = await RejectionOf(RequireUser(TOKEN, 1))

expect(error.extensions.code).toBe('FORBIDDEN')
expect(error.extensions.code).toBe('UNAUTHENTICATED')
})

it('rejects a valid token when no user id is given', async () => {
Query.mockResolvedValue({ rows: [{ user_id: 2 }] })

const error = await RejectionOf(RequireUser(TOKEN, null))

expect(error.extensions.code).toBe('FORBIDDEN')
expect(error.extensions.code).toBe('UNAUTHENTICATED')
})

it('lets the request through when the token belongs to that user', async () => {
Expand Down
15 changes: 14 additions & 1 deletion Frontend/src/FrontendLogic/LogicConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,14 @@ export async function Gql<T>(query: string, variables: Record<string, unknown>):
}
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
const json = await res.json()
if (json.errors) throw new Error(json.errors[0].message)
if (json.errors?.length) {
// NEW: a bad token logs the user out
if (json.errors.some((e: { extensions?: { code?: string } }) =>
e.extensions?.code === 'UNAUTHENTICATED')) {
onUnauthenticated?.()
}
throw new Error(json.errors[0].message)
}
return json.data
}

Expand All @@ -33,3 +40,9 @@ export function GetStoredToken(): string | null {
return null
}
}

let onUnauthenticated: (() => void) | null = null

export const SetUnauthenticatedHandler = (handler: (() => void) | null) => {
onUnauthenticated = handler
}
15 changes: 12 additions & 3 deletions Frontend/src/context/AuthContext.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import * as React from 'react'
import type { User } from '../../../Backend/logic/UserLogicBackend'
import { SaveUser, ClearUser, GetSavedUser } from '../FrontendLogic/UserLogicFrontend'
import { useCallback, useEffect } from 'react'
import { SetUnauthenticatedHandler } from '../FrontendLogic/LogicConnection'

interface AuthContextValue {
user: User | null
Expand All @@ -17,10 +19,17 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
setUser(user)
}

const Logout = () => {
ClearUser()
const Logout = useCallback(() => {
setUser(null)
}
ClearUser()
}, [])

useEffect(() => {
SetUnauthenticatedHandler(() => {
Logout()
})
return () => SetUnauthenticatedHandler(null)
}, [Logout])

return (
<AuthContext.Provider value={{ user, login: Login, logout: Logout }}>
Expand Down