From 4663ce40c971fc6bbc3fd3f06eb561e39e959b5a Mon Sep 17 00:00:00 2001 From: tycrek Date: Sat, 24 Dec 2022 21:05:32 -0700 Subject: [PATCH] feat: add creating users via API --- src/auth.ts | 4 +++- src/routers/api.ts | 20 +++++++++++++++++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/auth.ts b/src/auth.ts index 7b7d1d7..384fabe 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -113,7 +113,9 @@ export const createNewUser = (username: string, password: string, admin: boolean const authPath = path('auth.json'); const authData = fs.readJsonSync(authPath) as Users; authData.users.push(newUser); - fs.writeJson(authPath, authData, { spaces: '\t' }); + fs.writeJson(authPath, authData, { spaces: '\t' }) + .then(() => resolve(newUser)) + .catch(reject); }); export const setUserPassword = (unid: string, password: string): Promise => new Promise(async (resolve, reject) => { diff --git a/src/routers/api.ts b/src/routers/api.ts index a7a0675..b15bb9d 100644 --- a/src/routers/api.ts +++ b/src/routers/api.ts @@ -5,7 +5,8 @@ */ import { Router, Request, Response, NextFunction } from 'express'; -import { findFromToken, setUserPassword, users } from '../auth'; +import { findFromToken, setUserPassword, users, createNewUser } from '../auth'; +import { log } from '../utils'; import { data } from '../data'; import { User } from '../types/auth'; @@ -56,6 +57,23 @@ function buildUserRouter() { .catch(() => res.sendStatus(500)); }); + // Create a new user + // Admin only + userRouter.post('/new', adminAuthMiddleware, (req: Request, res: Response) => { + const username: string | undefined = req.body.username; + const password: string | undefined = req.body.password; + const admin = req.body.admin ?? false; + const meta: any = req.body.meta ?? {}; + + // Block if username or password is empty, or if username is already taken + if (username == null || username.length === 0 || password == null || password.length == 0 || users.find(user => user.username === username)) + return res.sendStatus(400); + + createNewUser(username, password, admin, meta) + .then((user) => res.send(user)) + .catch((err) => (log.error(err), res.sendStatus(500))); + }); + // Get a user (must be last as it's a catch-all) // Admin only userRouter.get('/:id', adminAuthMiddleware, (req: Request, res: Response) =>