style: fixed indent -> everything into 2 spaces

This commit is contained in:
axel 2025-04-17 03:26:15 +02:00
parent d2e064d40f
commit 2981887224
49 changed files with 1255 additions and 1253 deletions

View File

@ -1,5 +1,5 @@
{
"useTabs": true,
"useTabs": false,
"singleQuote": true,
"trailingComma": "all",
"printWidth": 100,

View File

@ -2,5 +2,5 @@
@import 'tailwindcss';
* {
font-family: "Inter", sans-serif;
}
font-family: 'Inter', sans-serif;
}

20
src/app.d.ts vendored
View File

@ -1,19 +1,19 @@
// See https://svelte.dev/docs/kit/types#app.d.ts
import type { Guard } from "$lib/server/guard";
import type { Guard } from '$lib/server/guard';
import 'unplugin-icons/types/svelte';
// for information about these interfaces
declare global {
namespace App {
// interface Error {}
interface Locals {
guard: Guard;
}
// interface PageData {}
// interface PageState {}
// interface Platform {}
}
namespace App {
// interface Error {}
interface Locals {
guard: Guard;
}
// interface PageData {}
// interface PageState {}
// interface Platform {}
}
}
export {};

View File

@ -1,12 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<!-- <link rel="icon" href="%sveltekit.assets%/favicon.png" /> -->
<meta name="viewport" content="width=device-width, initial-scale=1" />
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
<head>
<meta charset="utf-8" />
<!-- <link rel="icon" href="%sveltekit.assets%/favicon.png" /> -->
<meta name="viewport" content="width=device-width, initial-scale=1" />
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>

View File

@ -7,30 +7,30 @@ import { writeFileSync } from 'fs';
import { nanoid } from 'nanoid';
export const init: ServerInit = async () => {
await initRepos();
await initRepos();
if (!(await users.any())) {
const pass = nanoid();
if (!(await users.any())) {
const pass = nanoid();
await users.create({
name: 'admin',
password: bcrypt.hashSync(pass, 10),
admin: true,
groups: [],
devices: [],
});
await users.create({
name: 'admin',
password: bcrypt.hashSync(pass, 10),
admin: true,
groups: [],
devices: [],
});
console.log(`default admin password: ${pass}`);
console.log("saved to ./default_admin_pass.txt, don't share it and change it asap");
console.log(`default admin password: ${pass}`);
console.log("saved to ./default_admin_pass.txt, don't share it and change it asap");
writeFileSync('./data/default_admin_pass.txt', pass);
}
writeFileSync('./data/default_admin_pass.txt', pass);
}
};
export const handle: Handle = async ({ event, resolve }) => {
const { cookies, locals } = event;
const { cookies, locals } = event;
locals.guard = new Guard(await getUserFromSession(cookies.get('session')));
locals.guard = new Guard(await getUserFromSession(cookies.get('session')));
return await resolve(event);
return await resolve(event);
};

View File

@ -8,9 +8,9 @@ export let groups: IGroupRepo;
export let devices: IDeviceRepo;
export async function initRepos() {
const repos = await LowStorage.init();
const repos = await LowStorage.init();
users = repos.users;
groups = repos.groups;
devices = repos.devices;
users = repos.users;
groups = repos.groups;
devices = repos.devices;
}

View File

@ -2,9 +2,9 @@ import type { New, Updated } from '../types';
import type { Device, DeviceError } from '../types/device';
export interface IDeviceRepo {
getAll(): Promise<Device[]>;
getById(id: string): Promise<Device | undefined>;
create(group: New<Device>): Promise<DeviceError | undefined>;
update(group: Updated<Device>): Promise<DeviceError | undefined>;
delete(groupId: string): Promise<DeviceError | undefined>;
getAll(): Promise<Device[]>;
getById(id: string): Promise<Device | undefined>;
create(group: New<Device>): Promise<DeviceError | undefined>;
update(group: Updated<Device>): Promise<DeviceError | undefined>;
delete(groupId: string): Promise<DeviceError | undefined>;
}

View File

@ -2,10 +2,10 @@ import type { New, Updated } from '../types';
import type { Group, GroupError } from '../types/group';
export interface IGroupRepo {
getAll(): Promise<Group[]>;
getById(id: string): Promise<Group | undefined>;
create(group: New<Group>): Promise<GroupError | undefined>;
update(group: Updated<Group>): Promise<GroupError | undefined>;
delete(groupId: string): Promise<GroupError | undefined>;
countUsers(groupId: string): Promise<number>;
getAll(): Promise<Group[]>;
getById(id: string): Promise<Group | undefined>;
create(group: New<Group>): Promise<GroupError | undefined>;
update(group: Updated<Group>): Promise<GroupError | undefined>;
delete(groupId: string): Promise<GroupError | undefined>;
countUsers(groupId: string): Promise<number>;
}

View File

@ -2,28 +2,28 @@ import { JSONFilePreset } from 'lowdb/node';
import type { Device } from '../../types/device';
import type { Group } from '../../types/group';
import type { User } from '../../types/user';
import { LowUserRepo } from './userRepo';
import { LowGroupRepo } from './groupRepo';
import { LowDeviceRepo } from './deviceRepo';
import { LowGroupRepo } from './groupRepo';
import { LowUserRepo } from './userRepo';
const db = await JSONFilePreset<LowStorage.LowData>('./data/db.json', {
users: [],
groups: [],
devices: [],
users: [],
groups: [],
devices: [],
});
export namespace LowStorage {
export type LowData = {
users: User[];
groups: Group[];
devices: Device[];
};
export type LowData = {
users: User[];
groups: Group[];
devices: Device[];
};
export async function init() {
return {
users: new LowUserRepo(db),
groups: new LowGroupRepo(db),
devices: new LowDeviceRepo(db),
};
}
export async function init() {
return {
users: new LowUserRepo(db),
groups: new LowGroupRepo(db),
devices: new LowDeviceRepo(db),
};
}
}

View File

@ -1,76 +1,76 @@
import type { IDeviceRepo } from '../deviceRepo';
import type { Low } from 'lowdb';
import { nanoid } from 'nanoid';
import { type New, type Updated } from '../../types';
import { type Device, type DeviceError, DeviceErrors } from '../../types/device';
import { nanoid } from 'nanoid';
import type { IDeviceRepo } from '../deviceRepo';
import type { LowStorage } from './_init';
export class LowDeviceRepo implements IDeviceRepo {
private readonly db;
private readonly db;
constructor(db: Low<LowStorage.LowData>) {
this.db = db;
}
constructor(db: Low<LowStorage.LowData>) {
this.db = db;
}
async getAll(): Promise<Device[]> {
return this.db.data.devices;
}
async getAll(): Promise<Device[]> {
return this.db.data.devices;
}
async getById(id: string): Promise<Device | undefined> {
return this.db.data.devices.find((d) => d.id === id);
}
async getById(id: string): Promise<Device | undefined> {
return this.db.data.devices.find((d) => d.id === id);
}
async create(device: New<Device>): Promise<DeviceError | undefined> {
if (this.db.data.devices.find((d) => d.name === device.name)) {
return DeviceErrors.DUPLICATE_NAME;
}
async create(device: New<Device>): Promise<DeviceError | undefined> {
if (this.db.data.devices.find((d) => d.name === device.name)) {
return DeviceErrors.DUPLICATE_NAME;
}
await this.db.update(({ devices }) => {
devices.push({ id: nanoid(), ...device });
});
await this.db.update(({ devices }) => {
devices.push({ id: nanoid(), ...device });
});
return undefined;
}
return undefined;
}
async update(device: Updated<Device>): Promise<DeviceError | undefined> {
if (this.db.data.devices.find((d) => d.name === device.name && d.id !== device.id)) {
return DeviceErrors.DUPLICATE_NAME;
}
async update(device: Updated<Device>): Promise<DeviceError | undefined> {
if (this.db.data.devices.find((d) => d.name === device.name && d.id !== device.id)) {
return DeviceErrors.DUPLICATE_NAME;
}
let found = false;
await this.db.update(({ devices }) => {
const existingDevice = devices.find((d) => d.id === device.id);
if (!existingDevice) return;
let found = false;
await this.db.update(({ devices }) => {
const existingDevice = devices.find((d) => d.id === device.id);
if (!existingDevice) return;
Object.assign(existingDevice, device);
found = true;
});
Object.assign(existingDevice, device);
found = true;
});
return found ? undefined : DeviceErrors.NOT_FOUND;
}
return found ? undefined : DeviceErrors.NOT_FOUND;
}
async delete(deviceId: string): Promise<DeviceError | undefined> {
let found = false;
async delete(deviceId: string): Promise<DeviceError | undefined> {
let found = false;
this.db.data.devices = this.db.data.devices.filter((d) => {
if (d.id === deviceId) {
found = true;
return false;
}
return true;
});
this.db.data.devices = this.db.data.devices.filter((d) => {
if (d.id === deviceId) {
found = true;
return false;
}
return true;
});
if (found) {
this.db.data.users.forEach((u) => {
u.devices = u.devices.filter((d) => d !== deviceId);
});
this.db.data.groups.forEach((g) => {
g.devices = g.devices.filter((d) => d !== deviceId);
});
if (found) {
this.db.data.users.forEach((u) => {
u.devices = u.devices.filter((d) => d !== deviceId);
});
this.db.data.groups.forEach((g) => {
g.devices = g.devices.filter((d) => d !== deviceId);
});
await this.db.write();
}
await this.db.write();
}
return found ? undefined : DeviceErrors.NOT_FOUND;
}
return found ? undefined : DeviceErrors.NOT_FOUND;
}
}

View File

