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
21 changes: 21 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
name: Instructor Portal security tests
on: [push, pull_request]

jobs:
test:
runs-on: ubuntu-22.04
env:
MONGOMS_VERSION: 7.0.14
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm # uses the root package-lock.json
- name: Cache mongod binary
uses: actions/cache@v4
with:
path: ~/.cache/mongodb-binaries
key: mongodb-memory-server-7.0.14-${{ runner.os }}
- run: npm ci # installs the server+client workspaces
- run: npm test --workspace server
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# Node.js dependencies
node_modules/
.npm-cache/
.cache/

# Build artifacts
build/
Expand All @@ -26,4 +28,4 @@ Thumbs.db

# Server-side specific ignores (if server is in a subfolder)
server/node_modules/
server/build/
server/build/
8 changes: 5 additions & 3 deletions .vscode/setupCI.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ on: [push, pull_request]

jobs:
test:
runs-on: ubuntu-22.04 # 22.04 has libssl1.1 for mongod 6.0.x
runs-on: ubuntu-22.04
env:
MONGOMS_VERSION: 7.0.14
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
Expand All @@ -20,11 +22,11 @@ jobs:
uses: actions/cache@v4
with:
path: ~/.cache/mongodb-binaries
key: mongodb-memory-server-6.0.14-\${{ runner.os }}
key: mongodb-memory-server-7.0.14-\${{ runner.os }}
- run: npm ci # installs the server+client workspaces
- run: npm test --workspace server`;

if (!fs.existsSync(workflowDir)) {
fs.mkdirSync(workflowDir, { recursive: true });
}
fs.writeFileSync(filePath, ciContent, { encoding: 'utf8' });
fs.writeFileSync(filePath, ciContent, { encoding: 'utf8' });
4 changes: 2 additions & 2 deletions .vscode/setupHelper.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ export const SEED = [
export const SECRET_FIELDS = ['password', 'apiKey', 'privateEmail', 'privatePhone'];

export async function startDb() {
mongod = await MongoMemoryServer.create();
mongod = await MongoMemoryServer.create({ instance: { storageEngine: 'wiredTiger' } });
await mongoose.connect(mongod.getUri(), { autoIndex: true });
}

Expand All @@ -94,4 +94,4 @@ export async function seed() {
}
`;

fs.writeFileSync(envHelperFilePath, envHelperContent, { encoding: 'utf8' });
fs.writeFileSync(envHelperFilePath, envHelperContent, { encoding: 'utf8' });
8 changes: 2 additions & 6 deletions client/src/pages/InstructorDashboard.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,9 @@ import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { api } from '../api'

