Something went wrong. Try again.
A self-hosted web platform for applications & services with design based on Google's Material 3 Expressive. (Work In Progress)
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628import { promises as fs, existsSync as fsExistsSync } from "node:fs";import path from "node:path";import sharp from "sharp";import type { Instance } from "../index.ts";import System from "../system.ts";
export interface IUserDatabaseUser { id: number; username: string; forename: string; surname: string;}
// WARNING!: do not call new WorkspacesUser() it is only to be created by the UsersSubsystemexport class WorkspacesUser { userId: number; private instance: Instance;
constructor(instance: Instance, userId: number) { this.instance = instance; this.userId = userId; }
getPath(): string { return path.join(this.instance.sys.filesystem.FS_ROOT, `users/${this.userId}`); }
/** Sets the user's username to username @return `false` - failed to change the username @return `true` - successfully changed the username */ async setUsername(username: string): Promise<boolean> { const db = this.instance.sys.database.postgres();
try { if ((await db`SELECT username FROM public.users WHERE username = ${username}`).count !== 0) return false;
await db`UPDATE public.users SET username = ${username} WHERE id = ${this.userId}`; return true; } catch (_) { this.instance.sys.users.log.error(`Failed to set username for ${this.userId}`); return false; } }
/** Get the user's username @return `string` - the users username @return `undefined` - could not get the user's username */ async getUsername(): Promise<string | undefined> { const db = this.instance.sys.database.postgres();
return (await db`SELECT username FROM public.users WHERE id = ${this.userId}`)?.[0]?.username || undefined; }
/** Sets the user's forename to forename @return `false` - failed to change the forename @return `true` - successfully changed the forename */ async setForename(forename: string): Promise<boolean> { const db = this.instance.sys.database.postgres();
try { await db`UPDATE public.users SET forename = ${forename} WHERE id = ${this.userId}`;
return true; } catch (_) { this.instance.sys.users.log.error(`Failed to set forename for ${this.userId}`); return false; } }
/** Get the user's forename @return `string` - the users forename @return `undefined` - could not get the user's forename */ async getForename(): Promise<string | undefined> { const db = this.instance.sys.database.postgres();
return (await db`SELECT forename FROM public.users WHERE id = ${this.userId}`)?.[0]?.forename || undefined; }
/** Sets the user's surname to surname @return `false` - failed to change the surname @return `true` - successfully changed the surname */ async setSurname(surname: string): Promise<boolean> { const db = this.instance.sys.database.postgres();
try { this.instance.log.system.info(`Set Surname to '${surname}' for ${this.userId}`);
await db`UPDATE public.users SET surname = ${surname} WHERE id = ${this.userId}`;
return true; } catch (_) { this.instance.sys.users.log.error(`Failed to set surname for ${this.userId}`); return false; } }
/** Get the user's surname @return `string` - the users surname @return `undefined` - could not get the user's surname */ async getSurname(): Promise<string | undefined> { const db = this.instance.sys.database.postgres();
return (await db`SELECT surname FROM public.users WHERE id = ${this.userId}`)?.[0]?.surname || undefined; }
/** Sets the user's forename and surname to the provided forename and surname @return `false` - failed to change the surname @return `true` - successfully changed the surname */ async setFullName(forename: string, surname: string): Promise<boolean> { const forenameRes = await this.setForename(forename); const surnameRes = await this.setSurname(surname);
return forenameRes && surnameRes; }
/** Gets the user's forename and surname */ async getFullName(): Promise<{ forename?: string; surname?: string }> { const forenameRes = await this.getForename(); const surnameRes = await this.getSurname();
return { forename: forenameRes, surname: surnameRes }; }
/** Sets the user's quota to the provided quota in bits @returns `false` - failed to set the quota @returns `true` - successfully set the quota */ async setQuota(quota: number): Promise<boolean> { const db = this.instance.sys.database.postgres();
try { await db`UPDATE public.users SET storage_quota = ${quota} WHERE id = ${this.userId}`; return true; } catch (_) { this.instance.sys.users.log.error(`Failed to set storage quota for ${this.userId}`); return false; } }
/** Get the user's quota in bits @returns `number` - the users quota @returns `undefined` - could not get the user's quota */ async getQuota(): Promise<number | undefined> { const db = this.instance.sys.database.postgres();
return (await db`SELECT storage_quota FROM public.users WHERE id = ${this.userId}`)?.[0]?.storage_quota || undefined; }
/** Sets the user's bio to bio @returns `false` - failed to change the bio @returns `true` - successfully changed the bio */ async setBio(bio: string): Promise<boolean> { const db = this.instance.sys.database.postgres();
try { await db`UPDATE public.users SET bio = ${bio} WHERE id = ${this.userId}`; return true; } catch (_) { this.instance.sys.users.log.error(`Failed to set bio for ${this.userId}`); return false; } }
/** Get the user's bio @returns `string` - the users bio @returns `undefined` - could not get the user's bio */ async getBio(): Promise<string | undefined> { const db = this.instance.sys.database.postgres();
return (await db`SELECT bio FROM public.users WHERE id = ${this.userId}`)?.[0]?.bio || undefined; }
/** Sets the user's email to email @returns `false` - failed to change the email @returns `true` - successfully changed the email */ async setEmail(email: string): Promise<boolean> { const db = this.instance.sys.database.postgres(); try { await db`UPDATE public.users SET email = ${email} WHERE id = ${this.userId}`; return true; } catch (_) { this.instance.sys.users.log.error(`Failed to set email for ${this.userId}`); return false; } }
/** Get the user's email @returns `string` - the users email @returns `undefined` - could not get the user's email */ async getEmail(): Promise<string | undefined> { const db = this.instance.sys.database.postgres();
return (await db`SELECT email FROM public.users WHERE id = ${this.userId}`)?.[0]?.email || undefined; }
/** Sets the user's gender to gender @returns `false` - failed to change the gender @returns `true` - successfully changed the gender */ async setGender(gender: "female" | "male" | "other"): Promise<boolean> { const db = this.instance.sys.database.postgres();
try { await db`UPDATE public.users SET gender = ${gender} WHERE id = ${this.userId}`; return true; } catch (_) { this.instance.sys.users.log.error(`Failed to set gender for ${this.userId}`); return false; } }
/** Get the user's gender @returns `"female" | "male" | "other"` - the users gender @returns `undefined` - could not get the user's gender */ async getGender(): Promise<string | undefined> { const db = this.instance.sys.database.postgres();
return (await db`SELECT gender FROM public.users WHERE id = ${this.userId}`)?.[0]?.gender || undefined; }
/** Join a specified group for the user. @returns `true` - if successfully joined the group @returns `false` - if already a member or an error occurred. */ async joinGroup(groupId: string): Promise<boolean> { const db = this.instance.sys.database.postgres();
try { const existingGroups = await this.getGroups();
if (existingGroups.includes(groupId)) { return false; }
await db` UPDATE public.users SET groups = array_append(groups, ${groupId}) WHERE id = ${this.userId} `;
return true; } catch (error) { console.error("Error joining group:", error); return false; } }
/** Leave a specified group for the user. @returns `true` - if successfully left the group @returns `false` - if not a member or an error occurred. */ async leaveGroup(groupId: string): Promise<boolean> { const db = this.instance.sys.database.postgres();
try { const existingGroups = await this.getGroups();
if (!existingGroups.includes(groupId)) { return false; }
await db` UPDATE public.users SET groups = array_remove(groups, ${groupId}) WHERE id = ${this.userId} `;
return true; } catch (error) { console.error("Error leaving group:", error); return false; } }
/** Returns an array of groups the user belongs to. @returns `string[]` - An array of group IDs the user is a member of, or an empty array if none. */ async getGroups(): Promise<string[]> { const db = this.instance.sys.database.postgres();
return (await db`SELECT groups FROM public.users WHERE id = ${this.userId}`)?.[0].groups || []; }
/** Get if the user is an administrator @returns `boolean` - if the user an administrator */ async isAdministrator(): Promise<boolean> { const db = this.instance.sys.database.postgres();
return (await db`SELECT is_administrator FROM public.users WHERE id = ${this.userId}`)?.[0]?.is_administrator || false; }
/** Sets if user is an administrator @returns `false` - failed to change the administrator status @returns `true` - successfully changed the administrator status */ async setIsAdministrator(administrator: boolean): Promise<boolean> { const db = this.instance.sys.database.postgres();
try { await db`UPDATE public.users SET is_administrator = ${administrator} WHERE id = ${this.userId}`; return true; } catch (_) { this.instance.sys.users.log.error(`Failed to set is_administrator for ${this.userId}`); return false; } }
/** sets the user's original quality avatar to avatarFile @returns `true` - copied the avatarFile successfully @returns `false` - failed to copy the avatarFile */ async setAvatar(avatarFile: string): Promise<boolean> { try { await fs.cp(avatarFile, path.join(this.getPath(), "assets/avatar/avatar.webp")); return true; } catch (_) { this.instance.sys.users.log.error(`Failed to set avatar for ${this.userId} to ${avatarFile}`); return false; } }
/** generates the required avatar sizes from the user's avatarFile, if override is not set to true, only missing avatar sizes will be generated @returns `true` - generated required avatar files successfully @returns `false` - failed to generate all required avatar files */ async generateAvatars(override?: boolean): Promise<boolean> { const AVATAR_SIZES: { width: number; height: number; name: string }[] = [ { width: 16, height: 16, name: "xs" }, { width: 32, height: 32, name: "s" }, { width: 64, height: 64, name: "m" }, { width: 128, height: 128, name: "l" }, { width: 256, height: 256, name: "xl" }, { width: 512, height: 512, name: "2xl" }, ];
try { for (const size of AVATAR_SIZES) { if (override || !fsExistsSync(path.join(this.getPath(), `assets/avatar/${size.name}.webp`))) { this.instance.sys.users.log.info(`Generating avatar for user '${this.userId}' @ ${size.name}`); await sharp(path.join(this.getPath(), "assets/avatar/avatar.webp")) .resize(size.width, size.height) .toFile(path.join(this.getPath(), `assets/avatar/${size.name}.webp`)); this.instance.sys.users.log.success(`Generated avatar for user '${this.userId}' @ ${size.name}`); } } } catch (_) { this.instance.sys.users.log.error("Failed to generate avatar sizes"); }
return true; }
/** Check that all required directories and assets are valid for this user. If they are missing or invalid, directories will be created and assets will be generated / copied @returns `true` - if successful */ async verify(): Promise<boolean> { const username = await this.getUsername(); const USER_DIRECTORIES = [ "/", "/fs", "/fs/Desktop", "/fs/Downloads", "/fs/Documents", "/fs/Photos", "/fs/Music", "/fs/Videos", "/assets", "/assets/avatar", "/assets/wallpapers", "/assets/wallpapers/resized", "/mounts", "/recycle_bin", "/system", "/system/logs", "/system/temp", ];
for (const dir of USER_DIRECTORIES) { await this.instance.sys.filesystem.createDirectoryIfNotExists(path.join(this.instance.sys.filesystem.FS_ROOT, `users/${this.userId}`, dir)); }
if (!fsExistsSync(path.join(this.getPath(), "assets/avatar/avatar.webp"))) { await this.setAvatar(path.join(this.instance.sys.filesystem.SRC_ROOT, "assets/placeholder/avatar.png")); }
await this.generateAvatars();
if (!(await this.instance.sys.authorization.hasPassword(this.userId))) { this.instance.sys.users.log.warning(`user (${this.userId})${username} has no password set! Without a password, this account cannot be accessed.`); }
this.instance.sys.users.log.success(`Verified user (${this.userId}) ${this.instance.sys.users.log.emphasis(`${username}`)}`);
return true; }
/** Deletes a user from the filesystem and all database entries */ async delete() { await fs.rm(path.join(this.instance.sys.filesystem.FS_ROOT, `users/${this.userId}`), { recursive: true, force: true, });
const db = this.instance.sys.database.postgres();
await db`DELETE FROM public.users WHERE id = ${this.userId};`; await db`DELETE FROM public.sessions WHERE user_id = ${this.userId};`;
return true; }}
export default class UsersSystem extends System { constructor(instance: Instance) { super("users", instance); }
override async startup(): Promise<boolean> { await super.startup();
const db = this.instance.sys.database.postgres();
/** init the users database
id - permanent unique user id number (number) username - the user's changeable username (string) forename - the user's chosen forename (string) surname - the user's chosen surname (string) gender - the user's chosen gender ("female" | "male" | "other") bio - the user's chosen bio (string) storage_quota - the user's storage quota in MB (number) email - the user's chosen contact email (string) is_administrator - is the user an administrator (boolean) is_email_verified - is the user's chosen contact email verified to be theirs (boolean) socials - the user's chosen social media links in the format '[name]:-:[url]' as such, the string ':-:' must not be in either [name] or [url] (string[]) hashed_password - the user's password after it has been hashed by bun (string) two_factor_secret - the user's secret string used to verify 2fa opt codes (string) settings - a settings object groups - a list of the group ids which this user is a member of color_scheme - the user's color scheme */ await db`CREATE TABLE IF NOT EXISTS users ( id SERIAL PRIMARY KEY, username TEXT, forename TEXT, surname TEXT DEFAULT '', gender TEXT DEFAULT 'other', bio TEXT, storage_quota BIGINT DEFAULT 8589934592, email TEXT, is_administrator BOOL DEFAULT FALSE, is_email_verified BOOL DEFAULT FALSE, socials TEXT[] DEFAULT '{}', hashed_password TEXT, two_factor_secret TEXT, settings JSONB DEFAULT '{}'::JSONB, groups TEXT[], color_scheme JSONB )`;
if (!(await this.getAllUsers()).find((u) => u.isAdministrator())) { this.log.warning("No administrator account exists, creating default administrator account with username 'admin' and password 'password'");
const administratorUserId = await this.createUser("admin");
// if the account is newly-created if (administratorUserId !== undefined) { const adminUser = await this.getUserById(administratorUserId);
if (!adminUser) { this.log.error("Admin user didn't exist and couldn't be created!"); } else { // Name: Admin Istrator await adminUser.setFullName("Admin", "Istrator"); await adminUser.setIsAdministrator(true);
const defaultPassword = "password";
await this.instance.sys.authorization.setPassword(adminUser.userId, defaultPassword); this.log.info(`The default admin user has a password of '${defaultPassword}'`); } } }
const users = await this.getAllUsers();
for (const user of users) { await user.verify(); }
return true; }
/** Create a new Workspaces User @returns number - the userId of the created user @returns undefined - the user already exists */ async createUser(username: string, password?: string): Promise<number | undefined> { const db = this.instance.sys.database.postgres();
if ((await db`SELECT username FROM public.users WHERE username = ${username}`).count !== 0) { this.log.warning(`Failed to create user ${username} as they already exist`); return undefined; }
const user = { username, forename: "John", surname: "Doe", };
const id = (await db`INSERT INTO public.users ${db(user)} RETURNING id`)?.[0]?.id;
const ubi = await this.getUserById(id);
if (!ubi) { this.log.error("Failed during the user creation process."); return undefined; }
if (password) await this.instance.sys.authorization.setPassword(id, password);
await ubi.setAvatar(path.join(this.instance.sys.filesystem.SRC_ROOT, "assets/placeholder/avatar.png"));
await ubi.verify();
return id; }
/** Does a user with the userId exist @returns true - they exist @returns false - they do not exist */ async doesUserExist(userId: number): Promise<boolean> { const db = this.instance.sys.database.postgres();
return (await db`SELECT username FROM public.users WHERE id = ${userId}`).count === 1; }
/** Gets an array of all users registered on this instance @returns `WorkspacesUser[]` - an array of all users */ async getAllUsers(): Promise<WorkspacesUser[]> { const db = this.instance.sys.database.postgres();
try { // @ts-ignore this is valid return (await db`SELECT id FROM public.users`).map((u: { id: number }) => new WorkspacesUser(this.instance, u.id)); } catch (err) { this.log.error("Failed to getAllUsers()", err);
return []; } }
/** Gets a user by their userId @returns `WorkspacesUser` - the user @returns `undefined` - no such user exists */ async getUserById(userId: number): Promise<WorkspacesUser | undefined> { if ((await this.doesUserExist(userId)) === undefined) return undefined;
return new WorkspacesUser(this.instance, userId); }
/** Gets a user by their username @returns `WorkspacesUser` - the user @returns `undefined` - no such user exists */ async getUserByUsername(username: string): Promise<WorkspacesUser | undefined> { const db = this.instance.sys.database.postgres();
const userId = (await db`SELECT id FROM public.users WHERE username = ${username}`)?.[0]?.id;
if (!(await this.doesUserExist(userId))) return undefined;
return new WorkspacesUser(this.instance, userId); }}