Skip to content
Open

done #80

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
24 changes: 24 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
name: CI

on:
push:
pull_request:

jobs:
test:
runs-on: ubuntu-latest

steps:
- name: Check out the code
uses: actions/checkout@v4

- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: '20'

- name: Install dependencies
run: npm install

- name: Run the test suite
run: npm test
6 changes: 6 additions & 0 deletions babel.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// Lets jest load the project's ESM source (server + client) through babel-jest.
module.exports = {
presets: [
['@babel/preset-env', { targets: { node: 'current' } }]
]
};
32 changes: 29 additions & 3 deletions client/src/api.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,35 @@
import axios from 'axios'

// `withCredentials: true` makes the browser send (and store) the auth cookie on
// cross-origin requests to the API. The JWT is no longer kept in localStorage,
// so there is no token to attach by hand anymore.
export const api = axios.create({
baseURL: 'http://localhost:4000/api',
withCredentials: true
})

let csrfToken = null
export function resetCsrfToken() { csrfToken = null }

const PRE_AUTH = ['/auth/login', '/auth/register']
const SAFE = ['get', 'head', 'options']

api.interceptors.request.use(async (config) => {
const method = (config.method || 'get').toLowerCase()
if (SAFE.includes(method) || PRE_AUTH.includes(config.url)) return config

if (!csrfToken) {
const { data } = await api.get('/csrf-token')
csrfToken = data.csrfToken
}
config.headers['x-csrf-token'] = csrfToken
return config
})

// If the token went stale (e.g. session changed), refetch once and retry
api.interceptors.response.use(undefined, async (error) => {
const { config, response } = error
if (response?.status === 403 && config && !config._csrfRetried) {
config._csrfRetried = true
csrfToken = null
return api(config)
}
return Promise.reject(error)
})
37 changes: 19 additions & 18 deletions client/src/context/AuthContext.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { createContext, useCallback, useContext, useEffect, useState } from 'react'
import { api } from '../api'

import { api, resetCsrfToken } from '../api'
const AuthContext = createContext(null)

export function AuthProvider({ children }) {
Expand All @@ -17,22 +16,24 @@ export function AuthProvider({ children }) {
.finally(() => setLoading(false))
}, [])

const login = useCallback(async (email, password) => {
const res = await api.post('/auth/login', { email, password })
setUser(res.data.user)
}, [])

const register = useCallback(async (name, email, password) => {
const res = await api.post('/auth/register', { name, email, password })
setUser(res.data.user)
}, [])

const logout = useCallback(async () => {
try { await api.post('/auth/logout') } catch { /* ignore */ }
setUser(null)
window.location.href = '/login'
}, [])

const login = useCallback(async (email, password) => {
const res = await api.post('/auth/login', { email, password })
resetCsrfToken()
setUser(res.data.user)
}, [])

const register = useCallback(async (name, email, password) => {
const res = await api.post('/auth/register', { name, email, password })
resetCsrfToken()
setUser(res.data.user)
}, [])

const logout = useCallback(async () => {
try { await api.post('/auth/logout') } catch { /* ignore */ }
resetCsrfToken()
setUser(null)
window.location.href = '/login'
}, [])

return (
<AuthContext.Provider value={{ user, loading, login, register, logout }}>
Expand Down
24 changes: 24 additions & 0 deletions jest.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// One jest run with two environments:
// - "server" tests run in node (they boot the Express app + in-memory Mongo)
// - "client" tests run in jsdom (they exercise the browser-side api client)
// `npm test` runs both.
module.exports = {
projects: [
{
displayName: 'server',
testEnvironment: 'node',
testMatch: ['<rootDir>/tests/server/**/*.test.js'],
transform: {
'^.+\\.js$': 'babel-jest'
}
},
{
displayName: 'client',
testEnvironment: 'jsdom',
testMatch: ['<rootDir>/tests/client/**/*.test.js'],
transform: {
'^.+\\.js$': 'babel-jest'
}
}
]
};
Loading