@ -1,86 +1,86 @@
import type { IGroupRepo } from '../groupRepo';
import type { Low } from 'lowdb';
import { nanoid } from 'nanoid';
import { type New, type Updated } from '../../types';
import { type Group, type GroupError, GroupErrors } from '../../types/group';
import { nanoid } from 'nanoid';
import type { IGroupRepo } from '../groupRepo';
import type { LowStorage } from './_init';
export class LowGroupRepo implements IGroupRepo {
private readonly db;
private readonly db;
constructor(db: Low<LowStorage.LowData>) {
this.db = db;
}
constructor(db: Low<LowStorage.LowData>) {
this.db = db;
}
async getAll(): Promise<Group[]> {
return this.db.data.groups;
}
async getAll(): Promise<Group[]> {
return this.db.data.groups;
}
async getById(id: string): Promise<Group | undefined> {
return this.db.data.groups.find((g) => g.id === id);
}
async getById(id: string): Promise<Group | undefined> {
return this.db.data.groups.find((g) => g.id === id);
}
async create(group: New<Group>): Promise<GroupError | undefined> {
if (this.db.data.groups.find((g) => g.name === group.name)) {
return GroupErrors.DUPLICATE_NAME;
}
async create(group: New<Group>): Promise<GroupError | undefined> {
if (this.db.data.groups.find((g) => g.name === group.name)) {
return GroupErrors.DUPLICATE_NAME;
}
for (const deviceId of group.devices) {
if (!this.db.data.devices.some((d) => d.id === deviceId)) {
return GroupErrors.UNKNOWN_DEVICE;
}
}
for (const deviceId of group.devices) {
if (!this.db.data.devices.some((d) => d.id === deviceId)) {
return GroupErrors.UNKNOWN_DEVICE;
}
}
await this.db.update(({ groups }) => {
groups.push({ id: nanoid(), ...group });
});
await this.db.update(({ groups }) => {
groups.push({ id: nanoid(), ...group });
});
return undefined;
}
return undefined;
}
async update(group: Updated<Group>): Promise<GroupError | undefined> {
if (this.db.data.groups.find((g) => g.name === group.name && g.id !== group.id)) {
return GroupErrors.DUPLICATE_NAME;
}
async update(group: Updated<Group>): Promise<GroupError | undefined> {
if (this.db.data.groups.find((g) => g.name === group.name && g.id !== group.id)) {
return GroupErrors.DUPLICATE_NAME;
}
for (const deviceId of group.devices ?? []) {
if (!this.db.data.devices.some((d) => d.id === deviceId)) {
return GroupErrors.UNKNOWN_DEVICE;
}
}
for (const deviceId of group.devices ?? []) {
if (!this.db.data.devices.some((d) => d.id === deviceId)) {
return GroupErrors.UNKNOWN_DEVICE;
}
}
let found = false;
await this.db.update(({ groups }) => {
const existingGroup = groups.find((g) => g.id === group.id);
if (!existingGroup) return;
let found = false;
await this.db.update(({ groups }) => {
const existingGroup = groups.find((g) => g.id === group.id);
if (!existingGroup) return;
Object.assign(existingGroup, group);
found = true;
});
Object.assign(existingGroup, group);
found = true;
});
return found ? undefined : GroupErrors.NOT_FOUND;
}
return found ? undefined : GroupErrors.NOT_FOUND;
}
async delete(groupId: string): Promise<GroupError | undefined> {
let found = false;
async delete(groupId: string): Promise<GroupError | undefined> {
let found = false;
this.db.data.groups = this.db.data.groups.filter((g) => {
if (g.id === groupId) {
found = true;
return false;
}
return true;
});
this.db.data.groups = this.db.data.groups.filter((g) => {
if (g.id === groupId) {
found = true;
return false;
}
return true;
});
if (found) {
this.db.data.users.forEach((u) => (u.groups = u.groups.filter((gid) => gid != groupId)));
await this.db.write();
}
if (found) {
this.db.data.users.forEach((u) => (u.groups = u.groups.filter((gid) => gid != groupId)));
await this.db.write();
}
return found ? undefined : GroupErrors.NOT_FOUND;
}
return found ? undefined : GroupErrors.NOT_FOUND;
}
async countUsers(groupId: string): Promise<number> {
return this.db.data.users.filter((u) => u.groups.includes(groupId)).length;
}
async countUsers(groupId: string): Promise<number> {
return this.db.data.users.filter((u) => u.groups.includes(groupId)).length;
}
}

View File

@ -1,113 +1,113 @@
import type { Low } from 'lowdb';
import { nanoid } from 'nanoid';
import { type New, type Updated } from '../../types';
import { UserErrors, type User } from '../../types/user';
import type { IUserRepo } from '../userRepo';
import { nanoid } from 'nanoid';
import type { LowStorage } from './_init';
export class LowUserRepo implements IUserRepo {
private readonly db;
private readonly db;
constructor(db: Low<LowStorage.LowData>) {
this.db = db;
}
constructor(db: Low<LowStorage.LowData>) {
this.db = db;
}
async any() {
return this.db.data.users[0] != undefined;
}
async any() {
return this.db.data.users[0] != undefined;
}
async getAll() {
return this.db.data.users;
}
async getAll() {
return this.db.data.users;
}
async getById(id: string) {
return this.db.data.users.find((u) => u.id == id);
}
async getById(id: string) {
return this.db.data.users.find((u) => u.id == id);
}
async getByName(name: string) {
return this.db.data.users.find((u) => u.name == name);
}
async getByName(name: string) {
return this.db.data.users.find((u) => u.name == name);
}
async create(user: New<User>) {
if (!this.db.data.users.find((u) => u.name == user.name)) {
return UserErrors.DUPLICATE_NAME;
}
async create(user: New<User>) {
if (!this.db.data.users.find((u) => u.name == user.name)) {
return UserErrors.DUPLICATE_NAME;
}
for (let id of user.devices) {
if (!this.db.data.devices.some((d) => d.id == id)) {
return UserErrors.UNKNOWN_DEVICE;
}
}
for (let id of user.devices) {
if (!this.db.data.devices.some((d) => d.id == id)) {
return UserErrors.UNKNOWN_DEVICE;
}
}
for (let id of user.groups) {
if (!this.db.data.groups.some((g) => g.id == id)) {
return UserErrors.UNKNOWN_GROUP;
}
}
for (let id of user.groups) {
if (!this.db.data.groups.some((g) => g.id == id)) {
return UserErrors.UNKNOWN_GROUP;
}
}
await this.db.update(({ users }) => {
users.push({ id: nanoid(), ...user });
});
}
await this.db.update(({ users }) => {
users.push({ id: nanoid(), ...user });
});
}
async update(user: Updated<User>) {
if (this.db.data.users.find((u) => u.name == user.name && u.id != user.id)) {
return UserErrors.DUPLICATE_NAME;
}
async update(user: Updated<User>) {
if (this.db.data.users.find((u) => u.name == user.name && u.id != user.id)) {
return UserErrors.DUPLICATE_NAME;
}
for (let id of user.devices ?? []) {
if (!this.db.data.devices.some((d) => d.id == id)) {
return UserErrors.UNKNOWN_DEVICE;
}
}
for (let id of user.devices ?? []) {
if (!this.db.data.devices.some((d) => d.id == id)) {
return UserErrors.UNKNOWN_DEVICE;
}
}
for (let id of user.groups ?? []) {
if (!this.db.data.groups.some((g) => g.id == id)) {
return UserErrors.UNKNOWN_GROUP;
}
}
for (let id of user.groups ?? []) {
if (!this.db.data.groups.some((g) => g.id == id)) {
return UserErrors.UNKNOWN_GROUP;
}
}
let found = false;
await this.db.update(({ users }) => {
let existing = users.find((u) => u.id == user.id);
if (!existing) return;
let found = false;
await this.db.update(({ users }) => {
let existing = users.find((u) => u.id == user.id);
if (!existing) return;
Object.assign(existing, user);
found = true;
});
Object.assign(existing, user);
found = true;
});
return found ? undefined : UserErrors.NOT_FOUND;
}
return found ? undefined : UserErrors.NOT_FOUND;
}
async fetchDevices(userId: string) {
const user = this.db.data.users.find((u) => u.id === userId)!;
async fetchDevices(userId: string) {
const user = this.db.data.users.find((u) => u.id === userId)!;
if (user.admin) return this.db.data.devices;
if (user.admin) return this.db.data.devices;
const userDevices = this.db.data.devices.filter((d) => user.devices.includes(d.id));
const userGroups = this.db.data.groups.filter((g) => user.groups.includes(g.id));
const groupDevices = userGroups.flatMap((g) =>
this.db.data.devices.filter((d) => g.devices.includes(d.id)),
);
const userDevices = this.db.data.devices.filter((d) => user.devices.includes(d.id));
const userGroups = this.db.data.groups.filter((g) => user.groups.includes(g.id));
const groupDevices = userGroups.flatMap((g) =>
this.db.data.devices.filter((d) => g.devices.includes(d.id)),
);
// concat and dedupe
return [...new Set([...userDevices, ...groupDevices])];
}
// concat and dedupe
return [...new Set([...userDevices, ...groupDevices])];
}
async delete(userId: string) {
let found = false;
async delete(userId: string) {
let found = false;
this.db.data.users = this.db.data.users.filter((u) => {
if (u.id == userId) {
found = true;
return false;
}
this.db.data.users = this.db.data.users.filter((u) => {
if (u.id == userId) {
found = true;
return false;
}
return true;
});
return true;
});
await this.db.write();
await this.db.write();
return found ? undefined : UserErrors.NOT_FOUND;
}
return found ? undefined : UserErrors.NOT_FOUND;
}
}

View File

@ -3,12 +3,12 @@ import type { Device } from '../types/device';
import type { User, UserError } from '../types/user';
export interface IUserRepo {
any(): Promise<boolean>;
getAll(): Promise<User[]>;
getById(id: string): Promise<User | undefined>;
getByName(name: string): Promise<User | undefined>;
fetchDevices(userId: string): Promise<Device[]>;
create(user: New<User>): Promise<UserError | undefined>;
update(user: Updated<User>): Promise<UserError | undefined>;
delete(userId: string): Promise<UserError | undefined>;
any(): Promise<boolean>;
getAll(): Promise<User[]>;
getById(id: string): Promise<User | undefined>;
getByName(name: string): Promise<User | undefined>;
fetchDevices(userId: string): Promise<Device[]>;
create(user: New<User>): Promise<UserError | undefined>;
update(user: Updated<User>): Promise<UserError | undefined>;
delete(userId: string): Promise<UserError | undefined>;
}

View File

@ -1,23 +1,23 @@
import { AppError } from '.';
export type Device = {
id: string;
name: string;
mac: string;
broadcast: string;
port: number;
packets: number;
id: string;
name: string;
mac: string;
broadcast: string;
port: number;
packets: number;
};
export class DeviceError extends AppError {
constructor(message: string, status: number) {
super(message, status);
this.name = 'DeviceError';
Object.setPrototypeOf(this, DeviceError.prototype);
}
constructor(message: string, status: number) {
super(message, status);
this.name = 'DeviceError';
Object.setPrototypeOf(this, DeviceError.prototype);
}
}
export namespace DeviceErrors {
export const NOT_FOUND = new DeviceError('Group not found.', 404);
export const DUPLICATE_NAME = new DeviceError('Device with this name already exists.', 409);
export const NOT_FOUND = new DeviceError('Group not found.', 404);
export const DUPLICATE_NAME = new DeviceError('Device with this name already exists.', 409);
}

View File

@ -1,24 +1,24 @@
import { AppError } from '.';
export type Group = {
id: string;
name: string;
devices: string[];
id: string;
name: string;
devices: string[];
};
export class GroupError extends AppError {
constructor(message: string, status: number) {
super(message, status);
this.name = 'GroupError';
Object.setPrototypeOf(this, GroupError.prototype);
}
constructor(message: string, status: number) {
super(message, status);
this.name = 'GroupError';
Object.setPrototypeOf(this, GroupError.prototype);
}
}
export namespace GroupErrors {
export const NOT_FOUND = new GroupError('Group not found.', 404);
export const DUPLICATE_NAME = new GroupError('Group with this name already exists.', 409);
export const UNKNOWN_DEVICE = new GroupError(
'One or more of the selected devices do not exist.',
400,
);
export const NOT_FOUND = new GroupError('Group not found.', 404);
export const DUPLICATE_NAME = new GroupError('Group with this name already exists.', 409);
export const UNKNOWN_DEVICE = new GroupError(
'One or more of the selected devices do not exist.',
400,
);
}

View File

