Refactoring to Typescript...
This commit is contained in:
@@ -2,21 +2,39 @@ import crypto from 'crypto'
|
||||
|
||||
import { readFile, writeFile, access, constants } from 'fs/promises'
|
||||
|
||||
function once(fn, message) {
|
||||
import {
|
||||
CommonProps 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
|
||||
|
||||
return (...args) => {
|
||||
return ((...args: any) => {
|
||||
if (flag) {
|
||||
throw new Error(message ?? `cannot run more than once`)
|
||||
}
|
||||
flag = true
|
||||
return fn(...args)
|
||||
}
|
||||
}) as T
|
||||
}
|
||||
|
||||
function createMutex() {
|
||||
interface Lock {
|
||||
(): void
|
||||
}
|
||||
|
||||
interface Mutex {
|
||||
lock(): Promise<Lock>
|
||||
}
|
||||
|
||||
function createMutex(): Mutex {
|
||||
let locked = false
|
||||
const waiters = []
|
||||
const waiters: ((fn: () => void) => void)[] = []
|
||||
|
||||
const unlock = () => {
|
||||
if (waiters.length > 0) {
|
||||
@@ -29,7 +47,7 @@ function createMutex() {
|
||||
}
|
||||
}
|
||||
|
||||
const lock = () => {
|
||||
const lock = (): Promise<Lock> => {
|
||||
if (locked) {
|
||||
console.log(`[Mutex] Putting into queue`)
|
||||
return new Promise(resolve => {
|
||||
@@ -38,20 +56,26 @@ function createMutex() {
|
||||
} else {
|
||||
console.log(`[Mutex] Acquiring the lock`)
|
||||
locked = true
|
||||
return once(unlock, `lock already released`)
|
||||
return Promise.resolve(once(unlock, `lock already released`))
|
||||
}
|
||||
}
|
||||
|
||||
return { lock }
|
||||
}
|
||||
|
||||
// l = createLock()
|
||||
// unlock1 = await l.lock() // immediate
|
||||
// unlock2 = await l.lock() // hangs...
|
||||
// unlock1() // l2 restarts...
|
||||
// unlock2() // no waiters so noop
|
||||
type DatabaseConnection = {
|
||||
path: string
|
||||
initialValue: Database
|
||||
mu: Mutex
|
||||
}
|
||||
|
||||
export function createDatabase(path, initialValue) {
|
||||
export type Database = {
|
||||
users: Record<string, User>
|
||||
problems: Record<string, Problem>
|
||||
solutions: Record<string, Solution>
|
||||
}
|
||||
|
||||
export function createDatabase(path: string, initialValue: Database) {
|
||||
return {
|
||||
path,
|
||||
initialValue,
|
||||
@@ -59,8 +83,11 @@ export function createDatabase(path, initialValue) {
|
||||
}
|
||||
}
|
||||
|
||||
async function withDatabase({ path, initialValue, mu }, fn) {
|
||||
const unlock = await mu.lock()
|
||||
async function withDatabase<R>(
|
||||
{ path, initialValue, mu }: DatabaseConnection,
|
||||
fn: (db: Database) => R | Promise<R>
|
||||
): Promise<R> {
|
||||
const unlock: Lock = await mu.lock()
|
||||
|
||||
try {
|
||||
await access(path, constants.R_OK)
|
||||
@@ -82,43 +109,30 @@ async function withDatabase({ path, initialValue, mu }, fn) {
|
||||
return result
|
||||
}
|
||||
|
||||
export const getUsers = db =>
|
||||
//
|
||||
// Users
|
||||
//
|
||||
|
||||
export const getUsers = (db: DatabaseConnection) =>
|
||||
withDatabase(db, state => {
|
||||
return Object.values(state.users)
|
||||
})
|
||||
|
||||
export const getUser = (db, id) =>
|
||||
withDatabase(db, state => {
|
||||
export const getUser = (db: DatabaseConnection, id: string) =>
|
||||
withDatabase(db, (state: Database): User | null => {
|
||||
return state.users[id] ?? null
|
||||
})
|
||||
|
||||
// export const createUser = (db, { email, username }) =>
|
||||
// withDatabase(db, state => {
|
||||
// state.users[username] = {
|
||||
// email,
|
||||
// username,
|
||||
// }
|
||||
// })
|
||||
|
||||
// export const updateUser = (db, username, { email, password }) =>
|
||||
// withDatabase(db, state => {
|
||||
// state.users[username] = {
|
||||
// email,
|
||||
// password,
|
||||
// }
|
||||
// })
|
||||
|
||||
//
|
||||
// Problems
|
||||
//
|
||||
|
||||
export const createProblem = (db, { content, createdBy }) =>
|
||||
export const createProblem = (
|
||||
db: DatabaseConnection,
|
||||
{ content, createdBy }: Omit<Problem, 'id' | 'createdAt'>
|
||||
): Promise<ProblemId> =>
|
||||
withDatabase(db, state => {
|
||||
const nextId = (
|
||||
Object.keys(state.problems)
|
||||
.map(k => parseInt(k))
|
||||
.reduce((acc, id) => Math.max(acc, id)) + 1
|
||||
).toString()
|
||||
const nextId = (Object.keys(state.problems).length + 1).toString() as ProblemId
|
||||
|
||||
state.problems[nextId] = {
|
||||
id: nextId,
|
||||
@@ -130,12 +144,12 @@ export const createProblem = (db, { content, createdBy }) =>
|
||||
return nextId
|
||||
})
|
||||
|
||||
export const getProblem = (db, id) =>
|
||||
export const getProblem = (db: DatabaseConnection, id: string): Promise<Problem> =>
|
||||
withDatabase(db, state => {
|
||||
return state.problems[id]
|
||||
})
|
||||
|
||||
export const getProblems = db =>
|
||||
export const getProblems = (db: DatabaseConnection): Promise<Problem[]> =>
|
||||
withDatabase(db, state => {
|
||||
return Object.values(state.problems)
|
||||
})
|
||||
@@ -144,31 +158,52 @@ export const getProblems = db =>
|
||||
// Solutions
|
||||
//
|
||||
|
||||
export const createSolution = (db, { userId, problemId, content }) =>
|
||||
export const createSolution = (
|
||||
db: DatabaseConnection,
|
||||
{ sentBy, forProblem, content }: Omit<Solution, MetaProps>
|
||||
): Promise<SolutionId> =>
|
||||
withDatabase(db, state => {
|
||||
const id = crypto.randomBytes(10).toString('hex')
|
||||
state.solutions[id] = {
|
||||
id,
|
||||
userId,
|
||||
problemId,
|
||||
sentBy,
|
||||
forProblem,
|
||||
content,
|
||||
status: 'pending',
|
||||
}
|
||||
|
||||
return id
|
||||
})
|
||||
|
||||
export const getSolution = (db, id) =>
|
||||
export const getSolution = (db: DatabaseConnection, id: SolutionId): Promise<Solution> =>
|
||||
withDatabase(db, state => {
|
||||
return state.solutions[id]
|
||||
})
|
||||
|
||||
export const getSolutions = (db, { userId, problemId } = {}) =>
|
||||
export const updateSolution = (
|
||||
db: DatabaseConnection,
|
||||
id: SolutionId,
|
||||
solution: Omit<Solution, MetaProps>
|
||||
): Promise<Solution> =>
|
||||
withDatabase(db, state => {
|
||||
state.solutions[id] = { id, ...solution }
|
||||
return state.solutions[id]
|
||||
})
|
||||
|
||||
type SolutionsQuery = Partial<{
|
||||
sentBy: UserId
|
||||
forProblem: ProblemId
|
||||
}>
|
||||
|
||||
export const getSolutions = (db: DatabaseConnection, { sentBy, forProblem }: SolutionsQuery = {}) =>
|
||||
withDatabase(db, state => {
|
||||
let solutions = Object.values(state.solutions)
|
||||
|
||||
if (userId) {
|
||||
solutions = solutions.filter(s => s.userId === userId)
|
||||
if (sentBy) {
|
||||
solutions = solutions.filter(s => s.sentBy === sentBy)
|
||||
}
|
||||
if (problemId) {
|
||||
solutions = solutions.filter(s => s.problemId === problemId)
|
||||
if (forProblem) {
|
||||
solutions = solutions.filter(s => s.forProblem === forProblem)
|
||||
}
|
||||
|
||||
return solutions
|
||||
@@ -1,7 +0,0 @@
|
||||
export const initialDatabaseValue = {
|
||||
users: {
|
||||
['BachoSeven']: {},
|
||||
['aziis98']: {},
|
||||
},
|
||||
problems: {},
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { UserId } from '../../shared/model'
|
||||
import { Database } from './database'
|
||||
|
||||
export const initialDatabaseValue: Database = {
|
||||
users: {
|
||||
['BachoSeven']: {
|
||||
id: 'BachoSeven' as UserId,
|
||||
role: 'admin',
|
||||
},
|
||||
['aziis98']: {
|
||||
id: 'aziis98' as UserId,
|
||||
role: 'admin',
|
||||
},
|
||||
},
|
||||
problems: {},
|
||||
solutions: {},
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
import { Router } from 'express'
|
||||
|
||||
const createRouter = setup => options => {
|
||||
const r = new Router()
|
||||
setup(r, options)
|
||||
return r
|
||||
}
|
||||
|
||||
export const createStatusRouter = createRouter(r => {
|
||||
r.get('/', (req, res) => {
|
||||
res.json({ url: req.originalUrl, status: 'ok' })
|
||||
})
|
||||
})
|
||||
|
||||
export class PingRouter extends Router {
|
||||
constructor() {
|
||||
super()
|
||||
|
||||
this.post('/', (req, res) => {
|
||||
if (req.body?.message === 'ping') {
|
||||
res.json('pong')
|
||||
} else {
|
||||
res.status(400)
|
||||
res.json('Invalid request')
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export const INVALID_SESSION = `invalid session token`
|
||||
|
||||
export const authMiddleware = getUserForSession => async (req, res, next) => {
|
||||
if (req.cookies.sid) {
|
||||
const user = await getUserForSession(req.cookies.sid)
|
||||
if (user) {
|
||||
req.user = user
|
||||
} else {
|
||||
res.cookie('sid', '', { expires: new Date() })
|
||||
}
|
||||
}
|
||||
|
||||
next()
|
||||
}
|
||||
|
||||
export const authenticatedMiddleware = (req, res, next) => {
|
||||
req.user && next()
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import express, { NextFunction, Request, Response, Router } from 'express'
|
||||
import { User } from '../shared/model'
|
||||
|
||||
const createRouter =
|
||||
<T>(setup: (r: Router, options?: T) => void) =>
|
||||
(options: T) => {
|
||||
const r = express.Router()
|
||||
setup(r, options)
|
||||
return r
|
||||
}
|
||||
|
||||
export const createStatusRouter = createRouter(r => {
|
||||
r.get('/', (req, res) => {
|
||||
res.json({ url: req.originalUrl, status: 'ok' })
|
||||
})
|
||||
}) as () => Router
|
||||
|
||||
// export class PingRouter extends express.Router {
|
||||
// constructor() {
|
||||
// super()
|
||||
|
||||
// this.post('/', (req, res) => {
|
||||
// if (req.body?.message === 'ping') {
|
||||
// res.json('pong')
|
||||
// } else {
|
||||
// res.status(400)
|
||||
// res.json('Invalid request')
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
// }
|
||||
|
||||
export const INVALID_SESSION = `invalid session token`
|
||||
|
||||
export const authMiddleware =
|
||||
<U>(getUserForSession: (sid: string) => U) =>
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
if (req.cookies.sid) {
|
||||
const user = await getUserForSession(req.cookies.sid)
|
||||
if (user) {
|
||||
// @ts-ignore
|
||||
req.user = user
|
||||
} else {
|
||||
res.cookie('sid', '', { expires: new Date() })
|
||||
}
|
||||
}
|
||||
|
||||
next()
|
||||
}
|
||||
|
||||
interface AuthenticatedRequest extends Request {
|
||||
user: User | null
|
||||
}
|
||||
|
||||
export const authenticatedMiddleware = (
|
||||
req: AuthenticatedRequest,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
) => {
|
||||
req.user && next()
|
||||
}
|
||||
@@ -1,170 +0,0 @@
|
||||
import crypto from 'crypto'
|
||||
|
||||
import bodyParser from 'body-parser'
|
||||
import cookieParser from 'cookie-parser'
|
||||
|
||||
import express from 'express'
|
||||
|
||||
import { createStatusRouter, PingRouter } from './middlewares.js'
|
||||
import {
|
||||
createDatabase,
|
||||
createProblem,
|
||||
createSolution,
|
||||
getProblem,
|
||||
getProblems,
|
||||
getSolutions,
|
||||
getUser,
|
||||
getUsers,
|
||||
} from './db/database.js'
|
||||
import { initialDatabaseValue } from './db/example-data.js'
|
||||
|
||||
export async function createApiRouter() {
|
||||
const sessions = {
|
||||
store: {},
|
||||
createSession(username) {
|
||||
const sid = crypto.randomBytes(10).toString('hex')
|
||||
this.store[sid] = username
|
||||
return sid
|
||||
},
|
||||
getUserForSession(sid) {
|
||||
return this.store[sid] ?? null
|
||||
},
|
||||
}
|
||||
|
||||
const db = createDatabase('./db.local.json', initialDatabaseValue)
|
||||
|
||||
async function getRequestUser(req) {
|
||||
const userId = sessions.getUserForSession(req.cookies.sid)
|
||||
if (!userId) {
|
||||
return null
|
||||
}
|
||||
|
||||
const user = await getUser(db, userId)
|
||||
|
||||
return user
|
||||
}
|
||||
|
||||
const r = express.Router()
|
||||
|
||||
r.use(bodyParser.json())
|
||||
r.use(cookieParser())
|
||||
|
||||
r.use('/api/status', createStatusRouter())
|
||||
r.use('/api/ping', new PingRouter())
|
||||
|
||||
r.get('/api/current-user', async (req, res) => {
|
||||
res.json(await getRequestUser(req))
|
||||
})
|
||||
|
||||
r.post('/api/login', async (req, res) => {
|
||||
const { username } = req.body
|
||||
|
||||
const user = await getUser(db, username)
|
||||
if (!user) {
|
||||
res.sendStatus(403)
|
||||
return
|
||||
}
|
||||
|
||||
res.cookie('sid', sessions.createSession(username), { maxAge: 1000 * 60 * 60 * 24 * 7 })
|
||||
res.json({ status: 'ok' })
|
||||
})
|
||||
|
||||
r.post('/api/logout', (req, res) => {
|
||||
res.cookie('sid', '', { expires: new Date() })
|
||||
res.json({ status: 'ok' })
|
||||
})
|
||||
|
||||
r.get('/api/users', async (req, res) => {
|
||||
const requestUser = await getRequestUser(req)
|
||||
if (requestUser.role !== 'admin' && requestUser.role !== 'moderator') {
|
||||
res.sendStatus(401)
|
||||
return
|
||||
}
|
||||
|
||||
const users = await getUsers(db)
|
||||
res.json(users)
|
||||
})
|
||||
|
||||
r.get('/api/problems', async (req, res) => {
|
||||
res.json(await getProblems(db))
|
||||
})
|
||||
|
||||
r.get('/api/problem/:id', async (req, res) => {
|
||||
res.json(await getProblem(db, req.params.id))
|
||||
})
|
||||
|
||||
r.post('/api/problem', async (req, res) => {
|
||||
const user = await getRequestUser(req)
|
||||
if (!user) {
|
||||
res.sendStatus(401)
|
||||
return
|
||||
}
|
||||
if (user.role !== 'admin' && user.role !== 'moderator') {
|
||||
res.sendStatus(401)
|
||||
return
|
||||
}
|
||||
|
||||
const id = await createProblem(db, {
|
||||
content: req.body.content,
|
||||
createBy: user.username,
|
||||
})
|
||||
|
||||
res.json(id)
|
||||
})
|
||||
|
||||
r.get('/api/solutions', async (req, res) => {
|
||||
let queryUserId = req.query.user
|
||||
let queryProblemId = req.query.problem
|
||||
|
||||
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 (requestUser.role !== 'admin' && requestUser.role !== 'moderator') {
|
||||
queryUserId = requestUser.username
|
||||
}
|
||||
|
||||
res.json(await getSolutions(db, { userId: queryUserId, problemId: queryProblemId }))
|
||||
})
|
||||
|
||||
r.post('/api/solution', async (req, res) => {
|
||||
const user = await getRequestUser(req)
|
||||
if (!user) {
|
||||
res.sendStatus(401)
|
||||
return
|
||||
}
|
||||
|
||||
await createSolution(db, {
|
||||
userId: user.username,
|
||||
problemId: req.body.problemId,
|
||||
content: req.body.content,
|
||||
})
|
||||
|
||||
res.send({ status: 'ok' })
|
||||
})
|
||||
|
||||
r.get('/api/user/:id', async (req, res) => {
|
||||
const requestUser = await getRequestUser(req)
|
||||
if (!requestUser) {
|
||||
res.sendStatus(401)
|
||||
return
|
||||
}
|
||||
if (requestUser.role !== 'admin' && requestUser.role !== 'moderator') {
|
||||
res.sendStatus(401)
|
||||
return
|
||||
}
|
||||
|
||||
const requestedUser = await getUser(db, req.params.id)
|
||||
if (!requestedUser) {
|
||||
res.sendStatus(404)
|
||||
return
|
||||
}
|
||||
|
||||
res.json(requestedUser)
|
||||
})
|
||||
|
||||
return r
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
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 {
|
||||
createDatabase,
|
||||
createProblem,
|
||||
createSolution,
|
||||
getProblem,
|
||||
getProblems,
|
||||
getSolution,
|
||||
getSolutions,
|
||||
getUser,
|
||||
getUsers,
|
||||
updateSolution,
|
||||
} from './db/database'
|
||||
|
||||
import { isAdministrator, isStudent, Problem, ProblemId, UserId } from '../shared/model'
|
||||
import { initialDatabaseValue } from './db/example-data'
|
||||
|
||||
export async function createApiRouter() {
|
||||
type SessionId = string
|
||||
|
||||
const sessions = {
|
||||
store: {},
|
||||
createSession(userId: UserId) {
|
||||
const sid = crypto.randomBytes(10).toString('hex')
|
||||
this.store[sid] = userId
|
||||
return sid
|
||||
},
|
||||
getUserForSession(sid: SessionId) {
|
||||
return this.store[sid] ?? null
|
||||
},
|
||||
}
|
||||
|
||||
const db = createDatabase('./db.local.json', initialDatabaseValue)
|
||||
|
||||
async function getRequestUser(req: Request) {
|
||||
const userId = sessions.getUserForSession(req.cookies.sid)
|
||||
if (!userId) {
|
||||
return null
|
||||
}
|
||||
|
||||
console.log(userId)
|
||||
|
||||
return await getUser(db, userId)
|
||||
}
|
||||
|
||||
const r: Router = express.Router()
|
||||
|
||||
r.use(bodyParser.json())
|
||||
r.use(cookieParser())
|
||||
|
||||
r.use('/api/status', createStatusRouter())
|
||||
// r.use('/api/ping', new PingRouter())
|
||||
|
||||
r.get('/api/current-user', async (req, res) => {
|
||||
res.json(await getRequestUser(req))
|
||||
})
|
||||
|
||||
r.post('/api/login', async (req, res) => {
|
||||
const { id } = req.body
|
||||
|
||||
const user = await getUser(db, id)
|
||||
if (!user) {
|
||||
res.sendStatus(403)
|
||||
return
|
||||
}
|
||||
|
||||
res.cookie('sid', sessions.createSession(id), { maxAge: 1000 * 60 * 60 * 24 * 7 })
|
||||
res.json({ status: 'ok' })
|
||||
})
|
||||
|
||||
r.post('/api/logout', (req, res) => {
|
||||
res.cookie('sid', '', { expires: new Date() })
|
||||
res.json({ status: 'ok' })
|
||||
})
|
||||
|
||||
r.get('/api/users', async (req, res) => {
|
||||
const requestUser = await getRequestUser(req)
|
||||
if (requestUser.role !== 'admin' && requestUser.role !== 'moderator') {
|
||||
res.sendStatus(401)
|
||||
return
|
||||
}
|
||||
|
||||
const users = await getUsers(db)
|
||||
res.json(users)
|
||||
})
|
||||
|
||||
r.get('/api/problems', async (req, res) => {
|
||||
type ProblemWithSolutionsCount = Problem & { solutionsCount?: number }
|
||||
|
||||
const problems: ProblemWithSolutionsCount[] = await getProblems(db)
|
||||
const solutions = await getSolutions(db)
|
||||
|
||||
const solutionCounts: Record<ProblemId, number> = {}
|
||||
|
||||
for (const s of solutions) {
|
||||
solutionCounts[s.forProblem] ||= 0
|
||||
solutionCounts[s.forProblem]++
|
||||
}
|
||||
|
||||
for (const p of problems) {
|
||||
p.solutionsCount = solutionCounts[p.id] || 0
|
||||
}
|
||||
|
||||
res.json(problems)
|
||||
})
|
||||
|
||||
r.get('/api/problem/:id', async (req, res) => {
|
||||
res.json(await getProblem(db, req.params.id))
|
||||
})
|
||||
|
||||
r.post('/api/problem', async (req, res) => {
|
||||
const user = await getRequestUser(req)
|
||||
if (!user) {
|
||||
res.sendStatus(401)
|
||||
return
|
||||
}
|
||||
if (user.role !== 'admin' && user.role !== 'moderator') {
|
||||
res.sendStatus(401)
|
||||
return
|
||||
}
|
||||
|
||||
const id = await createProblem(db, {
|
||||
content: req.body.content,
|
||||
createdBy: user.id,
|
||||
})
|
||||
|
||||
res.json(id)
|
||||
})
|
||||
|
||||
r.get('/api/solution/:id', async (req, res) => {
|
||||
const user = await getRequestUser(req)
|
||||
|
||||
// l'utente deve essere loggato
|
||||
if (!user) {
|
||||
res.sendStatus(401)
|
||||
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)
|
||||
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)
|
||||
return
|
||||
}
|
||||
|
||||
await createSolution(db, {
|
||||
sentBy: user.id,
|
||||
forProblem: req.body.problemId,
|
||||
content: req.body.content,
|
||||
status: 'pending',
|
||||
})
|
||||
|
||||
res.send({ status: 'ok' })
|
||||
})
|
||||
|
||||
r.post('/api/solution/:id', async (req, res) => {
|
||||
const user = await getRequestUser(req)
|
||||
|
||||
// l'utente deve essere loggato
|
||||
if (!user) {
|
||||
res.sendStatus(401)
|
||||
return
|
||||
}
|
||||
|
||||
const solutionId = req.params.id
|
||||
const solution = await getSolution(db, solutionId)
|
||||
|
||||
// uno studente non può modificare una soluzione di un altro utente
|
||||
if (isStudent(user.role) && solution.sentBy !== user.id) {
|
||||
res.sendStatus(401)
|
||||
return
|
||||
}
|
||||
|
||||
// modifico la soluzione con il json mandato dal client nel body della richiesta
|
||||
await updateSolution(db, solutionId, req.body)
|
||||
|
||||
res.json({ status: 'ok' })
|
||||
})
|
||||
|
||||
r.get('/api/user/:id', async (req, res) => {
|
||||
const user = await getRequestUser(req)
|
||||
|
||||
// intanto l'utente deve essere loggato
|
||||
if (!user) {
|
||||
res.sendStatus(401)
|
||||
return
|
||||
}
|
||||
|
||||
// solo gli amministratori possono usare questa route
|
||||
if (!isAdministrator(user.role)) {
|
||||
res.sendStatus(401)
|
||||
return
|
||||
}
|
||||
|
||||
const requestedUser = await getUser(db, req.params.id)
|
||||
|
||||
// l'utente richiesto magari deve esistere
|
||||
if (!requestedUser) {
|
||||
res.sendStatus(404)
|
||||
return
|
||||
}
|
||||
|
||||
res.json(requestedUser)
|
||||
})
|
||||
|
||||
return r
|
||||
}
|
||||
Reference in New Issue
Block a user