refactor: switch to arrays instead of Objects/maps

pull/177/head
tycrek 1 year ago
parent 499aac0f5b
commit 27aa264d37
No known key found for this signature in database
GPG Key ID: FF8A54DCE404885A

@ -132,7 +132,7 @@ app.use((err: ErrWrap, _req: Request, res: Response) => log.error(err.message).e
if (data() == null) setTimeout(start, 100);
else log
.info('Users', `${users.size}`)
.info('Users', `${users.length}`)
.info('Files', `${data().size}`)
.info('Data engine', data().name, data().type)
.info('Frontend', ASS_FRONTEND.enabled ? ASS_FRONTEND.brand : 'disabled', `${ASS_FRONTEND.enabled ? `${getTrueHttp()}${getTrueDomain()}${ASS_FRONTEND.endpoint}` : ''}`)

@ -23,7 +23,7 @@ import { Request } from 'express';
/**
* Map of users
*/
export const users = new Map<string, User>();
export const users = [] as User[];
/**
* Migrates the old auth.json format to the new one
@ -36,15 +36,15 @@ const migrate = (): Promise<Users> => new Promise(async (resolve, reject) => {
const oldUsers = fs.readJsonSync(authPath).users as OldUsers;
// Create a new users object
const newUsers: Users = { users: {}, meta: {} };
const newUsers: Users = { users: [], meta: {} };
newUsers.migrated = true;
// Loop through each user
Object.entries(oldUsers).forEach(([token, { username }]) => {
// Create a new user object
const id = nanoid();
const newUser: User = {
unid: nanoid(),
username: username,
passhash: '', // TODO: Figure out how to configure passwords
token,
@ -52,7 +52,7 @@ const migrate = (): Promise<Users> => new Promise(async (resolve, reject) => {
meta: {}
};
newUsers.users[id] = newUser;
newUsers.users.push(newUser);
});
// Save the new users object to auth.json
@ -69,8 +69,8 @@ export const createNewUser = (username: string, passhash: string, admin: boolean
// todo: finish this
// Create a new user object
const id = nanoid();
const newUser: User = {
unid: nanoid(),
username,
passhash,
token: nanoid(32),
@ -79,13 +79,13 @@ export const createNewUser = (username: string, passhash: string, admin: boolean
};
// Add the user to the users map
users.set(id, newUser);
users.push(newUser);
// Save the new user to auth.json
const authPath = path('auth.json');
const auth = fs.readJsonSync(authPath) as Users;
auth.users[id] = newUser;
fs.writeJson(authPath, auth, { spaces: '\t' });
const authData = fs.readJsonSync(authPath) as Users;
authData.users.push(newUser);
fs.writeJson(authPath, authData, { spaces: '\t' });
});
@ -126,20 +126,17 @@ export const onStart = (authFile = 'auth.json') => new Promise((resolve, reject)
}
// Add users to the map
Object.entries(json.users).forEach(([uuid, user]) => users.set(uuid, user));
json.users.forEach((user) => users.push(user));
})
.catch((errReadJson) => log.error('Failed to read auth.json').callback(reject, errReadJson))
.then(resolve);
});
/**
* Retrieves a user using their upload token.
* Retrieves a user using their upload token. Returns `null` if the user does not exist.
*/
export const findFromToken = (token: string) => {
for (const [uuid, user] of users)
if (user.token === token)
return { uuid, user };
return null;
return users.find((user) => user.token === token) || null;
};
/**

@ -49,7 +49,7 @@ router.get('/', (req: Request, res: Response, next) => data().get(req.ass.resour
fileIs: fileData.is,
title: escape(fileData.originalname),
mimetype: fileData.mimetype,
uploader: findFromToken(fileData.token)?.user.username || 'Unknown',
uploader: findFromToken(fileData.token)?.username ?? 'Unknown',
timestamp: formatTimestamp(fileData.timestamp, fileData.timeoffset),
size: formatBytes(fileData.size),
// todo: figure out how to not ignore this

@ -110,7 +110,7 @@ router.post('/', (req: Request, res: Response, next: Function) => {
.then(() => {
// Log the upload
const logInfo = `${req.file!.originalname} (${req.file!.mimetype}, ${formatBytes(req.file.size)})`;
const uploader = findFromToken(req.token)?.user.username ?? 'Unknown';
const uploader = findFromToken(req.token)?.username ?? 'Unknown';
log.success('File uploaded', logInfo, `uploaded by ${uploader}`);
// Build the URLs

@ -2,6 +2,11 @@
* Defines the structure of a user
*/
export interface User {
/**
* Unique ID, provided by Nano ID
*/
unid: string
/**
* Name of the user
*/
@ -37,9 +42,7 @@ export interface Users {
/**
* List of users. The key is the user's unique ID.
*/
users: {
[key: string]: User
}
users: User[]
/**
* Indicates whether auth.json has been migrated

Loading…
Cancel
Save