feat: add creating users via API

pull/188/head
tycrek 1 year ago
parent faaaa8d572
commit 4663ce40c9
No known key found for this signature in database
GPG Key ID: FF8A54DCE404885A

@ -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<User> => new Promise(async (resolve, reject) => {

@ -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) =>

Loading…
Cancel
Save