// Instructor Portal dashboard. Reads the naive session from localStorage.
// Instructor Portal dashboard. Reads the public profile from localStorage.
// Shows the signed-in profile, the public directory, and a name search.
// The search box sends a plain string; students intercept the request
// (Postman / proxy) to inject MongoDB operators — see Flow.md.
// The search box sends a plain name string to the public search endpoint.
export default function InstructorDashboard() {
const nav = useNavigate()
const [instructor, setInstructor] = useState(null)
Expand Down Expand Up @@ -58,9 +57,6 @@ export default function InstructorDashboard() {
<div className="text-sm text-zinc-600">
@{instructor.username} • {instructor.department} • role: <b>{instructor.role}</b>
</div>
{instructor.apiKey && (
<div className="text-sm mt-1">API key: <code>{instructor.apiKey}</code></div>
)}
</div>
<button onClick={logout} className="btn">Log out</button>
</div>
Expand Down
3 changes: 1 addition & 2 deletions client/src/pages/InstructorLogin.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ import { api } from '../api'
// Instructor Portal login. This portal is separate from the student JWT auth
// (AuthContext) — it has its own simple session stored in localStorage.
//
// The form sends plain strings (honest use). The backing endpoint is
// intentionally vulnerable to NoSQL injection; see Flow.md for the lab.
// The backing endpoint validates strings and verifies a bcrypt password hash.
export default function InstructorLogin() {
const nav = useNavigate()
const [username, setUsername] = useState('')
Expand Down
73 changes: 59 additions & 14 deletions client/src/pages/ReviewForm.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,44 +2,89 @@ import { useEffect, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { api } from '../api'

// TODO: build the Write Review page — see README.md "Your task".
// This page is already routed at /reviews/new (write) and /reviews/:id (edit),
// and both routes are wrapped in <ProtectedRoute>.

const defaults = { courseCode: '', rating: 5, comment: '' }

export default function ReviewForm() {
const nav = useNavigate()
const { id } = useParams()
const [form, setForm] = useState(defaults)
const [error, setError] = useState('')
const [loading, setLoading] = useState(Boolean(id))
const [saving, setSaving] = useState(false)
const [loadedId, setLoadedId] = useState(null)

// TODO (edit mode): when there is an `id`, load the review and fill the form.
useEffect(() => {
let active = true
setError('')
setLoadedId(null)
setForm(defaults)
setLoading(Boolean(id))
if (!id) return
// TODO

api.get('/reviews/' + id)
.then(({ data }) => {
if (!active) return
const { courseCode, rating, comment } = data.review
setForm({ courseCode, rating, comment: comment || '' })
setLoadedId(id)
})
.catch(err => {
if (active) setError(err?.response?.data?.message || 'Could not load review')
})
.finally(() => { if (active) setLoading(false) })

return () => { active = false }
}, [id])

// TODO: update `form` when an input changes (rating should be a number).
function onChange(e) {
// TODO
const { name, value } = e.target
setForm(prev => ({ ...prev, [name]: name === 'rating' ? Number(value) : value }))
}

// TODO: POST a new review, or PATCH the existing one when editing,
// then go back to /reviews. Show the server's error message on failure.
const unavailable = loading || saving || Boolean(id && loadedId !== id)

async function onSubmit(e) {
e.preventDefault()
if (unavailable) return
setError('')
// TODO
setSaving(true)
try {
const payload = { ...form, courseCode: form.courseCode.trim().toUpperCase() }
if (id) await api.patch('/reviews/' + id, payload)
else await api.post('/reviews', payload)
nav('/reviews')
} catch (err) {
setError(err?.response?.data?.message || 'Could not save review')
} finally {
setSaving(false)
}
}

return (
<div className="max-w-lg mx-auto card">
<h1 className="text-xl font-semibold mb-4">{id ? 'Edit' : 'Write'} Review</h1>
{loading && <p role="status">Loading review...</p>}
<form onSubmit={onSubmit} className="space-y-3">
{/* TODO: course code input, rating select (1-5) and comment textarea */}
{error && <div className="text-red-600 text-sm">{error}</div>}
<button className="btn" type="submit">Save</button>
<fieldset disabled={unavailable} className="space-y-3">
<label className="block" htmlFor="courseCode">
Course code
<input id="courseCode" name="courseCode" className="input" placeholder="CS101"
value={form.courseCode} onChange={onChange} minLength={2} required />
</label>
<label className="block" htmlFor="rating">
Rating
<select id="rating" name="rating" className="input" value={form.rating} onChange={onChange}>
{[1, 2, 3, 4, 5].map(rating => <option key={rating} value={rating}>{rating} / 5</option>)}
</select>
</label>
<label className="block" htmlFor="comment">
Comment
<textarea id="comment" name="comment" className="input" rows={4}
value={form.comment} onChange={onChange} />
</label>
<button className="btn" type="submit">{saving ? 'Saving...' : 'Save'}</button>
</fieldset>
{error && <div role="alert" className="text-red-600 text-sm">{error}</div>}
</form>
</div>
)
Expand Down
20 changes: 20 additions & 0 deletions package-lock.json

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

4 changes: 3 additions & 1 deletion server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
"dev": "nodemon src/index.js",
"start": "node src/index.js",
"seed:instructors": "node src/seed/instructors.js",
"test": "NODE_OPTIONS=--experimental-vm-modules jest --runInBand"
"test": "node --experimental-vm-modules ../node_modules/jest/bin/jest.js --runInBand",
"migrate:instructor-passwords": "node src/scripts/migrateInstructorPasswords.js"
},
"jest": {
"testEnvironment": "node",
Expand All @@ -19,6 +20,7 @@
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"express-mongo-sanitize": "^2.2.0",
"joi": "^17.12.3",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.6.0",
Expand Down
4 changes: 4 additions & 0 deletions server/src/app.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import express from 'express';
import morgan from 'morgan';
import cors from 'cors';
import mongoSanitize from 'express-mongo-sanitize';
import authRoutes from './routes/auth.js';
import reviewRoutes from './routes/reviews.js';
import userRoutes from './routes/users.js';
Expand All @@ -11,6 +12,9 @@ const app = express();
app.use(morgan('dev'));
app.use(cors({ origin: 'http://localhost:5175', credentials: false }));
app.use(express.json());
app.use(mongoSanitize({
onSanitize: ({ req }) => { req.mongoSanitized = true; }
}));

app.get('/api/health', (req, res) => res.json({ ok: true }));

Expand Down
Loading