Almost MVP
This commit is contained in:
+25
-26
@@ -37,7 +37,7 @@ function createMutex(): Mutex {
|
||||
const unlock = () => {
|
||||
if (waiters.length > 0) {
|
||||
console.log(`[Mutex] Passing lock to next in queue (of size ${waiters.length})`)
|
||||
const resolve = waiters.shift()
|
||||
const resolve = waiters.shift()!!
|
||||
resolve(once(unlock, `lock already released`))
|
||||
} else {
|
||||
locked = false
|
||||
@@ -116,8 +116,8 @@ export const getUsers = (db: DatabaseConnection) =>
|
||||
return Object.values(state.users)
|
||||
})
|
||||
|
||||
export const getUser = (db: DatabaseConnection, id: string) =>
|
||||
withDatabase(db, (state: Database): User | null => {
|
||||
export const getUser: (db: DatabaseConnection, id: string) => Promise<User | null> = (db, id) =>
|
||||
withDatabase(db, state => {
|
||||
return state.users[id] ?? null
|
||||
})
|
||||
|
||||
@@ -142,9 +142,9 @@ export const createProblem = (
|
||||
return nextId
|
||||
})
|
||||
|
||||
export const getProblem = (db: DatabaseConnection, id: string): Promise<Problem> =>
|
||||
export const getProblem = (db: DatabaseConnection, id: string): Promise<Problem | null> =>
|
||||
withDatabase(db, state => {
|
||||
return state.problems[id]
|
||||
return state.problems[id] ?? null
|
||||
})
|
||||
|
||||
export const getProblems = (db: DatabaseConnection): Promise<Problem[]> =>
|
||||
@@ -158,53 +158,52 @@ export const getProblems = (db: DatabaseConnection): Promise<Problem[]> =>
|
||||
|
||||
export const createSolution = (
|
||||
db: DatabaseConnection,
|
||||
{ sentBy, forProblem, content }: Omit<Solution, MetaProps>
|
||||
{ sentBy, forProblem, content }: Omit<Solution, MetaProps | 'status' | 'visible'>
|
||||
): Promise<SolutionId> =>
|
||||
withDatabase(db, state => {
|
||||
const id = crypto.randomBytes(10).toString('hex')
|
||||
const id = crypto.randomBytes(10).toString('hex') as SolutionId
|
||||
|
||||
state.solutions[id] = {
|
||||
id,
|
||||
createdAt: new Date().toISOString(),
|
||||
|
||||
sentBy,
|
||||
forProblem,
|
||||
content,
|
||||
status: 'pending',
|
||||
visible: false,
|
||||
}
|
||||
|
||||
return id
|
||||
})
|
||||
|
||||
export const getSolution = (db: DatabaseConnection, id: SolutionId): Promise<Solution> =>
|
||||
export const getSolution = (db: DatabaseConnection, id: SolutionId): Promise<Solution | null> =>
|
||||
withDatabase(db, state => {
|
||||
return state.solutions[id]
|
||||
return state.solutions[id] ?? null
|
||||
})
|
||||
|
||||
export const updateSolution = (
|
||||
db: DatabaseConnection,
|
||||
id: SolutionId,
|
||||
solution: Omit<Solution, MetaProps>
|
||||
solution: Partial<Omit<Solution, MetaProps>>
|
||||
): Promise<Solution> =>
|
||||
withDatabase(db, state => {
|
||||
state.solutions[id] = { id, ...solution }
|
||||
state.solutions[id] = {
|
||||
...state.solutions[id],
|
||||
...solution,
|
||||
}
|
||||
|
||||
return state.solutions[id]
|
||||
})
|
||||
|
||||
type SolutionsQuery = Partial<{
|
||||
sentBy?: UserId
|
||||
forProblem?: ProblemId
|
||||
}>
|
||||
|
||||
export const getSolutions = (db: DatabaseConnection, { sentBy, forProblem }: SolutionsQuery = {}) =>
|
||||
export const getSolutions = (db: DatabaseConnection) =>
|
||||
withDatabase(db, state => {
|
||||
let solutions = Object.values(state.solutions)
|
||||
|
||||
console.log(solutions.length, sentBy, forProblem)
|
||||
|
||||
if (sentBy) {
|
||||
solutions = solutions.filter(s => s.sentBy === sentBy)
|
||||
}
|
||||
if (forProblem) {
|
||||
solutions = solutions.filter(s => s.forProblem === forProblem)
|
||||
}
|
||||
|
||||
return solutions
|
||||
})
|
||||
|
||||
export const getVisibleSolutions = (db: DatabaseConnection) =>
|
||||
withDatabase(db, state => {
|
||||
return Object.values(state.solutions).filter(s => s.visible)
|
||||
})
|
||||
|
||||
+95
-59
@@ -7,6 +7,8 @@ import express, { Request, Response, Router } from 'express'
|
||||
|
||||
import { createStatusRouter } from './middlewares'
|
||||
|
||||
import { StatusCodes } from 'http-status-codes'
|
||||
|
||||
import {
|
||||
createDatabase,
|
||||
createProblem,
|
||||
@@ -17,24 +19,37 @@ import {
|
||||
getSolutions,
|
||||
getUser,
|
||||
getUsers,
|
||||
getVisibleSolutions,
|
||||
updateSolution,
|
||||
} from './db/database'
|
||||
|
||||
import { isAdministrator, isStudent, Problem, ProblemId, UserId } from '../shared/model'
|
||||
import {
|
||||
Id,
|
||||
isAdministrator,
|
||||
isStudent,
|
||||
Opaque,
|
||||
Problem,
|
||||
ProblemId,
|
||||
Solution as SolutionModel,
|
||||
SolutionId,
|
||||
UserId,
|
||||
} from '../shared/model'
|
||||
import { initialDatabaseValue } from './db/example-data'
|
||||
|
||||
export async function createApiRouter() {
|
||||
type SessionId = string
|
||||
import { validateObjectKeys } from '../shared/utils'
|
||||
|
||||
export async function createApiRouter() {
|
||||
type SessionId = Opaque<string, string, 'session'>
|
||||
|
||||
const sessionStore: Record<SessionId, UserId> = {}
|
||||
const sessions = {
|
||||
store: {},
|
||||
createSession(userId: UserId) {
|
||||
const sid = crypto.randomBytes(10).toString('hex')
|
||||
this.store[sid] = userId
|
||||
const sid = crypto.randomBytes(10).toString('hex') as SessionId
|
||||
sessionStore[sid] = userId
|
||||
return sid
|
||||
},
|
||||
getUserForSession(sid: SessionId) {
|
||||
return this.store[sid] ?? null
|
||||
return sessionStore[sid] ?? null
|
||||
},
|
||||
}
|
||||
|
||||
@@ -68,7 +83,7 @@ export async function createApiRouter() {
|
||||
|
||||
const user = await getUser(db, id)
|
||||
if (!user) {
|
||||
res.sendStatus(403)
|
||||
res.sendStatus(StatusCodes.FORBIDDEN)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -83,8 +98,8 @@ export async function createApiRouter() {
|
||||
|
||||
r.get('/api/users', async (req, res) => {
|
||||
const requestUser = await getRequestUser(req)
|
||||
if (requestUser.role !== 'admin' && requestUser.role !== 'moderator') {
|
||||
res.sendStatus(401)
|
||||
if (!requestUser || !isAdministrator(requestUser.role)) {
|
||||
res.sendStatus(StatusCodes.UNAUTHORIZED)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -119,11 +134,11 @@ export async function createApiRouter() {
|
||||
r.post('/api/problem', async (req, res) => {
|
||||
const user = await getRequestUser(req)
|
||||
if (!user) {
|
||||
res.sendStatus(401)
|
||||
res.sendStatus(StatusCodes.UNAUTHORIZED)
|
||||
return
|
||||
}
|
||||
if (user.role !== 'admin' && user.role !== 'moderator') {
|
||||
res.sendStatus(401)
|
||||
res.sendStatus(StatusCodes.UNAUTHORIZED)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -135,86 +150,107 @@ export async function createApiRouter() {
|
||||
res.json(id)
|
||||
})
|
||||
|
||||
r.get('/api/solutions', async (req, res) => {
|
||||
let queryUser = (req.query.user ?? null) as UserId | null
|
||||
let queryProblem = (req.query.problem ?? null) as ProblemId | null
|
||||
|
||||
const requestUser = await getRequestUser(req)
|
||||
|
||||
let solutions = await getSolutions(db)
|
||||
// se l'utente non è loggato o se non è un amministratore allora mostra solo le soluzioni "visibili"
|
||||
if (!requestUser || !isAdministrator(requestUser.role)) {
|
||||
solutions = solutions.filter(
|
||||
s => s.visible || (requestUser && s.sentBy === requestUser.id)
|
||||
)
|
||||
}
|
||||
// filtra rispetto agli utenti
|
||||
if (queryUser !== null) {
|
||||
solutions = solutions.filter(s => s.sentBy === queryUser)
|
||||
}
|
||||
// filtra rispetto ai problemi
|
||||
if (queryProblem !== null) {
|
||||
solutions = solutions.filter(s => s.forProblem === queryProblem)
|
||||
}
|
||||
|
||||
res.json(solutions)
|
||||
})
|
||||
|
||||
r.get('/api/solution/:id', async (req, res) => {
|
||||
const user = await getRequestUser(req)
|
||||
|
||||
// l'utente deve essere loggato
|
||||
if (!user) {
|
||||
res.sendStatus(401)
|
||||
const solution = await getSolution(db, req.params.id as SolutionId)
|
||||
// la soluzione deve esistere
|
||||
if (solution === null) {
|
||||
res.sendStatus(StatusCodes.NOT_FOUND)
|
||||
return
|
||||
}
|
||||
|
||||
const solution = await getSolution(db, req.params.id)
|
||||
|
||||
// uno studente che prova a ottenere la soluzione di un altro utente
|
||||
if (!isAdministrator(user.role) && solution.sentBy !== user.id) {
|
||||
res.sendStatus(401)
|
||||
// uno studente può vedere solo soluzioni visibili o proprie soluzione
|
||||
if (!solution.visible && user && isStudent(user.role) && solution.sentBy !== user.id) {
|
||||
res.sendStatus(StatusCodes.UNAUTHORIZED)
|
||||
return
|
||||
}
|
||||
|
||||
res.json(solution)
|
||||
})
|
||||
|
||||
r.get('/api/solutions', async (req, res) => {
|
||||
let queryUserId = req.query.user as string
|
||||
let queryProblemId = req.query.problem as string
|
||||
|
||||
const requestUser = await getRequestUser(req)
|
||||
if (!requestUser) {
|
||||
res.sendStatus(401)
|
||||
return
|
||||
}
|
||||
|
||||
// if current user is not an administrator then force the user query to current user
|
||||
if (!isAdministrator(requestUser.role)) {
|
||||
queryUserId = requestUser.id
|
||||
}
|
||||
|
||||
res.json(
|
||||
await getSolutions(db, {
|
||||
sentBy: queryUserId as UserId,
|
||||
forProblem: queryProblemId as ProblemId,
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
r.post('/api/solution', async (req, res) => {
|
||||
const user = await getRequestUser(req)
|
||||
if (!user) {
|
||||
res.sendStatus(401)
|
||||
res.sendStatus(StatusCodes.UNAUTHORIZED)
|
||||
return
|
||||
}
|
||||
|
||||
await createSolution(db, {
|
||||
sentBy: user.id,
|
||||
forProblem: req.body.problemId,
|
||||
forProblem: req.body.forProblem,
|
||||
content: req.body.content,
|
||||
status: 'pending',
|
||||
})
|
||||
|
||||
res.send({ status: 'ok' })
|
||||
})
|
||||
|
||||
r.post('/api/solution/:id', async (req, res) => {
|
||||
const user = await getRequestUser(req)
|
||||
r.patch('/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(401)
|
||||
res.sendStatus(StatusCodes.UNAUTHORIZED)
|
||||
return
|
||||
}
|
||||
|
||||
const solutionId = req.params.id
|
||||
const solution = await getSolution(db, solutionId)
|
||||
|
||||
const solution = await getSolution(db, id)
|
||||
// la soluzione deve esistere
|
||||
if (solution === null) {
|
||||
res.sendStatus(404)
|
||||
return
|
||||
}
|
||||
// uno studente non può modificare una soluzione di un altro utente
|
||||
if (isStudent(user.role) && solution.sentBy !== user.id) {
|
||||
res.sendStatus(401)
|
||||
if (user.role === 'student' && solution.sentBy !== user.id) {
|
||||
res.status(StatusCodes.UNAUTHORIZED)
|
||||
res.send(`a student can only modify its own solution`)
|
||||
return
|
||||
}
|
||||
// uno studente può modificare solo il campo "content"
|
||||
if (
|
||||
user.role === 'student' &&
|
||||
!validateObjectKeys<keyof SolutionModel>(req.body, ['content'])
|
||||
) {
|
||||
res.status(StatusCodes.UNAUTHORIZED)
|
||||
res.send(`a student can only modify the field "content"`)
|
||||
return
|
||||
}
|
||||
// un moderatore può modificare solo i campi "content", "visible", "status"
|
||||
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
|
||||
}
|
||||
|
||||
// modifico la soluzione con il json mandato dal client nel body della richiesta
|
||||
await updateSolution(db, solutionId, req.body)
|
||||
await updateSolution(db, id, req.body)
|
||||
|
||||
res.json({ status: 'ok' })
|
||||
})
|
||||
@@ -224,13 +260,13 @@ export async function createApiRouter() {
|
||||
|
||||
// intanto l'utente deve essere loggato
|
||||
if (!user) {
|
||||
res.sendStatus(401)
|
||||
res.sendStatus(StatusCodes.UNAUTHORIZED)
|
||||
return
|
||||
}
|
||||
|
||||
// solo gli amministratori possono usare questa route
|
||||
if (!isAdministrator(user.role)) {
|
||||
res.sendStatus(401)
|
||||
res.sendStatus(StatusCodes.UNAUTHORIZED)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user