feat: added setting username via API

pull/190/head
tycrek 2 years ago
parent 5c89d67922
commit 642e84910b
No known key found for this signature in database
GPG Key ID: FF8A54DCE404885A

@ -239,6 +239,33 @@ export const deleteUserMeta = (unid: string, key: string): Promise<User> => new
.catch(reject); .catch(reject);
}); });
/**
* Sets the username for a user
* @since v0.14.1
*/
export const setUsername = (unid: string, username: string): Promise<User> => new Promise((resolve, reject) => {
// Find the user
const user = users.find((user) => user.unid === unid);
if (!user) return reject(new Error('User not found'));
// Check if the username is already taken
if (users.find((user) => user.username === username)) return reject(new Error('Username already taken'));
// Set the username
user.username = username;
// Save the new user to auth.json
const authPath = path('auth.json');
const authData = fs.readJsonSync(authPath) as Users;
const userIndex = authData.users.findIndex((user) => user.unid === unid);
authData.users[userIndex] = user;
fs.writeJson(authPath, authData, { spaces: '\t' })
.then(() => log.info('Set username for', user.unid, username))
.then(() => resolve(user))
.catch(reject);
});
/** /**
* Called by ass.ts on startup * Called by ass.ts on startup
* @since v0.14.0 * @since v0.14.0

@ -5,7 +5,7 @@
*/ */
import { Router, Request, Response, NextFunction } from 'express'; import { Router, Request, Response, NextFunction } from 'express';
import { findFromToken, setUserPassword, users, createNewUser, deleteUser, setUserMeta, deleteUserMeta, verifyCliKey } from '../auth'; import { findFromToken, setUserPassword, users, createNewUser, deleteUser, setUserMeta, deleteUserMeta, setUsername, verifyCliKey } from '../auth';
import { log } from '../utils'; import { log } from '../utils';
import { data } from '../data'; import { data } from '../data';
import { User } from '../types/auth'; import { User } from '../types/auth';
@ -124,6 +124,20 @@ function buildUserRouter() {
.catch((err) => errorHandler(res, err)); .catch((err) => errorHandler(res, err));
}); });
// Sets a username
// Admin only
userRouter.put('/username/:id', adminAuthMiddleware, (req: Request, res: Response) => {
const id = req.params.id;
const username: string | undefined = req.body.username;
if (username == null || username.length === 0)
return res.sendStatus(400);
setUsername(id, username)
.then(() => res.sendStatus(200))
.catch((err) => errorHandler(res, err));
});
// Delete a user meta key // Delete a user meta key
// Admin only // Admin only
userRouter.delete('/meta/:id', adminAuthMiddleware, (req: Request, res: Response) => { userRouter.delete('/meta/:id', adminAuthMiddleware, (req: Request, res: Response) => {

Loading…
Cancel
Save