all: Aggiunte varie feature e riscritte svariate cose
This commit is contained in:
+49
-40
@@ -2,15 +2,7 @@ import crypto from 'crypto'
|
||||
|
||||
import { readFile, writeFile, access, constants } from 'fs/promises'
|
||||
|
||||
import {
|
||||
MetadataProps as MetaProps,
|
||||
Problem,
|
||||
ProblemId,
|
||||
Solution,
|
||||
SolutionId,
|
||||
User,
|
||||
UserId,
|
||||
} from '../../shared/model'
|
||||
import { MetadataProps as MetaProps, Problem, ProblemId, Solution, SolutionId, User, UserId } from '../../shared/model'
|
||||
|
||||
function once<T extends (...args: any) => any>(fn: T, message: string): T {
|
||||
let flag = false
|
||||
@@ -36,23 +28,23 @@ function createMutex(): Mutex {
|
||||
|
||||
const unlock = () => {
|
||||
if (waiters.length > 0) {
|
||||
console.log(`[Mutex] Passing lock to next in queue (of size ${waiters.length})`)
|
||||
console.log(`[Database/Mutex] Passing lock to next in queue (of size ${waiters.length})`)
|
||||
const resolve = waiters.shift()!!
|
||||
resolve(once(unlock, `lock already released`))
|
||||
} else {
|
||||
locked = false
|
||||
console.log(`[Mutex] Releasing the lock`)
|
||||
console.log(`[Database/Mutex] Releasing the lock`)
|
||||
}
|
||||
}
|
||||
|
||||
const lock = (): Promise<Lock> => {
|
||||
if (locked) {
|
||||
console.log(`[Mutex] Putting into queue`)
|
||||
console.log(`[Database/Mutex] Putting into queue`)
|
||||
return new Promise(resolve => {
|
||||
waiters.push(resolve)
|
||||
})
|
||||
} else {
|
||||
console.log(`[Mutex] Acquiring the lock`)
|
||||
console.log(`[Database/Mutex] Acquiring the lock`)
|
||||
locked = true
|
||||
return Promise.resolve(once(unlock, `lock already released`))
|
||||
}
|
||||
@@ -81,10 +73,7 @@ export function createDatabase(path: string, initialValue: Database) {
|
||||
}
|
||||
}
|
||||
|
||||
async function withDatabase<R>(
|
||||
{ path, initialValue, mu }: DatabaseConnection,
|
||||
fn: (db: Database) => R | Promise<R>
|
||||
): Promise<R> {
|
||||
async function withDatabase<R>({ path, initialValue, mu }: DatabaseConnection, fn: (db: Database) => R | Promise<R>): Promise<R> {
|
||||
const unlock: Lock = await mu.lock()
|
||||
|
||||
try {
|
||||
@@ -125,18 +114,19 @@ export const getUser: (db: DatabaseConnection, id: string) => Promise<User | nul
|
||||
// Problems
|
||||
//
|
||||
|
||||
export const createProblem = (
|
||||
db: DatabaseConnection,
|
||||
{ content, createdBy }: Omit<Problem, 'id' | 'createdAt'>
|
||||
): Promise<ProblemId> =>
|
||||
export const createProblem = (db: DatabaseConnection, { title, content, createdBy }: Omit<Problem, MetaProps>): Promise<ProblemId> =>
|
||||
withDatabase(db, state => {
|
||||
const nextId = (Object.keys(state.problems).length + 1).toString() as ProblemId
|
||||
const problemIds = Object.keys(state.problems)
|
||||
const nextId = (problemIds.length > 0 ? String(parseInt(problemIds.at(-1)!) + 1) : '1') as ProblemId
|
||||
|
||||
state.problems[nextId] = {
|
||||
id: nextId,
|
||||
createdAt: new Date().toJSON(),
|
||||
deleted: false,
|
||||
|
||||
title,
|
||||
content,
|
||||
createdBy,
|
||||
createdAt: new Date().toJSON(),
|
||||
}
|
||||
|
||||
return nextId
|
||||
@@ -144,12 +134,28 @@ export const createProblem = (
|
||||
|
||||
export const getProblem = (db: DatabaseConnection, id: string): Promise<Problem | null> =>
|
||||
withDatabase(db, state => {
|
||||
return state.problems[id] ?? null
|
||||
const problem = (state.problems[id] ?? null) as Problem | null
|
||||
return problem && !problem.deleted ? problem : null
|
||||
})
|
||||
|
||||
export const getProblems = (db: DatabaseConnection): Promise<Problem[]> =>
|
||||
withDatabase(db, state => {
|
||||
return Object.values(state.problems)
|
||||
return Object.values(state.problems).filter(p => !p.deleted)
|
||||
})
|
||||
|
||||
export const updateProblem = (db: DatabaseConnection, id: ProblemId, problem: Partial<Omit<Problem, MetaProps>>): Promise<Problem> =>
|
||||
withDatabase(db, state => {
|
||||
state.problems[id] = {
|
||||
...state.problems[id],
|
||||
...problem,
|
||||
}
|
||||
|
||||
return state.problems[id]
|
||||
})
|
||||
|
||||
export const deleteProblem = (db: DatabaseConnection, id: ProblemId): Promise<void> =>
|
||||
withDatabase(db, state => {
|
||||
state.problems[id].deleted = true
|
||||
})
|
||||
|
||||
//
|
||||
@@ -166,6 +172,7 @@ export const createSolution = (
|
||||
state.solutions[id] = {
|
||||
id,
|
||||
createdAt: new Date().toISOString(),
|
||||
deleted: false,
|
||||
|
||||
sentBy,
|
||||
forProblem,
|
||||
@@ -179,14 +186,23 @@ export const createSolution = (
|
||||
|
||||
export const getSolution = (db: DatabaseConnection, id: SolutionId): Promise<Solution | null> =>
|
||||
withDatabase(db, state => {
|
||||
return state.solutions[id] ?? null
|
||||
const solution = (state.solutions[id] ?? null) as Solution | null
|
||||
return solution && !solution.deleted ? solution : null
|
||||
})
|
||||
|
||||
export const updateSolution = (
|
||||
db: DatabaseConnection,
|
||||
id: SolutionId,
|
||||
solution: Partial<Omit<Solution, MetaProps>>
|
||||
): Promise<Solution> =>
|
||||
export const getSolutions = (db: DatabaseConnection) =>
|
||||
withDatabase(db, state => {
|
||||
return Object.values(state.solutions).filter(s => !s.deleted)
|
||||
})
|
||||
|
||||
export const getVisibleSolutions = (db: DatabaseConnection): Promise<Solution[]> =>
|
||||
withDatabase(db, state => {
|
||||
return Object.values(state.solutions)
|
||||
.filter(s => !s.deleted)
|
||||
.filter(s => s.visible)
|
||||
})
|
||||
|
||||
export const updateSolution = (db: DatabaseConnection, id: SolutionId, solution: Partial<Omit<Solution, MetaProps>>): Promise<Solution> =>
|
||||
withDatabase(db, state => {
|
||||
state.solutions[id] = {
|
||||
...state.solutions[id],
|
||||
@@ -196,14 +212,7 @@ export const updateSolution = (
|
||||
return state.solutions[id]
|
||||
})
|
||||
|
||||
export const getSolutions = (db: DatabaseConnection) =>
|
||||
export const deleteSolution = (db: DatabaseConnection, id: SolutionId): Promise<void> =>
|
||||
withDatabase(db, state => {
|
||||
let solutions = Object.values(state.solutions)
|
||||
|
||||
return solutions
|
||||
})
|
||||
|
||||
export const getVisibleSolutions = (db: DatabaseConnection) =>
|
||||
withDatabase(db, state => {
|
||||
return Object.values(state.solutions).filter(s => s.visible)
|
||||
state.solutions[id].deleted = true
|
||||
})
|
||||
|
||||
@@ -52,10 +52,6 @@ interface AuthenticatedRequest extends Request {
|
||||
user: User | null
|
||||
}
|
||||
|
||||
export const authenticatedMiddleware = (
|
||||
req: AuthenticatedRequest,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
) => {
|
||||
export const authenticatedMiddleware = (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
|
||||
req.user && next()
|
||||
}
|
||||
|
||||
+100
-16
@@ -3,9 +3,7 @@ import crypto from 'crypto'
|
||||
import bodyParser from 'body-parser'
|
||||
import cookieParser from 'cookie-parser'
|
||||
|
||||
import express, { Request, Response, Router } from 'express'
|
||||
|
||||
import { createStatusRouter } from './middlewares'
|
||||
import express, { Request, Router } from 'express'
|
||||
|
||||
import { StatusCodes } from 'http-status-codes'
|
||||
|
||||
@@ -13,13 +11,15 @@ import {
|
||||
createDatabase,
|
||||
createProblem,
|
||||
createSolution,
|
||||
deleteProblem,
|
||||
deleteSolution,
|
||||
getProblem,
|
||||
getProblems,
|
||||
getSolution,
|
||||
getSolutions,
|
||||
getUser,
|
||||
getUsers,
|
||||
getVisibleSolutions,
|
||||
updateProblem,
|
||||
updateSolution,
|
||||
} from './db/database'
|
||||
|
||||
@@ -28,10 +28,11 @@ import {
|
||||
isAdministrator,
|
||||
isStudent,
|
||||
Opaque,
|
||||
Problem,
|
||||
Problem as ProblemModel,
|
||||
ProblemId,
|
||||
Solution as SolutionModel,
|
||||
SolutionId,
|
||||
User as UserModel,
|
||||
UserId,
|
||||
} from '../shared/model'
|
||||
import { initialDatabaseValue } from './db/example-data'
|
||||
@@ -55,14 +56,12 @@ export async function createApiRouter() {
|
||||
|
||||
const db = createDatabase(process.env.DATABASE_PATH ?? './db.local.json', initialDatabaseValue)
|
||||
|
||||
async function getRequestUser(req: Request) {
|
||||
async function getRequestUser(req: Request): Promise<UserModel | null> {
|
||||
const userId = sessions.getUserForSession(req.cookies.sid)
|
||||
if (!userId) {
|
||||
return null
|
||||
}
|
||||
|
||||
console.log(userId)
|
||||
|
||||
return await getUser(db, userId)
|
||||
}
|
||||
|
||||
@@ -71,8 +70,9 @@ export async function createApiRouter() {
|
||||
r.use(bodyParser.json())
|
||||
r.use(cookieParser())
|
||||
|
||||
r.use('/api/status', createStatusRouter())
|
||||
// r.use('/api/ping', new PingRouter())
|
||||
r.get('/api/status', (req, res) => {
|
||||
res.json({ url: req.originalUrl, status: 'ok' })
|
||||
})
|
||||
|
||||
r.get('/api/current-user', async (req, res) => {
|
||||
res.json(await getRequestUser(req))
|
||||
@@ -108,7 +108,7 @@ export async function createApiRouter() {
|
||||
})
|
||||
|
||||
r.get('/api/problems', async (req, res) => {
|
||||
type ProblemWithSolutionsCount = Problem & { solutionsCount?: number }
|
||||
type ProblemWithSolutionsCount = ProblemModel & { solutionsCount?: number }
|
||||
|
||||
const problems: ProblemWithSolutionsCount[] = await getProblems(db)
|
||||
const solutions = await getSolutions(db)
|
||||
@@ -131,18 +131,76 @@ export async function createApiRouter() {
|
||||
res.json(await getProblem(db, req.params.id))
|
||||
})
|
||||
|
||||
r.post('/api/problem', async (req, res) => {
|
||||
r.patch('/api/problem/:id', async (req, res) => {
|
||||
const id = req.params.id as ProblemId
|
||||
|
||||
const user = await getRequestUser(req)
|
||||
// l'utente deve essere loggato
|
||||
if (!user) {
|
||||
res.sendStatus(StatusCodes.UNAUTHORIZED)
|
||||
return
|
||||
}
|
||||
|
||||
// l'utente deve essere un admin o un moderatore
|
||||
if (!isAdministrator(user.role)) {
|
||||
res.sendStatus(StatusCodes.UNAUTHORIZED)
|
||||
return
|
||||
}
|
||||
|
||||
// uno studente può modificare solo il campo "content"
|
||||
if (user.role === 'moderator' && !validateObjectKeys<keyof ProblemModel>(req.body, ['content'])) {
|
||||
res.status(StatusCodes.UNAUTHORIZED)
|
||||
res.send(`a moderator can only modify the field "content"`)
|
||||
return
|
||||
}
|
||||
|
||||
await updateProblem(db, id, req.body)
|
||||
|
||||
res.send({ status: 'ok' })
|
||||
})
|
||||
|
||||
r.delete('/api/problem/:id', async (req, res) => {
|
||||
const id = req.params.id as ProblemId
|
||||
|
||||
const user = await getRequestUser(req)
|
||||
if (!user) {
|
||||
res.sendStatus(StatusCodes.UNAUTHORIZED)
|
||||
return
|
||||
}
|
||||
|
||||
if (user.role !== 'admin') {
|
||||
res.status(StatusCodes.UNAUTHORIZED)
|
||||
res.send(`only an admin can delete this entity`)
|
||||
return
|
||||
}
|
||||
|
||||
await deleteProblem(db, id)
|
||||
|
||||
res.send({ status: 'ok' })
|
||||
})
|
||||
|
||||
r.post('/api/problem', async (req, res) => {
|
||||
const user = await getRequestUser(req)
|
||||
// l'utente deve essere loggato
|
||||
if (!user) {
|
||||
res.sendStatus(StatusCodes.UNAUTHORIZED)
|
||||
return
|
||||
}
|
||||
// Solo un amministratore può inviare nuovi problemi
|
||||
if (user.role !== 'admin' && user.role !== 'moderator') {
|
||||
res.sendStatus(StatusCodes.UNAUTHORIZED)
|
||||
return
|
||||
}
|
||||
// Il contenuto del problema deve essere non vuoto
|
||||
if (req.body.content.trim().length === 0) {
|
||||
res.sendStatus(StatusCodes.UNPROCESSABLE_ENTITY)
|
||||
return
|
||||
}
|
||||
|
||||
const problemNextId = (await getProblems(db)).map(p => parseInt(p.id)).reduce((acc, v) => Math.max(acc, v), 1) + 1
|
||||
|
||||
const id = await createProblem(db, {
|
||||
title: req.body.title ?? `Problema ${problemNextId}`,
|
||||
content: req.body.content,
|
||||
createdBy: user.id,
|
||||
})
|
||||
@@ -236,10 +294,7 @@ export async function createApiRouter() {
|
||||
return
|
||||
}
|
||||
// un moderatore può modificare solo i campi "content", "visible", "status"
|
||||
if (
|
||||
user.role === 'moderator' &&
|
||||
!validateObjectKeys<keyof SolutionModel>(req.body, ['content', 'status', 'visible'])
|
||||
) {
|
||||
if (user.role === 'moderator' && !validateObjectKeys<keyof SolutionModel>(req.body, ['content', 'status', 'visible'])) {
|
||||
res.status(StatusCodes.UNAUTHORIZED)
|
||||
res.send(`a moderator can only modify the fields "content", "visible", "status"`)
|
||||
return
|
||||
@@ -250,6 +305,35 @@ export async function createApiRouter() {
|
||||
res.json({ status: 'ok' })
|
||||
})
|
||||
|
||||
r.delete('/api/solution/:id', async (req, res) => {
|
||||
const id = req.params.id as SolutionId
|
||||
|
||||
const user = await getRequestUser(req)
|
||||
// l'utente deve essere loggato
|
||||
if (!user) {
|
||||
res.sendStatus(StatusCodes.UNAUTHORIZED)
|
||||
return
|
||||
}
|
||||
|
||||
const solution = await getSolution(db, id)
|
||||
|
||||
// la soluzione deve esistere
|
||||
if (solution === null) {
|
||||
res.sendStatus(StatusCodes.NOT_FOUND)
|
||||
return
|
||||
}
|
||||
|
||||
// solo un admin può eliminare le soluzioni degli utenti
|
||||
if (user.role !== 'admin' && solution.sentBy !== user.id) {
|
||||
res.sendStatus(StatusCodes.UNAUTHORIZED)
|
||||
return
|
||||
}
|
||||
|
||||
await deleteSolution(db, id)
|
||||
|
||||
res.send({ status: 'ok' })
|
||||
})
|
||||
|
||||
r.get('/api/user/:id', async (req, res) => {
|
||||
const user = await getRequestUser(req)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user