@ -2,36 +2,36 @@ import { fail } from '@sveltejs/kit';
/** @deprecated unused for now - keeping around just in case but should be removed someday */
export class Result<TOk, TErr extends Error> {
public readonly err;
private readonly res;
public readonly err;
private readonly res;
constructor(res?: TOk, err?: TErr) {
this.res = res;
this.err = err;
}
constructor(res?: TOk, err?: TErr) {
this.res = res;
this.err = err;
}
public unwrap(): TOk {
if (this.err) {
console.error('Tried to unwrap a Result that contained an error');
throw this.err;
}
public unwrap(): TOk {
if (this.err) {
console.error('Tried to unwrap a Result that contained an error');
throw this.err;
}
return this.res!;
}
return this.res!;
}
}
export class AppError extends Error {
public readonly status: number;
constructor(message: string, status: number) {
super(message);
this.name = 'AppError';
this.status = status;
Object.setPrototypeOf(this, AppError.prototype);
}
public readonly status: number;
constructor(message: string, status: number) {
super(message);
this.name = 'AppError';
this.status = status;
Object.setPrototypeOf(this, AppError.prototype);
}
public toFail() {
return fail(this.status, { error: this.message });
}
public toFail() {
return fail(this.status, { error: this.message });
}
}
export type New<T> = Omit<T, 'id'>;

View File

@ -1,39 +1,39 @@
import { AppError } from '.';
export type User = {
id: string;
name: string;
password: string;
admin: boolean;
groups: string[];
devices: string[];
id: string;
name: string;
password: string;
admin: boolean;
groups: string[];
devices: string[];
};
export type PublicUser = Omit<User, 'password'>;
export function toPublicUser(user: User): PublicUser {
const clonedUser = structuredClone(user) as Partial<User>;
delete clonedUser.password;
return clonedUser as PublicUser;
const clonedUser = structuredClone(user) as Partial<User>;
delete clonedUser.password;
return clonedUser as PublicUser;
}
export class UserError extends AppError {
constructor(message: string, status: number) {
super(message, status);
this.name = 'UserError';
Object.setPrototypeOf(this, UserError.prototype);
}
constructor(message: string, status: number) {
super(message, status);
this.name = 'UserError';
Object.setPrototypeOf(this, UserError.prototype);
}
}
export namespace UserErrors {
export const NOT_FOUND = new UserError('User not found.', 404);
export const DUPLICATE_NAME = new UserError('User with this username already exists.', 409);
export const UNKNOWN_GROUP = new UserError(
'One or more of the selected groups do not exist.',
400,
);
export const UNKNOWN_DEVICE = new UserError(
'One or more of the selected devices do not exist.',
400,
);
export const NOT_FOUND = new UserError('User not found.', 404);
export const DUPLICATE_NAME = new UserError('User with this username already exists.', 409);
export const UNKNOWN_GROUP = new UserError(
'One or more of the selected groups do not exist.',
400,
);
export const UNKNOWN_DEVICE = new UserError(
'One or more of the selected devices do not exist.',
400,
);
}

View File

@ -2,50 +2,50 @@ import { redirect } from '@sveltejs/kit';
import type { User } from './db/types/user';
export class Guard {
private readonly user?: User;
private readonly user?: User;
private authRequired = false;
private adminRequired = false;
private authRequired = false;
private adminRequired = false;
constructor(user?: User, options?: { authRequired?: boolean; adminRequired?: boolean }) {
this.user = user;
this.authRequired = options?.authRequired ?? false;
this.adminRequired = options?.adminRequired ?? false;
}
constructor(user?: User, options?: { authRequired?: boolean; adminRequired?: boolean }) {
this.user = user;
this.authRequired = options?.authRequired ?? false;
this.adminRequired = options?.adminRequired ?? false;
}
public requiresAuth() {
return new Guard(this.user, { authRequired: true });
}
public requiresAuth() {
return new Guard(this.user, { authRequired: true });
}
public requiresAdmin() {
return new Guard(this.user, { authRequired: true, adminRequired: true });
}
public requiresAdmin() {
return new Guard(this.user, { authRequired: true, adminRequired: true });
}
public orRedirects() {
if (this.authRequired && !this.user) {
redirect(302, '/login');
}
public orRedirects() {
if (this.authRequired && !this.user) {
redirect(302, '/login');
}
if (this.adminRequired && !this.user?.admin) {
redirect(302, '/dash');
}
if (this.adminRequired && !this.user?.admin) {
redirect(302, '/dash');
}
return this;
}
return this;
}
public isFailed() {
if (this.authRequired && !this.user) {
return true;
}
public isFailed() {
if (this.authRequired && !this.user) {
return true;
}
if (this.adminRequired && !this.user?.admin) {
return true;
}
if (this.adminRequired && !this.user?.admin) {
return true;
}
return false;
}
return false;
}
public getUser() {
return this.user!;
}
public getUser() {
return this.user!;
}
}

View File

@ -2,29 +2,29 @@ import { nanoid } from 'nanoid';
import { users } from './db';
type SessionData = {
userId: string;
userAgent: string;
userId: string;
userAgent: string;
};
const sessions: Map<string, SessionData> = new Map();
export function createSession(data: SessionData) {
const token = nanoid();
sessions.set(token, data);
setTimeout(() => sessions.delete(token), 1000 * 60 * 60 * 24);
return token;
const token = nanoid();
sessions.set(token, data);
setTimeout(() => sessions.delete(token), 1000 * 60 * 60 * 24);
return token;
}
export async function getUserFromSession(sessionId?: string) {
if (!sessionId) return undefined;
if (!sessionId) return undefined;
const data = sessions.get(sessionId);
if (!data) return undefined;
const data = sessions.get(sessionId);
if (!data) return undefined;
return await users.getById(data.userId);
return await users.getById(data.userId);
}
export function deleteSession(sessionId?: string) {
if (!sessionId) return;
sessions.delete(sessionId);
if (!sessionId) return;
sessions.delete(sessionId);
}

View File

