feat: admin user management routes
This commit is contained in:
@@ -4,6 +4,7 @@ import {
|
||||
verifyPassword,
|
||||
createUser,
|
||||
getUserByUsername,
|
||||
getUserById,
|
||||
createSession,
|
||||
getUserBySession,
|
||||
deleteSession,
|
||||
@@ -93,6 +94,8 @@ export async function registerAuthRoutes(app: FastifyInstance): Promise<void> {
|
||||
if (!user || !ok) {
|
||||
return reply.code(401).send({ error: 'invalid_credentials' })
|
||||
}
|
||||
const oldToken = request.cookies[COOKIE_NAME]
|
||||
if (oldToken) deleteSession(request.server.db, oldToken)
|
||||
const token = createSession(request.server.db, user.id)
|
||||
return reply.setCookie(COOKIE_NAME, token, cookieOpts()).code(200).send({ user: toPublicUser(user) })
|
||||
})
|
||||
@@ -106,4 +109,37 @@ export async function registerAuthRoutes(app: FastifyInstance): Promise<void> {
|
||||
app.get('/api/me', { preHandler: [requireAuth] }, async (request) => {
|
||||
return { user: toPublicUser(request.user as UserRow) }
|
||||
})
|
||||
|
||||
app.get('/api/users', { preHandler: [requireAuth, requireAdmin] }, async (request) => {
|
||||
const users = request.server.db.prepare('SELECT * FROM users ORDER BY id').all() as UserRow[]
|
||||
return { users: users.map(toPublicUser) }
|
||||
})
|
||||
|
||||
app.post('/api/users', { preHandler: [requireAuth, requireAdmin] }, async (request, reply) => {
|
||||
const { username, password } = (request.body ?? {}) as { username?: string; password?: string }
|
||||
const invalid = validateCredentials(username, password)
|
||||
if (invalid) return reply.code(400).send({ error: 'invalid_input', detail: invalid })
|
||||
if (getUserByUsername(request.server.db, username as string)) {
|
||||
return reply.code(409).send({ error: 'username_taken' })
|
||||
}
|
||||
const user = createUser(request.server.db, username as string, await hashPassword(password as string), false)
|
||||
request.server.db.prepare('INSERT INTO settings (user_id) VALUES (?)').run(user.id)
|
||||
return reply.code(200).send(toPublicUser(user))
|
||||
})
|
||||
|
||||
app.delete(
|
||||
'/api/users/:id',
|
||||
{ preHandler: [requireAuth, requireAdmin] },
|
||||
async (request, reply) => {
|
||||
const id = Number((request.params as { id: string }).id)
|
||||
if (id === (request.user as UserRow).id) {
|
||||
return reply.code(400).send({ error: 'cannot_delete_self' })
|
||||
}
|
||||
if (!getUserById(request.server.db, id)) {
|
||||
return reply.code(404).send({ error: 'not_found' })
|
||||
}
|
||||
request.server.db.prepare('DELETE FROM users WHERE id = ?').run(id)
|
||||
return reply.code(200).send({ ok: true })
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user