You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.5 KiB
TypeScript

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()
}