Skip to content

Commit

Permalink
feat: add creating users via API
Browse files Browse the repository at this point in the history
  • Loading branch information
tycrek committed Dec 25, 2022
1 parent faaaa8d commit 4663ce4
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
4 changes: 3 additions & 1 deletion src/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down
20 changes: 19 additions & 1 deletion src/routers/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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) =>
Expand Down

0 comments on commit 4663ce4

Please sign in to comment.