@ -1,34 +1,36 @@
<script>
import { Checkbox, Label } from 'bits-ui';
import IconCheck from '~icons/tabler/check';
import { Checkbox, Label } from 'bits-ui';
import IconCheck from '~icons/tabler/check';
let {
name,
label,
description = null,
class: extraClasses = '',
checked = $bindable(),
...others
} = $props();
let {
name,
label,
description = null,
class: extraClasses = '',
checked = $bindable(),
...others
} = $props();
</script>
<div class="text-sm text-neutral-100">
<div class="flex items-center gap-4 {description ? 'mb-2' : 'mb-6'}">
<Label.Root for={name} class="block uppercase cursor-pointer">{label}</Label.Root>
<Checkbox.Root id={name} {name} bind:checked {...others}>
{#snippet children({ checked })}
<div
class="p-1 border border-neutral-600 rounded-lg bg-neutral-950 hover:bg-neutral-800 transition-all
<div class="flex items-center gap-4 {description ? 'mb-2' : 'mb-6'}">
<Label.Root for={name} class="block uppercase cursor-pointer">{label}</Label.Root>
<Checkbox.Root id={name} {name} bind:checked {...others}>
{#snippet children({ checked })}
<div
class="p-1 border border-neutral-600 rounded-lg bg-neutral-950 hover:bg-neutral-800 transition-all
duration-300 ease-in-out cursor-pointer"
>
<IconCheck
class="transition-all duration-300 ease-in-out {checked ? 'opacity-100' : 'opacity-0'} test"
/>
</div>
{/snippet}
</Checkbox.Root>
</div>
{#if description}
<p class="text-sm text-neutral-400 dark:text-neutral-500 mb-6">{description}</p>
{/if}
>
<IconCheck
class="transition-all duration-300 ease-in-out {checked
? 'opacity-100'
: 'opacity-0'} test"
/>
</div>
{/snippet}
</Checkbox.Root>
</div>
{#if description}
<p class="text-sm text-neutral-400 dark:text-neutral-500 mb-6">{description}</p>
{/if}
</div>

View File

@ -1,139 +1,139 @@
<script lang="ts">
import { Combobox, Label } from 'bits-ui';
import IconCaretDown from '~icons/tabler/caret-down';
import IconCaretUp from '~icons/tabler/caret-up';
import IconCheck from '~icons/tabler/check';
import IconSelector from '~icons/tabler/selector';
import { slideFade } from '../transitions/slideFade';
import { Combobox, Label } from 'bits-ui';
import IconCaretDown from '~icons/tabler/caret-down';
import IconCaretUp from '~icons/tabler/caret-up';
import IconCheck from '~icons/tabler/check';
import IconSelector from '~icons/tabler/selector';
import { slideFade } from '../transitions/slideFade';
let {
name,
label,
description = '',
data,
class: extraClasses = '',
}: {
name: string;
label: string;
description?: string;
data: {
value: string;
name: string;
selected: boolean;
}[];
class?: string;
} = $props();
let {
name,
label,
description = '',
data,
class: extraClasses = '',
}: {
name: string;
label: string;
description?: string;
data: {
value: string;
name: string;
selected: boolean;
}[];
class?: string;
} = $props();
let searchTerm = $state('');
let searchFiltered = $derived(data.filter((e) => e.name.toLowerCase().startsWith(searchTerm)));
let searchTerm = $state('');
let searchFiltered = $derived(data.filter((e) => e.name.toLowerCase().startsWith(searchTerm)));
let value = $state(data.filter((d) => d.selected).map((d) => d.value));
let inputRef: HTMLInputElement | null = $state(null);
let value = $state(data.filter((d) => d.selected).map((d) => d.value));
let inputRef: HTMLInputElement | null = $state(null);
</script>
<div class="text-sm text-neutral-100">
<Label.Root
for={name}
onclick={() => inputRef?.focus()}
class="block uppercase mb-2 cursor-pointer"
>
{label}
</Label.Root>
<Label.Root
for={name}
onclick={() => inputRef?.focus()}
class="block uppercase mb-2 cursor-pointer"
>
{label}
</Label.Root>
<Combobox.Root
type="multiple"
{name}
bind:value
onOpenChange={(val) => {
if (!val) searchTerm = '';
}}
>
<div
class="flex border border-neutral-600 shadow text-sm rounded-full {description
? 'mb-2'
: 'mb-6'}"
>
<div class="relative w-full">
<Combobox.Input
bind:ref={inputRef}
placeholder="{value.length} selected | Type to search..."
oninput={(e) => (searchTerm = e.currentTarget.value.toLowerCase())}
class="bg-neutral-950 px-4 py-2 rounded-l-full
<Combobox.Root
type="multiple"
{name}
bind:value
onOpenChange={(val) => {
if (!val) searchTerm = '';
}}
>
<div
class="flex border border-neutral-600 shadow text-sm rounded-full {description
? 'mb-2'
: 'mb-6'}"
>
<div class="relative w-full">
<Combobox.Input
bind:ref={inputRef}
placeholder="{value.length} selected | Type to search..."
oninput={(e) => (searchTerm = e.currentTarget.value.toLowerCase())}
class="bg-neutral-950 px-4 py-2 rounded-l-full
focus:ring-indigo-500 focus:border-indigo-500 {extraClasses} z-1"
/>
<!-- <Button.Root type="button" class="{searchTerm == '' ? 'hidden' : ''} absolute text-neutral-500 right-3 top-1/2 -translate-y-1/2">
/>
<!-- <Button.Root type="button" class="{searchTerm == '' ? 'hidden' : ''} absolute text-neutral-500 right-3 top-1/2 -translate-y-1/2">
<IconX/>
</Button.Root> -->
</div>
<Combobox.Trigger
class="border-l border-neutral-600 pl-4 pr-3 py-2 rounded-r-full
</div>
<Combobox.Trigger
class="border-l border-neutral-600 pl-4 pr-3 py-2 rounded-r-full
cursor-pointer bg-neutral-800 hover:bg-neutral-700 transition-all duration-300 ease-in-out"
>
<div class="flex items-center gap-2">
Select
<IconSelector />
</div>
</Combobox.Trigger>
</div>
<Combobox.Portal>
<Combobox.Content
forceMount
class="flex flex-col mt-2 min-w-50 sm:min-w-70 max-h-70 shadow-lg
>
<div class="flex items-center gap-2">
Select
<IconSelector />
</div>
</Combobox.Trigger>
</div>
<Combobox.Portal>
<Combobox.Content
forceMount
class="flex flex-col mt-2 min-w-50 sm:min-w-70 max-h-70 shadow-lg
border border-neutral-600 rounded-2xl bg-neutral-950 p-2 text-sm text-neutral-100"
>
{#snippet child({ wrapperProps, props, open })}
{#if open}
<div {...wrapperProps}>
<div {...props} transition:slideFade>
<Combobox.ScrollUpButton class="flex justify-center relative">
<div
class="absolute top-full inset-x-0 h-5 z-50 pointer-events-none
>
{#snippet child({ wrapperProps, props, open })}
{#if open}
<div {...wrapperProps}>
<div {...props} transition:slideFade>
<Combobox.ScrollUpButton class="flex justify-center relative">
<div
class="absolute top-full inset-x-0 h-5 z-50 pointer-events-none
bg-gradient-to-b from-neutral-950 to-transparent"
></div>
<IconCaretUp />
</Combobox.ScrollUpButton>
<Combobox.Viewport>
{#if searchFiltered.length > 0}
{#each searchFiltered as el}
<Combobox.Item
label={searchTerm}
value={el.value}
class="flex items-center justify-between gap-4 px-4 py-2
></div>
<IconCaretUp />
</Combobox.ScrollUpButton>
<Combobox.Viewport>
{#if searchFiltered.length > 0}
{#each searchFiltered as el}
<Combobox.Item
label={searchTerm}
value={el.value}
class="flex items-center justify-between gap-4 px-4 py-2
data-highlighted:bg-neutral-800 rounded-xl
cursor-pointer transition-all duration-150 ease-in-out"
>
{#snippet children({ selected })}
{el.name}
<IconCheck
class="transition-all duration-150 ease-in-out {selected
? 'opacity-100'
: 'opacity-0'}"
/>
{/snippet}
</Combobox.Item>
{/each}
{:else}
<p class="px-4 py-2 text-neutral-500 cursor-not-allowed">
No results found. Try another term.
</p>
{/if}
</Combobox.Viewport>
<Combobox.ScrollDownButton class="flex justify-center relative">
<IconCaretDown />
<div
class="absolute bottom-full inset-x-0 h-5 z-50 pointer-events-none
bg-gradient-to-t from-neutral-950 to-transparent"
></div>
</Combobox.ScrollDownButton>
</div>
</div>
{/if}
{/snippet}
</Combobox.Content>
</Combobox.Portal>
</Combobox.Root>
>
{#snippet children({ selected })}
{el.name}
<IconCheck
class="transition-all duration-150 ease-in-out {selected
? 'opacity-100'
: 'opacity-0'}"
/>
{/snippet}
</Combobox.Item>
{/each}
{:else}
<p class="px-4 py-2 text-neutral-500 cursor-not-allowed">
No results found. Try another term.
</p>
{/if}
</Combobox.Viewport>
<Combobox.ScrollDownButton class="flex justify-center relative">
<IconCaretDown />
<div
class="absolute bottom-full inset-x-0 h-5 z-50 pointer-events-none
bg-gradient-to-t from-neutral-950 to-transparent"
></div>
</Combobox.ScrollDownButton>
</div>
</div>
{/if}
{/snippet}
</Combobox.Content>
</Combobox.Portal>
</Combobox.Root>
{#if description}
<p class="text-sm text-neutral-400 dark:text-neutral-500 mb-6">{description}</p>
{/if}
{#if description}
<p class="text-sm text-neutral-400 dark:text-neutral-500 mb-6">{description}</p>
{/if}
</div>

View File

@ -1,29 +1,29 @@
<script>
import { Label } from 'bits-ui';
import { Label } from 'bits-ui';
let {
name,
label,
description = null,
class: extraClasses = '',
value = $bindable(),
...others
} = $props();
let {
name,
label,
description = null,
class: extraClasses = '',
value = $bindable(),
...others
} = $props();
</script>
<div class="text-sm text-neutral-100">
<Label.Root for={name} class="block uppercase mb-2 cursor-pointer">{label}</Label.Root>
<input
id={name}
{name}
bind:value
type="text"
{...others}
class="border border-neutral-600 shadow bg-neutral-950
<Label.Root for={name} class="block uppercase mb-2 cursor-pointer">{label}</Label.Root>
<input
id={name}
{name}
bind:value
type="text"
{...others}
class="border border-neutral-600 shadow bg-neutral-950
px-4 py-2 text-sm focus:ring-indigo-500 focus:border-indigo-500 rounded-full
{extraClasses} {description ? 'mb-2' : 'mb-6'}"
/>
{#if description}
<p class="text-sm text-neutral-400 dark:text-neutral-500 mb-6">{description}</p>
{/if}
/>
{#if description}
<p class="text-sm text-neutral-400 dark:text-neutral-500 mb-6">{description}</p>
{/if}
</div>

View File

@ -1,52 +1,52 @@
<script lang="ts">
import { enhance } from '$app/forms';
import { Button } from 'bits-ui';
import IconDeviceFloppy from '~icons/tabler/device-floppy';
import IconTrash from '~icons/tabler/trash';
import IconX from '~icons/tabler/x';
import { enhance } from '$app/forms';
import { Button } from 'bits-ui';
import IconDeviceFloppy from '~icons/tabler/device-floppy';
import IconTrash from '~icons/tabler/trash';
import IconX from '~icons/tabler/x';
let { children, createOnly } = $props();
let { children, createOnly } = $props();
</script>
<div class="w-full sm:px-6 px-3 py-4 max-w-xl mx-auto mb-12">
<form method="POST" action="?/update" use:enhance>
{@render children()}
<form method="POST" action="?/update" use:enhance>
{@render children()}
<div class="flex gap-2 justify-between sm:text-base text-sm">
<div class="flex gap-2">
<Button.Root
type="submit"
class="flex items-center gap-2 text-black cursor-pointer
<div class="flex gap-2 justify-between sm:text-base text-sm">
<div class="flex gap-2">
<Button.Root
type="submit"
class="flex items-center gap-2 text-black cursor-pointer
bg-neutral-100 hover:bg-neutral-400 hover:scale-95 transition-all duration-300 ease-in-out
rounded-full py-2 px-4 border border-neutral-100"
>
<IconDeviceFloppy />
<p>Save</p>
</Button.Root>
>
<IconDeviceFloppy />
<p>Save</p>
</Button.Root>
<Button.Root
type="button"
onclick={() => history.back()}
class="flex items-center gap-2 text-white cursor-pointer
<Button.Root
type="button"
onclick={() => history.back()}
class="flex items-center gap-2 text-white cursor-pointer
bg-neutral-800 hover:bg-neutral-700 hover:scale-95 transition-all duration-300 ease-in-out
rounded-full py-2 px-4 border border-neutral-600"
>
<IconX />
<p>Cancel</p>
</Button.Root>
</div>
>
<IconX />
<p>Cancel</p>
</Button.Root>
</div>
{#if !createOnly}
<Button.Root
formaction="?/delete"
class="flex items-center gap-2 text-white cursor-pointer
{#if !createOnly}
<Button.Root
formaction="?/delete"
class="flex items-center gap-2 text-white cursor-pointer
bg-red-700 hover:bg-red-500 hover:scale-95 transition-all duration-300 ease-in-out
rounded-full py-2 px-4 border border-red-500"
>
<IconTrash />
<p>Delete</p>
</Button.Root>
{/if}
</div>
</form>
>
<IconTrash />
<p>Delete</p>
</Button.Root>
{/if}
</div>
</form>
</div>

View File

@ -1,32 +1,32 @@
<script lang="ts">
import { Button } from 'bits-ui';
import IconPlus from '~icons/tabler/plus';
import { Button } from 'bits-ui';
import IconPlus from '~icons/tabler/plus';
let { createHref = null, msgAdd, children } = $props();
let { createHref = null, msgAdd, children } = $props();
</script>
{#if createHref}
<Button.Root
href={createHref}
class="fixed flex items-center sm:bottom-12 sm:right-12 bottom-6 right-6
<Button.Root
href={createHref}
class="fixed flex items-center sm:bottom-12 sm:right-12 bottom-6 right-6
bg-neutral-100 rounded-full shadow-xl sm:px-6 sm:py-2 p-4
transition-all duration-300 ease-in-out
hover:bg-neutral-300 hover:scale-105"
>
<span class="hidden sm:block">{msgAdd}</span>
<IconPlus class="sm:ml-2" />
</Button.Root>
>
<span class="hidden sm:block">{msgAdd}</span>
<IconPlus class="sm:ml-2" />
</Button.Root>
{/if}
<div class="w-full sm:px-6 px-3 py-4 max-w-3xl mx-auto">
{#if children}
{@render children?.()}
{:else}
<div class="p-4 text-center text-neutral-700">
<p>Nothing here.</p>
{#if createHref}
<p>Get started by clicking "{msgAdd}".</p>
{/if}
</div>
{/if}
{#if children}
{@render children?.()}
{:else}
<div class="p-4 text-center text-neutral-700">
<p>Nothing here.</p>
{#if createHref}
<p>Get started by clicking "{msgAdd}".</p>
{/if}
</div>
{/if}
</div>

View File

@ -8,38 +8,38 @@ import type { TransitionConfig } from 'svelte/transition';
// why? made no sense, opacity changed so fast you couldn't see it... oh well
export function slideFade(
node: Element,
{ delay = 0, duration = 300, easing = cubicOut, axis = 'y' } = {},
node: Element,
{ delay = 0, duration = 300, easing = cubicOut, axis = 'y' } = {},
): TransitionConfig {
const style = getComputedStyle(node);
const style = getComputedStyle(node);
const opacity = +style.opacity;
const opacity = +style.opacity;
const primaryProp = axis === 'y' ? 'height' : 'width';
const primaryVal = parseFloat(style.getPropertyValue(primaryProp));
const primaryProp = axis === 'y' ? 'height' : 'width';
const primaryVal = parseFloat(style.getPropertyValue(primaryProp));
const secondaryProps = axis === 'y' ? ['top', 'bottom'] : ['left', 'right'];
const padStart = parseFloat(style.getPropertyValue(`padding-${secondaryProps[0]}`));
const padEnd = parseFloat(style.getPropertyValue(`padding-${secondaryProps[1]}`));
const marginStart = parseFloat(style.getPropertyValue(`margin-${secondaryProps[0]}`));
const marginEnd = parseFloat(style.getPropertyValue(`margin-${secondaryProps[1]}`));
const borderWidthStart = parseFloat(style.getPropertyValue(`border-${secondaryProps[0]}-width`));
const borderWidthEnd = parseFloat(style.getPropertyValue(`border-${secondaryProps[1]}-width`));
const secondaryProps = axis === 'y' ? ['top', 'bottom'] : ['left', 'right'];
const padStart = parseFloat(style.getPropertyValue(`padding-${secondaryProps[0]}`));
const padEnd = parseFloat(style.getPropertyValue(`padding-${secondaryProps[1]}`));
const marginStart = parseFloat(style.getPropertyValue(`margin-${secondaryProps[0]}`));
const marginEnd = parseFloat(style.getPropertyValue(`margin-${secondaryProps[1]}`));
const borderWidthStart = parseFloat(style.getPropertyValue(`border-${secondaryProps[0]}-width`));
const borderWidthEnd = parseFloat(style.getPropertyValue(`border-${secondaryProps[1]}-width`));
return {
delay,
duration,
easing,
css: (t) =>
'overflow: hidden;' +
`opacity: ${t * opacity};` +
`${primaryProp}: ${t * primaryVal}px;` +
`padding-${secondaryProps[0]}: ${t * padStart}px;` +
`padding-${secondaryProps[1]}: ${t * padEnd}px;` +
`margin-${secondaryProps[0]}: ${t * marginStart}px;` +
`margin-${secondaryProps[1]}: ${t * marginEnd}px;` +
`border-${secondaryProps[0]}-width: ${t * borderWidthStart}px;` +
`border-${secondaryProps[1]}-width: ${t * borderWidthEnd}px;` +
`min-${primaryProp}: 0`,
};
return {
delay,
duration,
easing,
css: (t) =>
'overflow: hidden;' +
`opacity: ${t * opacity};` +
`${primaryProp}: ${t * primaryVal}px;` +
`padding-${secondaryProps[0]}: ${t * padStart}px;` +
`padding-${secondaryProps[1]}: ${t * padEnd}px;` +
`margin-${secondaryProps[0]}: ${t * marginStart}px;` +
`margin-${secondaryProps[1]}: ${t * marginEnd}px;` +
`border-${secondaryProps[0]}-width: ${t * borderWidthStart}px;` +
`border-${secondaryProps[1]}-width: ${t * borderWidthEnd}px;` +
`min-${primaryProp}: 0`,
};
}

View File

@ -1,38 +1,38 @@
<script lang="ts">
import { Button } from 'bits-ui';
import IconChevronRight from '~icons/tabler/chevron-right';
import { slideFade } from '../transitions/slideFade';
import { Button } from 'bits-ui';
import IconChevronRight from '~icons/tabler/chevron-right';
import { slideFade } from '../transitions/slideFade';
let {
children,
label,
expanded = $bindable(false),
renderHidden = false,
class: extraClasses = '',
} = $props();
let {
children,
label,
expanded = $bindable(false),
renderHidden = false,
class: extraClasses = '',
} = $props();
</script>
<div class={extraClasses}>
<Button.Root
type="button"
onclick={() => (expanded = !expanded)}
class="flex items-center gap-2 cursor-pointer text-neutral-500 uppercase text-sm"
>
<IconChevronRight class="{expanded ? 'rotate-90' : ''} transition-all duration-300" />
{label}
</Button.Root>
<Button.Root
type="button"
onclick={() => (expanded = !expanded)}
class="flex items-center gap-2 cursor-pointer text-neutral-500 uppercase text-sm"
>
<IconChevronRight class="{expanded ? 'rotate-90' : ''} transition-all duration-300" />
{label}
</Button.Root>
<!-- a bit hacky, all of that just to keep a smooth slide transition with no side effect -->
<!-- i wish i could just use CSS transitions and display: none -->
<!-- but noooo, CSS won't let you animate height: auto because fuck you that's why -->
{#if expanded}
<div transition:slideFade class="mt-4">
{@render children()}
</div>
{:else if renderHidden}
<!-- keep a hidden render, useful to send form data even if hidden -->
<div class="hidden">
{@render children()}
</div>
{/if}
<!-- a bit hacky, all of that just to keep a smooth slide transition with no side effect -->
<!-- i wish i could just use CSS transitions and display: none -->
<!-- but noooo, CSS won't let you animate height: auto because fuck you that's why -->
{#if expanded}
<div transition:slideFade class="mt-4">
{@render children()}
</div>
{:else if renderHidden}
<!-- keep a hidden render, useful to send form data even if hidden -->
<div class="hidden">
{@render children()}
</div>
{/if}
</div>

View File

@ -1,13 +1,13 @@
<script lang="ts">
let { children, class: className = '' } = $props();
let { children, class: className = '' } = $props();
</script>
<nav class="flex items-center {className}">
<ul
role="menubar"
class="flex items-center w-full sm:w-auto justify-between gap-1 p-1 bg-neutral-950
<ul
role="menubar"
class="flex items-center w-full sm:w-auto justify-between gap-1 p-1 bg-neutral-950
border border-neutral-600 rounded-full"
>
{@render children()}
</ul>
>
{@render children()}
</ul>
</nav>

View File

@ -1,24 +1,24 @@
<script lang="ts">
import { Button } from 'bits-ui';
import { Button } from 'bits-ui';
let { Icon = null, children, active, ...others } = $props();
let { Icon = null, children, active, ...others } = $props();
</script>
<li role="none">
<Button.Root
role="menuitem"
class="flex items-center cursor-pointer px-4 py-1 rounded-full transition-all duration-300 ease-in-out
<Button.Root
role="menuitem"
class="flex items-center cursor-pointer px-4 py-1 rounded-full transition-all duration-300 ease-in-out
{active ? 'bg-neutral-100 text-neutral-900' : 'hover:bg-neutral-600'}"
{...others}
>
{#if Icon}
<Icon
class="block overflow-hidden transition-all duration-300 ease-in-out
{...others}
>
{#if Icon}
<Icon
class="block overflow-hidden transition-all duration-300 ease-in-out
{children ? 'w-0 text-neutral-900' : ''}
{active ? 'w-5 mr-2' : ''}"
/>
{/if}
/>
{/if}
{@render children?.()}
</Button.Root>
{@render children?.()}
</Button.Root>
</li>

View File

@ -1,37 +1,37 @@
<script lang="ts">
import { Button } from 'bits-ui';
import IconEdit from '~icons/tabler/edit';
import IconPlay from '~icons/tabler/player-play';
import { Button } from 'bits-ui';
import IconEdit from '~icons/tabler/edit';
import IconPlay from '~icons/tabler/player-play';
let { title, subtitle, editHref = null, wakePost = null } = $props();
let { title, subtitle, editHref = null, wakePost = null } = $props();
</script>
<div
class="flex gap-10 items-center rounded-full border border-neutral-600 py-3 pl-7 pr-3 bg-neutral-950 shadow"
class="flex gap-10 items-center rounded-full border border-neutral-600 py-3 pl-7 pr-3 bg-neutral-950 shadow"
>
<div class="flex flex-col text-sm">
<p class="text-neutral-300">{title}</p>
<p class="text-neutral-600">{subtitle}</p>
</div>
<div class="flex flex-col text-sm">
<p class="text-neutral-300">{title}</p>
<p class="text-neutral-600">{subtitle}</p>
</div>
<div class="flex gap-2">
{#if editHref}
<Button.Root
class="bg-neutral-800 hover:bg-neutral-700 transition-all duration-300 ease-in-out
<div class="flex gap-2">
{#if editHref}
<Button.Root
class="bg-neutral-800 hover:bg-neutral-700 transition-all duration-300 ease-in-out
border border-neutral-600 rounded-full p-4 text-neutral-100"
href={editHref}
>
<IconEdit />
</Button.Root>
{/if}
href={editHref}
>
<IconEdit />
</Button.Root>
{/if}
{#if wakePost}
<Button.Root
class="bg-emerald-600 hover:bg-emerald-800 transition-all duration-300 ease-in-out
{#if wakePost}
<Button.Root
class="bg-emerald-600 hover:bg-emerald-800 transition-all duration-300 ease-in-out
border border-emerald-500 rounded-full p-4 text-neutral-100 cursor-pointer"
>
<IconPlay />
</Button.Root>
{/if}
</div>
>
<IconPlay />
</Button.Root>
{/if}
</div>
</div>

View File

@ -1,7 +1,7 @@
<script lang="ts">
import '../app.css';
import '../app.css';
let { children } = $props();
let { children } = $props();
</script>
{@render children()}

View File

@ -2,5 +2,5 @@ import { redirect } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async () => {
redirect(302, '/dash');
redirect(302, '/dash');
};

View File

@ -2,9 +2,9 @@ import { toPublicUser } from '$lib/server/db/types/user';
import type { LayoutServerLoad } from './$types';
export const load: LayoutServerLoad = async ({ locals: { guard } }) => {
const user = guard.requiresAuth().orRedirects().getUser();
const user = guard.requiresAuth().orRedirects().getUser();
return {
user: toPublicUser(user),
};
return {
user: toPublicUser(user),
};
};

View File

@ -1,98 +1,98 @@
<script lang="ts">
import { page } from '$app/state';
import { pageTitle } from '$lib/v2/globalStores.js';
import NavBar from '$lib/v2/ui/NavBar.svelte';
import NavBarLink from '$lib/v2/ui/NavBarLink.svelte';
import { Button, DropdownMenu } from 'bits-ui';
import IconChevronDown from '~icons/tabler/chevron-down';
import IconChevronRight from '~icons/tabler/chevron-right';
import IconHome from '~icons/tabler/home';
import IconUsers from '~icons/tabler/users';
import IconUsersGroup from '~icons/tabler/users-group';
import IconDeviceDesktopPin from '~icons/tabler/device-desktop-pin';
import IconLogout from '~icons/tabler/logout';
import { slideFade } from '$lib/v2/transitions/slideFade.js';
import { page } from '$app/state';
import { pageTitle } from '$lib/v2/globalStores.js';
import { slideFade } from '$lib/v2/transitions/slideFade.js';
import NavBar from '$lib/v2/ui/NavBar.svelte';
import NavBarLink from '$lib/v2/ui/NavBarLink.svelte';
import { Button, DropdownMenu } from 'bits-ui';
import IconChevronDown from '~icons/tabler/chevron-down';
import IconChevronRight from '~icons/tabler/chevron-right';
import IconDeviceDesktopPin from '~icons/tabler/device-desktop-pin';
import IconHome from '~icons/tabler/home';
import IconLogout from '~icons/tabler/logout';
import IconUsers from '~icons/tabler/users';
import IconUsersGroup from '~icons/tabler/users-group';
let { data, children } = $props();
let { data, children } = $props();
function isActive(pageName: string) {
return page.route.id?.includes(pageName);
}
function isActive(pageName: string) {
return page.route.id?.includes(pageName);
}
</script>
<svelte:head>
<title>Dashboard - {$pageTitle}</title>
<title>Dashboard - {$pageTitle}</title>
</svelte:head>
<div
class="fixed top-0 left-0 right-0 z-50 flex sm:flex-row flex-col
class="fixed top-0 left-0 right-0 z-50 flex sm:flex-row flex-col
p-3 sm:p-6 pb-6 gap-3 text-sm text-neutral-100 bg-linear-to-b from-neutral-900 via-neutral-900 to-transparent"
>
<NavBar>
<NavBarLink Icon={IconHome} active={isActive('devices')} href="/dash/devices"
>Devices</NavBarLink
>
<NavBarLink Icon={IconUsers} active={isActive('users')} href="/dash/users">Users</NavBarLink>
<NavBarLink Icon={IconUsersGroup} active={isActive('groups')} href="/dash/groups"
>Groups</NavBarLink
>
</NavBar>
<div class="flex grow">
<div
class="flex grow items-center gap-3 text-neutral-100 text-sm sm:text-base font-light shadow"
>
<IconChevronRight />
<p>{$pageTitle}</p>
</div>
<DropdownMenu.Root>
<DropdownMenu.Trigger class="rounded-full bg-neutral-950 border border-neutral-600 p-1">
<Button.Root
class="flex items-center p-1 cursor-pointer rounded-full
<NavBar>
<NavBarLink Icon={IconHome} active={isActive('devices')} href="/dash/devices"
>Devices</NavBarLink
>
<NavBarLink Icon={IconUsers} active={isActive('users')} href="/dash/users">Users</NavBarLink>
<NavBarLink Icon={IconUsersGroup} active={isActive('groups')} href="/dash/groups"
>Groups</NavBarLink
>
</NavBar>
<div class="flex grow">
<div
class="flex grow items-center gap-3 text-neutral-100 text-sm sm:text-base font-light shadow"
>
<IconChevronRight />
<p>{$pageTitle}</p>
</div>
<DropdownMenu.Root>
<DropdownMenu.Trigger class="rounded-full bg-neutral-950 border border-neutral-600 p-1">
<Button.Root
class="flex items-center p-1 cursor-pointer rounded-full
pl-3 pr-2 py-1 gap-2 hover:bg-neutral-700 transition-all duration-300 ease-in-out"
>
<span><span class="hidden md:inline">Signed in as</span> {data.user.name}</span>
<IconChevronDown />
</Button.Root>
</DropdownMenu.Trigger>
<DropdownMenu.Content
forceMount
class="z-1 bg-neutral-950 border border-neutral-600
>
<span><span class="hidden md:inline">Signed in as</span> {data.user.name}</span>
<IconChevronDown />
</Button.Root>
</DropdownMenu.Trigger>
<DropdownMenu.Content
forceMount
class="z-1 bg-neutral-950 border border-neutral-600
m-3 p-2 flex flex-col gap-2 rounded-2xl shadow-lg"
>
{#snippet child({ wrapperProps, props, open })}
{#if open}
<div {...wrapperProps}>
<div {...props} transition:slideFade>
<DropdownMenu.Item>
<a
href="/sessions"
class="px-3 py-2 hover:bg-neutral-700 transition-all duration-300 ease-in-out
>
{#snippet child({ wrapperProps, props, open })}
{#if open}
<div {...wrapperProps}>
<div {...props} transition:slideFade>
<DropdownMenu.Item>
<a
href="/sessions"
class="px-3 py-2 hover:bg-neutral-700 transition-all duration-300 ease-in-out
rounded-lg flex items-center justify-between gap-4"
>
<p>Sessions</p>
<IconDeviceDesktopPin />
</a>
</DropdownMenu.Item>
<DropdownMenu.Item>
<a
data-sveltekit-preload-data="tap"
href="/logout"
class="px-3 py-2 hover:bg-neutral-700 transition-all duration-300 ease-in-out
>
<p>Sessions</p>
<IconDeviceDesktopPin />
</a>
</DropdownMenu.Item>
<DropdownMenu.Item>
<a
data-sveltekit-preload-data="tap"
href="/logout"
class="px-3 py-2 hover:bg-neutral-700 transition-all duration-300 ease-in-out
rounded-lg flex items-center justify-between gap-4"
>
<p>Logout</p>
<IconLogout />
</a>
</DropdownMenu.Item>
</div>
</div>
{/if}
{/snippet}
</DropdownMenu.Content>
</DropdownMenu.Root>
</div>
>
<p>Logout</p>
<IconLogout />
</a>
</DropdownMenu.Item>
</div>
</div>
{/if}
{/snippet}
</DropdownMenu.Content>
</DropdownMenu.Root>
</div>
</div>
<div class="w-full h-svh bg-neutral-900 overflow-y-scroll sm:pt-20 pt-28">
{@render children()}
{@render children()}
</div>

View File

@ -1,6 +1,6 @@
import { redirect, type ServerLoad } from '@sveltejs/kit';
export const load: ServerLoad = async ({ locals: { guard } }) => {
guard.requiresAuth().orRedirects();
redirect(302, '/dash/devices');
guard.requiresAuth().orRedirects();
redirect(302, '/dash/devices');
};

View File

@ -2,8 +2,8 @@ import { users } from '$lib/server/db';
import type { ServerLoad } from '@sveltejs/kit';
export const load: ServerLoad = async ({ locals: { guard } }) => {
const user = guard.requiresAuth().orRedirects().getUser();
return {
devices: await users.fetchDevices(user.id),
};
const user = guard.requiresAuth().orRedirects().getUser();
return {
devices: await users.fetchDevices(user.id),
};
};

View File

@ -1,22 +1,22 @@
<script>
import { pageTitle } from '$lib/v2/globalStores.js';
import ListPage from '$lib/v2/snippets/ListPage.svelte';
import ResCard from '$lib/v2/ui/ResCard.svelte';
import { pageTitle } from '$lib/v2/globalStores.js';
import ListPage from '$lib/v2/snippets/ListPage.svelte';
import ResCard from '$lib/v2/ui/ResCard.svelte';
let { data } = $props();
let { data } = $props();
$pageTitle = 'Listing all devices';
$pageTitle = 'Listing all devices';
</script>
<ListPage createHref={data.user.admin ? '/dash/devices/new' : null} msgAdd="Add Device">
<div class="flex gap-4 flex-wrap justify-center">
{#each data.devices as device}
<ResCard
title={device.name}
subtitle={device.mac}
editHref={data.user.admin ? `/dash/devices/${device.id}` : null}
wakePost={`/dash/devices/${device.id}/wake`}
/>
{/each}
</div>
<div class="flex gap-4 flex-wrap justify-center">
{#each data.devices as device}
<ResCard
title={device.name}
subtitle={device.mac}
editHref={data.user.admin ? `/dash/devices/${device.id}` : null}
wakePost={`/dash/devices/${device.id}/wake`}
/>
{/each}
</div>
</ListPage>

View File

@ -6,91 +6,91 @@ import { wake } from 'wake_on_lan';
import { z } from 'zod';
export const load: ServerLoad = async ({ locals: { guard }, params }) => {
guard.requiresAdmin().orRedirects();
guard.requiresAdmin().orRedirects();
const device = await devices.getById(params.id ?? '');
const device = await devices.getById(params.id ?? '');
if (!device && params.id !== 'new') {
redirect(302, '/dash/devices');
}
if (!device && params.id !== 'new') {
redirect(302, '/dash/devices');
}
return {
device,
};
return {
device,
};
};
export const actions = {
update: async ({ request, params, locals: { guard } }) => {
if (guard.requiresAdmin().isFailed()) return FORBIDDEN;
update: async ({ request, params, locals: { guard } }) => {
if (guard.requiresAdmin().isFailed()) return FORBIDDEN;
const form = await request.formData();
const form = await request.formData();
const schema = z.object({
name: z
.string({ message: 'Name is required.' })
.min(3, { message: 'Name must be at least 3 characters.' })
.max(24, { message: 'Name must be at most 24 characters.' }),
mac: z
.string({ message: 'MAC address is required.' })
.refine((v) => validator.isMACAddress(v), { message: 'Invalid MAC address.' }),
broadcast: z
.string()
.refine((v) => validator.isIP(v), { message: 'Invalid broadcast IP address.' }),
port: z.coerce
.number({ message: 'Port is invalid.' })
.min(1, { message: 'Port must be at least 1.' })
.max(65535, { message: 'Port must be at most 65535.' }),
packets: z.coerce
.number({ message: 'Packets quantity is invalid.' })
.min(1, { message: 'Packets quantity must be at least 1.' })
.max(50, { message: 'Packets quantity must be at most 50.' }),
});
const schema = z.object({
name: z
.string({ message: 'Name is required.' })
.min(3, { message: 'Name must be at least 3 characters.' })
.max(24, { message: 'Name must be at most 24 characters.' }),
mac: z
.string({ message: 'MAC address is required.' })
.refine((v) => validator.isMACAddress(v), { message: 'Invalid MAC address.' }),
broadcast: z
.string()
.refine((v) => validator.isIP(v), { message: 'Invalid broadcast IP address.' }),
port: z.coerce
.number({ message: 'Port is invalid.' })
.min(1, { message: 'Port must be at least 1.' })
.max(65535, { message: 'Port must be at most 65535.' }),
packets: z.coerce
.number({ message: 'Packets quantity is invalid.' })
.min(1, { message: 'Packets quantity must be at least 1.' })
.max(50, { message: 'Packets quantity must be at most 50.' }),
});
const parsed = schema.safeParse({
name: form.get('name'),
mac: form.get('mac'),
broadcast: form.get('broadcast'),
port: form.get('port'),
packets: form.get('packets'),
});
const parsed = schema.safeParse({
name: form.get('name'),
mac: form.get('mac'),
broadcast: form.get('broadcast'),
port: form.get('port'),
packets: form.get('packets'),
});
if (!parsed.success) {
return PARSE_ERROR(parsed.error);
}
if (!parsed.success) {
return PARSE_ERROR(parsed.error);
}
const err =
params.id === 'new'
? await devices.create(parsed.data)
: await devices.update({ id: params.id ?? '', ...parsed.data });
const err =
params.id === 'new'
? await devices.create(parsed.data)
: await devices.update({ id: params.id ?? '', ...parsed.data });
return err ? err.toFail() : SUCCESS;
},
return err ? err.toFail() : SUCCESS;
},
delete: async ({ locals: { guard }, params }) => {
if (guard.requiresAdmin().isFailed()) return FORBIDDEN;
delete: async ({ locals: { guard }, params }) => {
if (guard.requiresAdmin().isFailed()) return FORBIDDEN;
const err = await devices.delete(params.id ?? '');
return err ? err.toFail() : SUCCESS;
},
const err = await devices.delete(params.id ?? '');
return err ? err.toFail() : SUCCESS;
},
wake: async ({ params, locals: { guard } }) => {
guard = guard.requiresAuth();
if (guard.isFailed()) return FORBIDDEN;
wake: async ({ params, locals: { guard } }) => {
guard = guard.requiresAuth();
if (guard.isFailed()) return FORBIDDEN;
const device = (await users.fetchDevices(guard.getUser().id)).find((d) => d.id === params.id);
const device = (await users.fetchDevices(guard.getUser().id)).find((d) => d.id === params.id);
if (!device) {
return fail(404);
}
if (!device) {
return fail(404);
}
console.log('Trying to wake ' + device.name);
console.log('Trying to wake ' + device.name);
wake(device.mac, {
address: device.broadcast,
port: device.port,
num_packets: device.packets,
});
wake(device.mac, {
address: device.broadcast,
port: device.port,
num_packets: device.packets,
});
return SUCCESS;
},
return SUCCESS;
},
} satisfies Actions;

View File

@ -1,73 +1,73 @@
<script lang="ts">
import { browser } from '$app/environment';
import InputText from '$lib/v2/forms/InputText.svelte';
import { pageTitle } from '$lib/v2/globalStores';
import EditPage from '$lib/v2/snippets/EditPage.svelte';
import Collapsible from '$lib/v2/ui/Collapsible.svelte';
import { browser } from '$app/environment';
import InputText from '$lib/v2/forms/InputText.svelte';
import { pageTitle } from '$lib/v2/globalStores';
import EditPage from '$lib/v2/snippets/EditPage.svelte';
import Collapsible from '$lib/v2/ui/Collapsible.svelte';
let { data, form } = $props();
let { data, form } = $props();
$pageTitle = data.device ? 'Editing device: ' + data.device.name : 'Adding new Device';
$pageTitle = data.device ? 'Editing device: ' + data.device.name : 'Adding new Device';
// store the state of data that can be collapsed on the form and bind to it
// as to not lose user edits when the form is collapsed and expanded again
let collapsibleData = $state({
broadcast: data.device?.broadcast || '255.255.255.255',
port: data.device?.port || '9',
packets: data.device?.packets || '3',
});
// store the state of data that can be collapsed on the form and bind to it
// as to not lose user edits when the form is collapsed and expanded again
let collapsibleData = $state({
broadcast: data.device?.broadcast || '255.255.255.255',
port: data.device?.port || '9',
packets: data.device?.packets || '3',
});
$effect(() => {
if (form?.success && browser) {
history.back();
}
});
$effect(() => {
if (form?.success && browser) {
history.back();
}
});
</script>
<EditPage createOnly={!data.device}>
<InputText
name="name"
label="Name"
description="How the device will appear in the dashboard"
value={data.device?.name}
placeholder="New Device"
class="w-full"
required
/>
<InputText
name="name"
label="Name"
description="How the device will appear in the dashboard"
value={data.device?.name}
placeholder="New Device"
class="w-full"
required
/>
<InputText
name="mac"
label="MAC Address"
description="Address used for the Wake-On-Lan packets"
value={data.device?.mac}
placeholder="00:00:00:00:00:00"
class="w-full"
required
/>
<InputText
name="mac"
label="MAC Address"
description="Address used for the Wake-On-Lan packets"
value={data.device?.mac}
placeholder="00:00:00:00:00:00"
class="w-full"
required
/>
<Collapsible label="Advanced" class="mb-6" renderHidden>
<InputText
name="broadcast"
label="Broadcast IP"
bind:value={collapsibleData.broadcast}
class="w-full"
required
/>
<Collapsible label="Advanced" class="mb-6" renderHidden>
<InputText
name="broadcast"
label="Broadcast IP"
bind:value={collapsibleData.broadcast}
class="w-full"
required
/>
<InputText
name="port"
label="Broadcast Port"
bind:value={collapsibleData.port}
class="w-full"
required
/>
<InputText
name="port"
label="Broadcast Port"
bind:value={collapsibleData.port}
class="w-full"
required
/>
<InputText
name="packets"
label="Packets Quantity"
bind:value={collapsibleData.packets}
class="w-full"
required
/>
</Collapsible>
<InputText
name="packets"
label="Packets Quantity"
bind:value={collapsibleData.packets}
class="w-full"
required
/>
</Collapsible>
</EditPage>

View File

@ -2,17 +2,17 @@ import { groups } from '$lib/server/db';
import { type ServerLoad } from '@sveltejs/kit';
export const load: ServerLoad = async ({ locals: { guard } }) => {
guard.requiresAdmin().orRedirects();
guard.requiresAdmin().orRedirects();
const allGroups = await groups.getAll();
let userCounts: { [key: string]: number } = {};
const allGroups = await groups.getAll();
let userCounts: { [key: string]: number } = {};
for (let g of allGroups) {
userCounts[g.id] = await groups.countUsers(g.id);
}
for (let g of allGroups) {
userCounts[g.id] = await groups.countUsers(g.id);
}
return {
groups: allGroups,
userCounts,
};
return {
groups: allGroups,
userCounts,
};
};

View File

@ -1,21 +1,21 @@
<script>
import { pageTitle } from '$lib/v2/globalStores.js';
import ListPage from '$lib/v2/snippets/ListPage.svelte';
import ResCard from '$lib/v2/ui/ResCard.svelte';
import { pageTitle } from '$lib/v2/globalStores.js';
import ListPage from '$lib/v2/snippets/ListPage.svelte';
import ResCard from '$lib/v2/ui/ResCard.svelte';
let { data } = $props();
let { data } = $props();
$pageTitle = 'Listing all groups';
$pageTitle = 'Listing all groups';
</script>
<ListPage createHref={data.user.admin ? '/dash/groups/new' : null} msgAdd="Add Group">
<div class="flex gap-4 flex-wrap justify-center">
{#each data.groups as group}
<ResCard
title={group.name}
subtitle="{data.userCounts[group.id]} users, {group.devices.length} devices"
editHref={data.user.admin ? `/dash/groups/${group.id}` : null}
/>
{/each}
</div>
<div class="flex gap-4 flex-wrap justify-center">
{#each data.groups as group}
<ResCard
title={group.name}
subtitle="{data.userCounts[group.id]} users, {group.devices.length} devices"
editHref={data.user.admin ? `/dash/groups/${group.id}` : null}
/>
{/each}
</div>
</ListPage>

View File

@ -4,55 +4,55 @@ import { redirect, type Actions, type ServerLoad } from '@sveltejs/kit';
import { z } from 'zod';
export const load: ServerLoad = async ({ locals: { guard }, params }) => {
guard.requiresAdmin().orRedirects();
guard.requiresAdmin().orRedirects();
const group = await groups.getById(params.id ?? '');
const group = await groups.getById(params.id ?? '');
if (!group && params.id !== 'new') {
redirect(302, '/dash/groups');
}
if (!group && params.id !== 'new') {
redirect(302, '/dash/groups');
}
return {
devices: await devices.getAll(),
group,
};
return {
devices: await devices.getAll(),
group,
};
};
export const actions = {
update: async ({ request, locals: { guard }, params }) => {
if (guard.requiresAdmin().isFailed()) return FORBIDDEN;
update: async ({ request, locals: { guard }, params }) => {
if (guard.requiresAdmin().isFailed()) return FORBIDDEN;
const form = await request.formData();
const form = await request.formData();
const schema = z.object({
name: z
.string({ message: 'Name is required.' })
.min(3, { message: 'Name must be at least 3 characters.' })
.max(24, { message: 'Name must be at most 24 characters.' }),
devices: z.array(z.string()),
});
const schema = z.object({
name: z
.string({ message: 'Name is required.' })
.min(3, { message: 'Name must be at least 3 characters.' })
.max(24, { message: 'Name must be at most 24 characters.' }),
devices: z.array(z.string()),
});
const parsed = schema.safeParse({
name: form.get('name'),
devices: form.getAll('devices'),
});
const parsed = schema.safeParse({
name: form.get('name'),
devices: form.getAll('devices'),
});
if (!parsed.success) {
return PARSE_ERROR(parsed.error);
}
if (!parsed.success) {
return PARSE_ERROR(parsed.error);
}
const err =
params.id === 'new'
? await groups.create({ ...parsed.data })
: await groups.update({ id: params.id ?? '', ...parsed.data });
const err =
params.id === 'new'
? await groups.create({ ...parsed.data })
: await groups.update({ id: params.id ?? '', ...parsed.data });
return err ? err.toFail() : SUCCESS;
},
return err ? err.toFail() : SUCCESS;
},
delete: async ({ locals: { guard }, params }) => {
if (guard.requiresAdmin().isFailed()) return FORBIDDEN;
delete: async ({ locals: { guard }, params }) => {
if (guard.requiresAdmin().isFailed()) return FORBIDDEN;
const err = await groups.delete(params.id ?? '');
return err ? err.toFail() : SUCCESS;
},
const err = await groups.delete(params.id ?? '');
return err ? err.toFail() : SUCCESS;
},
} satisfies Actions;

View File

@ -1,41 +1,41 @@
<script lang="ts">
import { browser } from '$app/environment';
import InputCombobox from '$lib/v2/forms/InputCombobox.svelte';
import InputText from '$lib/v2/forms/InputText.svelte';
import { pageTitle } from '$lib/v2/globalStores';
import EditPage from '$lib/v2/snippets/EditPage.svelte';
import { browser } from '$app/environment';
import InputCombobox from '$lib/v2/forms/InputCombobox.svelte';
import InputText from '$lib/v2/forms/InputText.svelte';
import { pageTitle } from '$lib/v2/globalStores';
import EditPage from '$lib/v2/snippets/EditPage.svelte';
let { data, form } = $props();
let { data, form } = $props();
$pageTitle = data.group ? 'Editing group: ' + data.group.name : 'Adding new group';
$pageTitle = data.group ? 'Editing group: ' + data.group.name : 'Adding new group';
$effect(() => {
if (form?.success && browser) {
history.back();
}
});
$effect(() => {
if (form?.success && browser) {
history.back();
}
});
</script>
<EditPage createOnly={!data.group}>
<InputText
name="name"
label="Name"
description="How the group will appear in the dashboard"
value={data.group?.name}
placeholder="New Group"
class="w-full"
required
/>
<InputText
name="name"
label="Name"
description="How the group will appear in the dashboard"
value={data.group?.name}
placeholder="New Group"
class="w-full"
required
/>
<InputCombobox
label="Devices"
description="Devices that users who are part of this group will be able to wake"
name="devices"
class="w-full"
data={data.devices.map((d) => ({
value: d.id,
name: d.name,
selected: data.group?.devices.find((devId) => devId === d.id) ? true : false,
}))}
/>
<InputCombobox
label="Devices"
description="Devices that users who are part of this group will be able to wake"
name="devices"
class="w-full"
data={data.devices.map((d) => ({
value: d.id,
name: d.name,
selected: data.group?.devices.find((devId) => devId === d.id) ? true : false,
}))}
/>
</EditPage>

View File

@ -1,11 +1,11 @@
import { users } from '$lib/server/db';
import { toPublicUser, type User } from '$lib/server/db/types/user';
import { toPublicUser } from '$lib/server/db/types/user';
import type { ServerLoad } from '@sveltejs/kit';
export const load: ServerLoad = async ({ locals: { guard } }) => {
guard.requiresAdmin().orRedirects();
guard.requiresAdmin().orRedirects();
return {
users: (await users.getAll()).map((u) => toPublicUser(u)),
};
return {
users: (await users.getAll()).map((u) => toPublicUser(u)),
};
};

View File

@ -1,21 +1,21 @@
<script>
import { pageTitle } from '$lib/v2/globalStores.js';
import ListPage from '$lib/v2/snippets/ListPage.svelte';
import ResCard from '$lib/v2/ui/ResCard.svelte';
import { pageTitle } from '$lib/v2/globalStores.js';
import ListPage from '$lib/v2/snippets/ListPage.svelte';
import ResCard from '$lib/v2/ui/ResCard.svelte';
let { data } = $props();
let { data } = $props();
$pageTitle = 'Listing all users';
$pageTitle = 'Listing all users';
</script>
<ListPage createHref={data.user.admin ? '/dash/users/new' : null} msgAdd="Add User">
<div class="flex gap-4 flex-wrap justify-center">
{#each data.users as user}
<ResCard
title={user.name}
subtitle="{user.devices.length} devices, {user.groups.length} groups"
editHref={data.user.admin ? `/dash/users/${user.id}` : null}
/>
{/each}
</div>
<div class="flex gap-4 flex-wrap justify-center">
{#each data.users as user}
<ResCard
title={user.name}
subtitle="{user.devices.length} devices, {user.groups.length} groups"
editHref={data.user.admin ? `/dash/users/${user.id}` : null}
/>
{/each}
</div>
</ListPage>

View File

@ -7,85 +7,85 @@ import bcrypt from 'bcryptjs';
import { z } from 'zod';
export const load: ServerLoad = async ({ locals: { guard }, params }) => {
guard.requiresAdmin().orRedirects();
guard.requiresAdmin().orRedirects();
let user = await users.getById(params.id ?? '');
let user = await users.getById(params.id ?? '');
if (!user && params.id !== 'new') {
redirect(302, '/dash/users');
}
if (!user && params.id !== 'new') {
redirect(302, '/dash/users');
}
return {
user: toPublicUser(user!),
groups: await groups.getAll(),
devices: await devices.getAll(),
};
return {
user: toPublicUser(user!),
groups: await groups.getAll(),
devices: await devices.getAll(),
};
};
export const actions = {
update: async ({ request, locals: { guard }, params }) => {
if (guard.requiresAdmin().isFailed()) return FORBIDDEN;
update: async ({ request, locals: { guard }, params }) => {
if (guard.requiresAdmin().isFailed()) return FORBIDDEN;
const form = await request.formData();
const form = await request.formData();
const schema = z.object({
name: z
.string({ message: 'Name is required.' })
.min(3, { message: 'Name must be at least 3 characters.' })
.max(24, { message: 'Name must be at most 24 characters.' }),
admin: z.boolean(),
password: z
.string()
.refine((v) => (params.id === 'new' ? v.length > 0 : true), {
// if /new, password must be present
message: 'Password is required at user creation.',
})
.refine((v) => (v.length > 0 ? v.length >= 8 : true), {
// if password present, must be at least 8 chars
message: 'Password must be at least 8 characters.',
}),
groups: z.array(z.string()),
devices: z.array(z.string()),
});
const schema = z.object({
name: z
.string({ message: 'Name is required.' })
.min(3, { message: 'Name must be at least 3 characters.' })
.max(24, { message: 'Name must be at most 24 characters.' }),
admin: z.boolean(),
password: z
.string()
.refine((v) => (params.id === 'new' ? v.length > 0 : true), {
// if /new, password must be present
message: 'Password is required at user creation.',
})
.refine((v) => (v.length > 0 ? v.length >= 8 : true), {
// if password present, must be at least 8 chars
message: 'Password must be at least 8 characters.',
}),
groups: z.array(z.string()),
devices: z.array(z.string()),
});
const parsed = schema.safeParse({
name: form.get('name'),
admin: form.get('admin') === 'on',
password: form.get('password'),
groups: form.getAll('groups'),
devices: form.getAll('devices'),
});
const parsed = schema.safeParse({
name: form.get('name'),
admin: form.get('admin') === 'on',
password: form.get('password'),
groups: form.getAll('groups'),
devices: form.getAll('devices'),
});
if (!parsed.success) {
return PARSE_ERROR(parsed.error);
}
if (!parsed.success) {
return PARSE_ERROR(parsed.error);
}
if (params.id === 'new') {
const err = await users.create({
...parsed.data,
password: bcrypt.hashSync(parsed.data.password, 10),
});
if (params.id === 'new') {
const err = await users.create({
...parsed.data,
password: bcrypt.hashSync(parsed.data.password, 10),
});
return err ? err.toFail() : SUCCESS;
}
return err ? err.toFail() : SUCCESS;
}
let updatedUser: Updated<User> = { id: params.id ?? '', ...parsed.data };
let updatedUser: Updated<User> = { id: params.id ?? '', ...parsed.data };
if (parsed.data.password.length > 0) {
updatedUser.password = bcrypt.hashSync(parsed.data.password, 10);
} else {
// avoid saving empty passwpord
delete updatedUser.password;
}
if (parsed.data.password.length > 0) {
updatedUser.password = bcrypt.hashSync(parsed.data.password, 10);
} else {
// avoid saving empty passwpord
delete updatedUser.password;
}
const err = await users.update(updatedUser);
return err ? err.toFail() : SUCCESS;
},
const err = await users.update(updatedUser);
return err ? err.toFail() : SUCCESS;
},
delete: async ({ locals: { guard }, params }) => {
if (guard.requiresAdmin().isFailed()) return FORBIDDEN;
delete: async ({ locals: { guard }, params }) => {
if (guard.requiresAdmin().isFailed()) return FORBIDDEN;
const err = await users.delete(params.id ?? '');
return err ? err.toFail() : SUCCESS;
},
const err = await users.delete(params.id ?? '');
return err ? err.toFail() : SUCCESS;
},
} satisfies Actions;

View File

@ -1,72 +1,72 @@
<script lang="ts">
import { browser } from '$app/environment';
import InputCheckbox from '$lib/v2/forms/InputCheckbox.svelte';
import InputCombobox from '$lib/v2/forms/InputCombobox.svelte';
import InputText from '$lib/v2/forms/InputText.svelte';
import { pageTitle } from '$lib/v2/globalStores';
import EditPage from '$lib/v2/snippets/EditPage.svelte';
import { browser } from '$app/environment';
import InputCheckbox from '$lib/v2/forms/InputCheckbox.svelte';
import InputCombobox from '$lib/v2/forms/InputCombobox.svelte';
import InputText from '$lib/v2/forms/InputText.svelte';
import { pageTitle } from '$lib/v2/globalStores';
import EditPage from '$lib/v2/snippets/EditPage.svelte';
let { data, form } = $props();
let { data, form } = $props();
$pageTitle = data.user ? 'Editing user: ' + data.user.name : 'Adding new user';
$pageTitle = data.user ? 'Editing user: ' + data.user.name : 'Adding new user';
$effect(() => {
if (form?.success && browser) {
history.back();
}
});
$effect(() => {
if (form?.success && browser) {
history.back();
}
});
</script>
<p class="text-white">{form?.error}</p>
<EditPage createOnly={!data.user}>
<InputText
name="name"
label="Name"
description="How the user will appear in the dashboard"
value={data.user?.name}
placeholder="New User"
class="w-full"
required
/>
<InputText
name="name"
label="Name"
description="How the user will appear in the dashboard"
value={data.user?.name}
placeholder="New User"
class="w-full"
required
/>
<InputText
name="password"
label="Password"
description={data.user
? "Leave blank to keep the user's current password"
: 'The password will be hashed and stored in the database'}
type="password"
class="w-full"
/>
<InputText
name="password"
label="Password"
description={data.user
? "Leave blank to keep the user's current password"
: 'The password will be hashed and stored in the database'}
type="password"
class="w-full"
/>
<InputCheckbox
name="admin"
label="Administrator"
description="Can manage and use all devices, groups and users"
checked={data.user?.admin ?? false}
/>
<InputCheckbox
name="admin"
label="Administrator"
description="Can manage and use all devices, groups and users"
checked={data.user?.admin ?? false}
/>
<InputCombobox
label="Devices"
description="Devices that the user will be able to wake"
name="devices"
class="w-full"
data={data.devices.map((d) => ({
value: d.id,
name: d.name,
selected: data.user?.devices.find((devId) => devId === d.id) ? true : false,
}))}
/>
<InputCombobox
label="Devices"
description="Devices that the user will be able to wake"
name="devices"
class="w-full"
data={data.devices.map((d) => ({
value: d.id,
name: d.name,
selected: data.user?.devices.find((devId) => devId === d.id) ? true : false,
}))}
/>
<InputCombobox
label="Groups"
description="Groups that the user will be a part of and inherit device access from"
name="groups"
class="w-full"
data={data.groups.map((g) => ({
value: g.id,
name: g.name,
selected: data.user?.groups.find((groupId) => groupId === g.id) ? true : false,
}))}
/>
<InputCombobox
label="Groups"
description="Groups that the user will be a part of and inherit device access from"
name="groups"
class="w-full"
data={data.groups.map((g) => ({
value: g.id,
name: g.name,
selected: data.user?.groups.find((groupId) => groupId === g.id) ? true : false,
}))}
/>
</EditPage>

View File

@ -1,49 +1,49 @@
import { dev } from '$app/environment';
import { users } from '$lib/server/db';
import { createSession } from '$lib/server/sessions';
import { fail, redirect } from '@sveltejs/kit';
import bcrypt from 'bcryptjs';
import type { Actions } from './$types';
import { dev } from '$app/environment';
export const actions = {
default: async ({ cookies, request, locals: { guard } }) => {
if (!guard.requiresAuth().isFailed()) {
redirect(302, '/dash');
}
default: async ({ cookies, request, locals: { guard } }) => {
if (!guard.requiresAuth().isFailed()) {
redirect(302, '/dash');
}
const data = await request.formData();
const username = data.get('username')?.toString();
const password = data.get('password')?.toString();
const data = await request.formData();
const username = data.get('username')?.toString();
const password = data.get('password')?.toString();
if (!username || !password) {
return fail(400, {
error: 'MISSING_CREDENTIALS',
});
}
if (!username || !password) {
return fail(400, {
error: 'MISSING_CREDENTIALS',
});
}
const user = await users.getByName(username);
const user = await users.getByName(username);
if (!user || !bcrypt.compareSync(password, user.password)) {
return fail(403, {
error: 'INVALID_CREDENTIALS',
});
}
if (!user || !bcrypt.compareSync(password, user.password)) {
return fail(403, {
error: 'INVALID_CREDENTIALS',
});
}
cookies.set(
'session',
createSession({
userAgent: request.headers.get('user-agent') ?? 'UNKNOWN',
userId: user.id,
}),
{
path: '/',
httpOnly: true,
secure: !dev, // safari doesn't allow secure cookies on localhost
sameSite: true,
maxAge: 60 * 60 * 24,
},
);
cookies.set(
'session',
createSession({
userAgent: request.headers.get('user-agent') ?? 'UNKNOWN',
userId: user.id,
}),
{
path: '/',
httpOnly: true,
secure: !dev, // safari doesn't allow secure cookies on localhost
sameSite: true,
maxAge: 60 * 60 * 24,
},
);
redirect(302, '/dash');
},
redirect(302, '/dash');
},
} satisfies Actions;

View File

@ -1,21 +1,21 @@
<script lang="ts">
import type { PageProps } from './$types';
import type { PageProps } from './$types';
let { form }: PageProps = $props();
let { form }: PageProps = $props();
</script>
<form method="POST">
<label>
Username
<input name="username" type="text">
</label>
<label>
Password
<input name="password" type="password">
</label>
<button>Log in</button>
<label>
Username
<input name="username" type="text" />
</label>
<label>
Password
<input name="password" type="password" />
</label>
<button>Log in</button>
</form>
{#if form?.error}
<p>Could not login: {form.error}</p>
{/if}
<p>Could not login: {form.error}</p>
{/if}

View File

@ -1,8 +1,8 @@
import { deleteSession } from "$lib/server/sessions";
import { redirect, type ServerLoad } from "@sveltejs/kit";
import { deleteSession } from '$lib/server/sessions';
import { redirect, type ServerLoad } from '@sveltejs/kit';
export const load: ServerLoad = async ({ cookies }) => {
deleteSession(cookies.get("session"));
cookies.delete("session", { path: "/" });
redirect(302, "/login");
};
deleteSession(cookies.get('session'));
cookies.delete('session', { path: '/' });
redirect(302, '/login');
};