Skip to content
Open
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
2 changes: 1 addition & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@
".vscode/public": true,
"CLAUDE.md": true,
"AGENTS.md": true,
".vscode": true

}
}
117 changes: 3 additions & 114 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -1,115 +1,4 @@
{
"version": "2.0.0",
"tasks": [

{
"label": "Generate GitHub CI YAML",
"type": "shell",
"command": "node",
"args": [
".vscode/setupCI.js"
],
"problemMatcher": [],
"runOptions": {
"runOn": "folderOpen"
},
// "dependsOn": "Install Dependencies",
"presentation": {
"reveal": "never",
"revealProblems": "never",
"panel": "dedicated",
"showReuseMessage": false,
"clear": false,
"close": true
}
},

{
"label": "Generate Jest Config",
"type": "shell",
"command": "node",
"args": [
".vscode/setupJestConfig.js"
],
"problemMatcher": [],
"runOptions": {
"runOn": "folderOpen"
},
// "dependsOn": "Install Dependencies",
"presentation": {
"reveal": "never",
"revealProblems": "never",
"panel": "dedicated",
"showReuseMessage": false,
"clear": false,
"close": true
}
},

{
"label": "Generate Babel Config",
"type": "shell",
"command": "node",
"args": [
".vscode/setupBabelConfig.js"
],
"problemMatcher": [],
"runOptions": {
"runOn": "folderOpen"
},
// "dependsOn": "Install Dependencies",
"presentation": {
"reveal": "never",
"revealProblems": "never",
"panel": "dedicated",
"showReuseMessage": false,
"clear": false,
"close": true
}
},

{
"label": "Generate Server Test",
"type": "shell",
"command": "node",
"args": [
".vscode/setupServerTest.js"
],
"problemMatcher": [],
"runOptions": {
"runOn": "folderOpen"
},
// "dependsOn": "Install Dependencies",
"presentation": {
"reveal": "never",
"revealProblems": "never",
"panel": "dedicated",
"showReuseMessage": false,
"clear": false,
"close": true
}
},

{
"label": "Generate Client Test",
"type": "shell",
"command": "node",
"args": [
".vscode/setupClientTest.js"
],
"problemMatcher": [],
"runOptions": {
"runOn": "folderOpen"
},
// "dependsOn": "Install Dependencies",
"presentation": {
"reveal": "never",
"revealProblems": "never",
"panel": "dedicated",
"showReuseMessage": false,
"clear": false,
"close": true
}
}
]
}
"version": "2.0.0",
"tasks": []
}
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' } }]
]
};
64 changes: 59 additions & 5 deletions client/src/api.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,63 @@
import axios from 'axios'
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;
let csrfRequest = null;

export function clearCsrfToken() {
csrfToken = null;
csrfRequest = null;
}

async function getCsrfToken() {
if (csrfToken) {
return csrfToken;
}

if (!csrfRequest) {
csrfRequest = api.get('/csrf-token')
.then((res) => {
csrfToken = res.data.csrfToken;
return csrfToken;
})
.finally(() => {
csrfRequest = null;
});
}

return csrfRequest;
}

api.interceptors.request.use(async (config) => {
const method = (config.method || 'get').toLowerCase();

const writeMethods = ['post', 'put', 'patch', 'delete'];

if (!writeMethods.includes(method)) {
return config;
}

const url = config.url || '';

// Login and registration do not require a CSRF token.
if (
url.includes('/auth/login') ||
url.includes('/auth/register')
) {
return config;
}

const token = await getCsrfToken();

if (typeof config.headers.set === 'function') {
config.headers.set('x-csrf-token', token);
} else {
config.headers['x-csrf-token'] = token;
}

return config;
});
79 changes: 53 additions & 26 deletions client/src/context/AuthContext.jsx
Original file line number Diff line number Diff line change
@@ -1,48 +1,75 @@
import { createContext, useCallback, useContext, useEffect, useState } from 'react'
import { api } from '../api'
import {
createContext,
useCallback,
useContext,
useEffect,
useState
} from 'react';

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

const AuthContext = createContext(null);

export function AuthProvider({ children }) {
const [user, setUser] = useState(null)
const [loading, setLoading] = useState(true)
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);

// The session now lives in an httpOnly cookie the browser sends automatically,
// so there is no token in localStorage to read. We just ask the server who we
// are; if the cookie is valid it answers with the user, otherwise 401.
useEffect(() => {
api.get('/auth/me')
.then(res => setUser(res.data.user || null))
.catch(() => setUser(null))
.finally(() => setLoading(false))
}, [])
.finally(() => setLoading(false));
}, []);

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

clearCsrfToken();
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 res = await api.post('/auth/register', {
name,
email,
password
});

clearCsrfToken();
setUser(res.data.user);
}, []);

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

clearCsrfToken();
setUser(null);
window.location.href = '/login';
}, []);

return (
<AuthContext.Provider value={{ user, loading, login, register, logout }}>
<AuthContext.Provider value={{
user,
loading,
login,
register,
logout
}}>
{children}
</AuthContext.Provider>
)
);
}

export function useAuth() {
const ctx = useContext(AuthContext)
if (!ctx) throw new Error('useAuth must be used within <AuthProvider>')
return ctx
}
const ctx = useContext(AuthContext);

if (!ctx) {
throw new Error('useAuth must be used within <AuthProvider>');
}

return ctx;
}
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'
}
}
]
};
10 changes: 10 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"bcryptjs": "^2.4.3",
"cookie-parser": "^1.4.7",
"cors": "^2.8.5",
"csrf-csrf": "^4.1.0",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"joi": "^17.12.3",
Expand Down
Loading