Add web interface with admin functionality (#167)

This commit is contained in:
Alex
2022-05-21 02:23:55 -05:00
committed by GitHub
parent 79dea504b0
commit a779c3803c
76 changed files with 8252 additions and 87 deletions

31
web/src/app.css Normal file
View File

@@ -0,0 +1,31 @@
@import url('https://fonts.googleapis.com/css2?family=Work+Sans:wght@300;400;500;600;700&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Snowburst+One&display=swap');
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
font-family: 'Work Sans', sans-serif;
}
body {
min-height: 100vh;
margin: 0;
background-color: #f6f8fe;
color: #5f6368;
}
@layer utilities {
.immich-form-input {
@apply bg-slate-100 p-2 rounded-md focus:border-immich-primary text-sm
}
.immich-form-label {
@apply font-medium text-sm text-gray-500
}
.immich-btn-primary {
@apply bg-immich-primary text-gray-100 border rounded-xl py-2 px-4 transition-all duration-150 hover:bg-immich-primary hover:shadow-lg text-sm font-medium
}
}

32
web/src/app.d.ts vendored Normal file
View File

@@ -0,0 +1,32 @@
/// <reference types="@sveltejs/kit" />
// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
declare namespace App {
interface Locals {
user?: {
id: string,
email: string,
accessToken: string,
firstName: string,
lastName: string,
isAdmin: boolean,
}
}
// interface Platform {}
interface Session {
user?: {
id: string,
email: string,
accessToken: string,
firstName: string,
lastName: string
isAdmin: boolean,
}
}
// interface Stuff {}
}

12
web/src/app.html Normal file
View File

@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%svelte.assets%/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
%svelte.head%
</head>
<body>
<div>%svelte.body%</div>
</body>
</html>

54
web/src/hooks.ts Normal file
View File

@@ -0,0 +1,54 @@
import type { ExternalFetch, GetSession, Handle } from '@sveltejs/kit';
import * as cookie from 'cookie';
import { serverEndpoint } from '$lib/constants';
import { session } from '$app/stores';
export const handle: Handle = async ({ event, resolve, }) => {
const cookies = cookie.parse(event.request.headers.get('cookie') || '');
if (!cookies.session) {
return await resolve(event)
}
const { email, isAdmin, firstName, lastName, id, accessToken } = JSON.parse(cookies.session);
const res = await fetch(`${serverEndpoint}/auth/validateToken`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`
}
})
if (res.status === 201) {
event.locals.user = {
id,
accessToken,
firstName,
lastName,
isAdmin,
email
};
}
const response = await resolve(event);
return response;
};
export const getSession: GetSession = async ({ locals }) => {
if (!locals.user) return {}
return {
user: {
id: locals.user.id,
accessToken: locals.user.accessToken,
firstName: locals.user.firstName,
lastName: locals.user.lastName,
isAdmin: locals.user.isAdmin,
email: locals.user.email
}
}
}

53
web/src/lib/api.ts Normal file
View File

@@ -0,0 +1,53 @@
import { serverEndpoint } from './constants';
type ISend = {
method: string,
path: string,
data?: any,
token: string
}
type IOption = {
method: string,
headers: Record<string, string>,
body: any
}
async function send({ method, path, data, token }: ISend) {
const opts: IOption = { method, headers: {} } as IOption;
if (data) {
opts.headers['Content-Type'] = 'application/json';
opts.body = JSON.stringify(data);
}
if (token) {
opts.headers['Authorization'] = `Bearer ${token}`;
}
return fetch(`${serverEndpoint}/${path}`, opts)
.then((r) => r.text())
.then((json) => {
try {
return JSON.parse(json);
} catch (err) {
return json;
}
});
}
export function getRequest(path: string, token: string) {
return send({ method: 'GET', path, token });
}
export function delRequest(path: string, token: string) {
return send({ method: 'DELETE', path, token });
}
export function postRequest(path: string, data: any, token: string) {
return send({ method: 'POST', path, data, token });
}
export function putRequest(path: string, data: any, token: string) {
return send({ method: 'PUT', path, data, token });
}

74
web/src/lib/auth-api.ts Normal file
View File

@@ -0,0 +1,74 @@
type AdminRegistrationResult = Promise<{
error?: string
success?: string
user?: {
email: string
}
}>
type LoginResult = Promise<{
error?: string
success?: string
needUpdate?: boolean
needSelectAdmin?: boolean
user?: {
accessToken: string
firstName: string
lastName: string
isAdmin: boolean
id: string
email: string
}
}>
type UpdateResult = Promise<{
error?: string
success?: string,
user?: {
accessToken: string
firstName: string
lastName: string
isAdmin: boolean
id: string
email: string
}
}>
export async function sendRegistrationForm(form: HTMLFormElement): AdminRegistrationResult {
const response = await fetch(form.action, {
method: form.method,
body: new FormData(form),
headers: { accept: 'application/json' },
})
return await response.json()
}
export async function sendLoginForm(form: HTMLFormElement): LoginResult {
const response = await fetch(form.action, {
method: form.method,
body: new FormData(form),
headers: { accept: 'application/json' },
})
return await response.json()
}
export async function sendUpdateForm(form: HTMLFormElement): UpdateResult {
const response = await fetch(form.action, {
method: form.method,
body: new FormData(form),
headers: { accept: 'application/json' },
})
return await response.json()
}

View File

@@ -0,0 +1,41 @@
<script lang="ts">
import { createEventDispatcher } from 'svelte';
import PencilOutline from 'svelte-material-icons/PencilOutline.svelte';
export let usersOnServer: Array<any>;
const dispatch = createEventDispatcher();
</script>
<p class="text-sm">USER LIST</p>
<table class="text-left w-full my-4">
<thead class="border rounded-md mb-2 bg-gray-50 flex text-immich-primary w-full h-12 ">
<tr class="flex w-full place-items-center">
<th class="text-center w-1/4 font-medium text-sm">Email</th>
<th class="text-center w-1/4 font-medium text-sm">First name</th>
<th class="text-center w-1/4 font-medium text-sm">Last name</th>
<th class="text-center w-1/4 font-medium text-sm">Edit</th>
</tr>
</thead>
<tbody class="overflow-y-auto rounded-md w-full max-h-[320px] block border">
{#each usersOnServer as user, i}
<tr
class={`text-center flex place-items-center w-full border-b h-[80px] ${
i % 2 == 0 ? 'bg-gray-100' : 'bg-immich-bg'
}`}
>
<td class="text-sm px-4 w-1/4 text-ellipsis">{user.email}</td>
<td class="text-sm px-4 w-1/4 text-ellipsis">{user.firstName}</td>
<td class="text-sm px-4 w-1/4 text-ellipsis">{user.lastName}</td>
<td class="text-sm px-4 w-1/4 text-ellipsis"
><button
class="bg-immich-primary text-gray-100 rounded-full p-3 transition-all duration-150 hover:bg-immich-primary/75"
><PencilOutline size="20" /></button
></td
>
</tr>
{/each}
</tbody>
</table>
<button on:click={() => dispatch('createUser')} class="immich-btn-primary">Create user</button>

View File

@@ -0,0 +1,78 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { sendRegistrationForm } from '$lib/auth-api';
let error: string;
let success: string;
async function registerAdmin(event: SubmitEvent) {
error = '';
const formElement = event.target as HTMLFormElement;
const response = await sendRegistrationForm(formElement);
if (response.error) {
error = JSON.stringify(response.error);
}
if (response.success) {
success = response.success;
goto('/auth/login');
}
}
</script>
<div class="border bg-white p-4 shadow-sm w-[500px] rounded-md py-8">
<div class="flex flex-col place-items-center place-content-center gap-4 px-4">
<img class="text-center" src="/immich-logo.svg" height="100" width="100" alt="immich-logo" />
<h1 class="text-2xl text-immich-primary font-medium">Admin Registration</h1>
<p class="text-sm border rounded-md p-4 font-mono text-gray-600">
Since you are the first user on the system, you will be assigned as the Admin and are responsible for
administrative tasks, and additional users will be created by you.
</p>
</div>
<form on:submit|preventDefault={registerAdmin} method="post" action="" autocomplete="off">
<div class="m-4 flex flex-col gap-2">
<label class="immich-form-label" for="email">Admin Email</label>
<input class="immich-form-input" id="email" name="email" type="email" required />
</div>
<div class="m-4 flex flex-col gap-2">
<label class="immich-form-label" for="password">Admin Password</label>
<input class="immich-form-input" id="password" name="password" type="password" required />
</div>
<div class="m-4 flex flex-col gap-2">
<label class="immich-form-label" for="password">First Name</label>
<input class="immich-form-input" id="firstName" name="firstName" type="text" required />
</div>
<div class="m-4 flex flex-col gap-2">
<label class="immich-form-label" for="password">Last Name</label>
<input class="immich-form-input" id="lastName" name="lastName" type="text" required />
</div>
{#if error}
<p class="text-red-400">{error}</p>
{/if}
{#if success}
<div>
<p>Admin account has been registered</p>
<p>
<a href="/auth/login">Login</a>
</p>
</div>
{/if}
<div class="flex w-full">
<button
type="submit"
class="m-4 p-2 bg-immich-primary hover:bg-immich-primary/75 px-6 py-4 text-white rounded-md shadow-md w-full"
>Sign Up</button
>
</div>
</form>
</div>

View File

@@ -0,0 +1,74 @@
<script lang="ts">
import { sendRegistrationForm } from '$lib/auth-api';
import { createEventDispatcher } from 'svelte';
let error: string;
let success: string;
const dispatch = createEventDispatcher();
async function registerUser(event: SubmitEvent) {
error = '';
const formElement = event.target as HTMLFormElement;
const response = await sendRegistrationForm(formElement);
if (response.error) {
error = JSON.stringify(response.error);
}
if (response.success) {
success = 'New user created';
dispatch('user-created');
}
}
</script>
<div class="border bg-white p-4 shadow-sm w-[500px] rounded-md py-8">
<div class="flex flex-col place-items-center place-content-center gap-4 px-4">
<img class="text-center" src="/immich-logo.svg" height="100" width="100" alt="immich-logo" />
<h1 class="text-2xl text-immich-primary font-medium">Create new user</h1>
<p class="text-sm border rounded-md p-4 font-mono text-gray-600">
Please provide your user with the password, they will have to change it on their first sign in.
</p>
</div>
<form on:submit|preventDefault={registerUser} method="post" action="/admin/api/create-user" autocomplete="off">
<div class="m-4 flex flex-col gap-2">
<label class="immich-form-label" for="email">Email</label>
<input class="immich-form-input" id="email" name="email" type="email" required />
</div>
<div class="m-4 flex flex-col gap-2">
<label class="immich-form-label" for="password">Password</label>
<input class="immich-form-input" id="password" name="password" type="password" required />
</div>
<div class="m-4 flex flex-col gap-2">
<label class="immich-form-label" for="password">First Name</label>
<input class="immich-form-input" id="firstName" name="firstName" type="text" required />
</div>
<div class="m-4 flex flex-col gap-2">
<label class="immich-form-label" for="password">Last Name</label>
<input class="immich-form-input" id="lastName" name="lastName" type="text" required />
</div>
{#if error}
<p class="text-red-400">{error}</p>
{/if}
{#if success}
<p class="text-immich-primary">{success}</p>
{/if}
<div class="flex w-full">
<button
type="submit"
class="m-4 p-2 bg-immich-primary hover:bg-immich-primary/75 px-6 py-4 text-white rounded-md shadow-md w-full"
>Create</button
>
</div>
</form>
</div>

View File

@@ -0,0 +1,73 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { session } from '$app/stores';
import { sendLoginForm } from '$lib/auth-api';
import { createEventDispatcher } from 'svelte';
let error: string;
const dispatch = createEventDispatcher();
async function login(event: SubmitEvent) {
error = '';
const formElement = event.target as HTMLFormElement;
const response = await sendLoginForm(formElement);
if (response.error) {
error = response.error;
}
if (response.needUpdate) {
return dispatch('need-update');
}
if (response.needSelectAdmin) {
return dispatch('need-select-admin');
}
if (response.success) {
$session.user = {
accessToken: response.user!.accessToken,
firstName: response.user!.firstName,
lastName: response.user!.lastName,
isAdmin: response.user!.isAdmin,
id: response.user!.id,
email: response.user!.email,
};
return dispatch('success');
}
}
</script>
<div class="border bg-white p-4 shadow-sm w-[500px] rounded-md py-8">
<div class="flex flex-col place-items-center place-content-center gap-4 px-4">
<img class="text-center" src="/immich-logo.svg" height="100" width="100" alt="immich-logo" />
<h1 class="text-2xl text-immich-primary font-medium">Login</h1>
</div>
<form on:submit|preventDefault={login} method="post" action="" autocomplete="off">
<div class="m-4 flex flex-col gap-2">
<label class="immich-form-label" for="email">Email</label>
<input class="immich-form-input" id="email" name="email" type="email" required />
</div>
<div class="m-4 flex flex-col gap-2">
<label class="immich-form-label" for="password">Password</label>
<input class="immich-form-input" id="password" name="password" type="password" required />
</div>
{#if error}
<p class="text-red-400 pl-4">{error}</p>
{/if}
<div class="flex w-full">
<button
type="submit"
class="m-4 p-2 bg-immich-primary hover:bg-immich-primary/75 px-6 py-4 text-white rounded-md shadow-md w-full font-semibold"
>Login</button
>
</div>
</form>
</div>

View File

@@ -0,0 +1,93 @@
<script lang="ts">
import { session } from '$app/stores';
import { createEventDispatcher, onMount } from 'svelte';
import { fade } from 'svelte/transition';
import type { ImmichUser } from '../../models/immich-user';
import Check from 'svelte-material-icons/Check.svelte';
let error: string = '';
let allUsers: Array<ImmichUser> = [];
let selectedUserId: string;
const dispatch = createEventDispatcher();
onMount(async () => {
const res = await fetch('/auth/login/api/get-users', { method: 'GET' });
const data = await res.json();
allUsers = data.allUsers;
});
const assignAdmin = async () => {
const res = await fetch('/auth/login/api/select-admin', {
method: 'POST',
body: JSON.stringify({
id: selectedUserId,
isAdmin: true,
}),
});
if (res.status === 200) {
const data = await res.json();
$session.user = {
accessToken: '',
firstName: data.userInfo.firstName,
lastName: data.userInfo.lastName,
isAdmin: data.userInfo.isAdmin,
id: data.userInfo.id,
email: data.userInfo.email,
};
dispatch('success');
} else {
error = JSON.stringify(await res.json());
}
};
</script>
<div class="border bg-white p-4 shadow-sm w-[500px] rounded-md py-8">
<div class="flex flex-col place-items-center place-content-center gap-4 px-4">
<img class="text-center" src="/immich-logo.svg" height="100" width="100" alt="immich-logo" />
<h1 class="text-2xl text-immich-primary font-medium">Select Admin</h1>
<p class="text-sm border rounded-md p-4 font-mono text-gray-600">
There are multiple users on the server, and none have been selected to be the admin. Please assign one as the
admin, who will be responsible for administrative tasks
</p>
</div>
<div class="text-xs m-4">USERS ON SERVER, CLICK TO SELECT ONE</div>
<div class="overflow-y-auto rounded-md max-h-[300px] block border mx-4 px-4 py-2">
{#each allUsers as user, i}
<div
class="p-4 flex justify-between place-items-center my-4 rounded-md hover:cursor-pointer shadow-sm bg-gray-50 hover:bg-gray-100"
on:click={() => (selectedUserId = user.id)}
>
<p class="test-sm text-slate-600">{i + 1} | {user.email}</p>
<!-- Icon -->
{#if selectedUserId == user.id}
<div
in:fade={{ duration: 100 }}
class="border rounded-full border-gray-300 bg-immich-primary w-8 h-8 flex place-items-center place-content-center"
>
<Check color="white" size="24" />
</div>
{:else}
<div in:fade={{ duration: 100 }} class="border rounded-full border-gray-300 w-8 h-8" />
{/if}
</div>
{/each}
</div>
{#if error}
<div class="text-xs m-4 text-red-400">Error: {error}</div>
{/if}
<div class="flex w-full">
<button
type="submit"
class="m-4 p-2 bg-immich-primary hover:bg-immich-primary/75 px-6 py-4 text-white rounded-md shadow-md w-full font-semibold"
on:click={assignAdmin}>Assign as Admin</button
>
</div>
</div>

View File

@@ -0,0 +1,68 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { session } from '$app/stores';
import { sendUpdateForm } from '$lib/auth-api';
import { createEventDispatcher } from 'svelte';
let error: string;
const dispatch = createEventDispatcher();
async function updateInfo(event: SubmitEvent) {
error = '';
const formElement = event.target as HTMLFormElement;
const response = await sendUpdateForm(formElement);
if (response.error) {
error = response.error;
}
if (response.success) {
$session.user = {
accessToken: response.user!.accessToken,
firstName: response.user!.firstName,
lastName: response.user!.lastName,
isAdmin: response.user!.isAdmin,
id: response.user!.id,
email: response.user!.email,
};
dispatch('success');
}
}
</script>
<div class="border bg-white p-4 shadow-sm w-[500px] rounded-md py-8">
<div class="flex flex-col place-items-center place-content-center gap-4 px-4">
<img class="text-center" src="/immich-logo.svg" height="100" width="100" alt="immich-logo" />
<h1 class="text-2xl text-immich-primary font-medium">Update User Info</h1>
<p class="text-sm border rounded-md p-4 font-mono text-gray-600">
Your account doesn't have information about your name, please update to continue the login process.
</p>
</div>
<form on:submit|preventDefault={updateInfo} method="post" action="/auth/login/update" autocomplete="off">
<div class="m-4 flex flex-col gap-2">
<label class="immich-form-label" for="firstName">First name</label>
<input class="immich-form-input" id="firstName" name="firstName" type="text" required />
</div>
<div class="m-4 flex flex-col gap-2">
<label class="immich-form-label" for="lastName">Last name</label>
<input class="immich-form-input" id="lastName" name="lastName" type="text" required />
</div>
{#if error}
<p class="text-red-400 pl-4">{error}</p>
{/if}
<div class="flex w-full">
<button
type="submit"
class="m-4 p-2 bg-immich-primary hover:bg-immich-primary/75 px-6 py-4 text-white rounded-md shadow-md w-full font-semibold"
>Update</button
>
</div>
</form>
</div>

View File

@@ -0,0 +1,15 @@
export function clickOutside(node: Node) {
const handleClick = (event: any) => {
if (!node.contains(event.target)) {
node.dispatchEvent(new CustomEvent("outclick"));
}
};
document.addEventListener("click", handleClick, true);
return {
destroy() {
document.removeEventListener("click", handleClick, true);
}
};
}

View File

@@ -0,0 +1,17 @@
<script lang="ts">
import { clickOutside } from './click-outside';
import { createEventDispatcher } from 'svelte';
import { fade } from 'svelte/transition';
const dispatch = createEventDispatcher();
</script>
<section
in:fade={{ duration: 100 }}
out:fade={{ duration: 100 }}
class="absolute w-full h-full bg-black/40 z-[100] flex place-items-center place-content-center "
>
<div class="bg-immich-bg z-[9999] rounded-md" use:clickOutside on:outclick={() => dispatch('clickOutside')}>
<slot />
</div>
</section>

View File

@@ -0,0 +1,60 @@
<script lang="ts">
import { page } from '$app/stores';
import type { ImmichUser } from '$lib/models/immich-user';
import { fade } from 'svelte/transition';
export let user: ImmichUser;
let shouldShowAccountInfo = false;
const getFirstLetter = (text?: string) => {
return text?.charAt(0).toUpperCase();
};
</script>
<section id="dashboard-navbar" class="fixed w-screen z-[100] bg-immich-bg text-sm">
<div class="flex border place-items-center px-6 py-2 ">
<a class="flex gap-2 place-items-center hover:cursor-pointer" href="/photos">
<img src="/immich-logo.svg" alt="immich logo" height="35" width="35" />
<h1 class="font-immich-title text-2xl text-immich-primary">Immich</h1>
</a>
<div class="flex-1 ml-24">
<div class="w-[50%] border rounded-md bg-gray-200 px-8 py-4">Search</div>
</div>
<section class="flex gap-6 place-items-center">
<!-- <div>Upload</div> -->
{#if user.isAdmin}
<a
class={`hover:text-immich-primary font-medium ${
$page.url.pathname == '/admin' && 'text-immich-primary underline'
}`}
href="/admin">Administration</a
>
{/if}
<div
on:mouseover={() => (shouldShowAccountInfo = true)}
on:focus={() => (shouldShowAccountInfo = true)}
on:mouseleave={() => (shouldShowAccountInfo = false)}
>
<button
class="flex place-items-center place-content-center rounded-full bg-immich-primary/80 h-10 w-10 text-gray-100 hover:bg-immich-primary"
>
{getFirstLetter(user.firstName)}{getFirstLetter(user.lastName)}
</button>
{#if shouldShowAccountInfo}
<div
in:fade={{ delay: 500, duration: 150 }}
out:fade={{ delay: 200, duration: 150 }}
class="absolute -bottom-12 right-5 border bg-gray-500 text-[12px] text-gray-100 p-2 rounded-md shadow-md"
>
<p>{user.firstName} {user.lastName}</p>
<p>{user.email}</p>
</div>
{/if}
</div>
</section>
</div>
</section>

View File

@@ -0,0 +1,27 @@
<script lang="ts">
export let title: string;
export let logo: any;
export let actionType: AdminSideBarSelection | AppSideBarSelection;
export let isSelected: boolean;
import { createEventDispatcher } from 'svelte';
import type { AdminSideBarSelection, AppSideBarSelection } from '../../models/admin-sidebar-selection';
const dispatch = createEventDispatcher();
const onButtonClicked = () => {
dispatch('selected', {
actionType,
});
};
</script>
<div
on:click={onButtonClicked}
class={`flex gap-4 place-items-center pl-5 py-3 rounded-tr-xl rounded-br-xl hover:bg-gray-200 hover:text-immich-primary hover:cursor-pointer
${isSelected && 'bg-immich-primary/10 text-immich-primary hover:bg-immich-primary/50'}
`}
>
<svelte:component this={logo} size="24" />
<p class="font-medium text-sm">{title}</p>
</div>

1
web/src/lib/constants.ts Normal file
View File

@@ -0,0 +1 @@
export const serverEndpoint = import.meta.env.VITE_SERVER_ENDPOINT

View File

@@ -0,0 +1,9 @@
export enum AdminSideBarSelection {
USER_MANAGEMENT = "User management",
}
export enum AppSideBarSelection {
PHOTOS = "Photos",
EXPLORE = "Explore",
}

View File

@@ -0,0 +1,7 @@
export type ImmichUser = {
id: string,
email: string,
firstName: string,
lastName: string,
isAdmin: boolean,
}

View File

@@ -0,0 +1,39 @@
<script lang="ts">
import { getRequest } from '$lib/api';
import { onDestroy } from 'svelte';
import { fade } from 'svelte/transition';
import '../app.css';
import { serverEndpoint } from '../lib/constants';
let endpoint = serverEndpoint;
let isServerOk = true;
const pingServerInterval = setInterval(async () => {
const response = await getRequest('server-info/ping', '');
if (response.res === 'pong') isServerOk = true;
if (response.statusCode === 404) isServerOk = false;
}, 10000);
onDestroy(() => clearInterval(pingServerInterval));
</script>
<main>
<slot />
</main>
<footer
class="text-sm fixed bottom-0 h-8 flex place-items-center place-content-center bg-immich-primary/10 w-screen font-mono gap-8 px-4 font-medium"
>
<p class="">
Server URL <span class="text-immich-primary font-bold">{endpoint}</span>
</p>
<p class="">
Server Status
{#if isServerOk}
<span class="text-immich-primary font-bold">OK</span>
{:else}
<span class="text-red-500 font-bold">OFFLINE</span>
{/if}
</p>
</footer>

View File

@@ -0,0 +1,44 @@
import type { RequestHandler } from '@sveltejs/kit';
import { serverEndpoint } from '$lib/constants';
export const post: RequestHandler = async ({ request, locals }) => {
const form = await request.formData();
const email = form.get('email')
const password = form.get('password')
const firstName = form.get('firstName')
const lastName = form.get('lastName')
const payload = {
email,
password,
firstName,
lastName,
}
const res = await fetch(`${serverEndpoint}/user`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${locals.user?.accessToken}`
},
body: JSON.stringify(payload),
})
if (res.status === 201) {
return {
status: 201,
body: {
success: 'Succesfully create user account'
}
}
} else {
return {
status: 400,
body: {
error: await res.json()
}
}
}
}

View File

@@ -0,0 +1,100 @@
<script context="module" lang="ts">
import type { Load } from '@sveltejs/kit';
import { getRequest } from '$lib/api';
export const load: Load = async ({ session, fetch }) => {
if (!session.user) {
return {
status: 302,
redirect: '/auth/login',
};
}
const usersOnServer = await getRequest('user', session.user.accessToken);
return {
status: 200,
props: {
user: session.user,
usersOnServer,
},
};
};
</script>
<script lang="ts">
import { onMount } from 'svelte';
import { session } from '$app/stores';
import type { ImmichUser } from '$lib/models/immich-user';
import { AdminSideBarSelection } from '$lib/models/admin-sidebar-selection';
import SideBarButton from '$lib/components/shared/side-bar-button.svelte';
import AccountMultipleOutline from 'svelte-material-icons/AccountMultipleOutline.svelte';
import NavigationBar from '$lib/components/shared/navigation-bar.svelte';
import UserManagement from '$lib/components/admin/user-management.svelte';
import FullScreenModal from '$lib/components/shared/full-screen-modal.svelte';
import CreateUserForm from '$lib/components/forms/create-user-form.svelte';
let selectedAction: AdminSideBarSelection;
export let user: ImmichUser;
export let usersOnServer: Array<ImmichUser>;
let shouldShowCreateUserForm: boolean;
const onButtonClicked = (buttonType: CustomEvent) => {
selectedAction = buttonType.detail['actionType'] as AdminSideBarSelection;
};
onMount(() => {
selectedAction = AdminSideBarSelection.USER_MANAGEMENT;
});
const onUserCreated = async () => {
if ($session.user) {
usersOnServer = await getRequest('user', $session.user.accessToken);
}
shouldShowCreateUserForm = false;
};
</script>
<svelte:head>
<title>Immich - Administration</title>
</svelte:head>
<NavigationBar {user} />
{#if shouldShowCreateUserForm}
<FullScreenModal on:clickOutside={() => (shouldShowCreateUserForm = false)}>
<div>
<CreateUserForm on:user-created={onUserCreated} />
</div>
</FullScreenModal>
{/if}
<section class="grid grid-cols-[250px_auto] relative pt-[72px] h-screen">
<section id="admin-sidebar" class="pt-8 pr-6">
<SideBarButton
title="User"
logo={AccountMultipleOutline}
actionType={AdminSideBarSelection.USER_MANAGEMENT}
isSelected={selectedAction === AdminSideBarSelection.USER_MANAGEMENT}
on:selected={onButtonClicked}
/>
</section>
<section class="overflow-y-auto relative">
<div id="setting-title" class="pt-10 fixed w-full z-50 bg-immich-bg">
<h1 class="text-lg ml-8 mb-4 text-immich-primary font-medium">{selectedAction}</h1>
<hr />
</div>
<section id="setting-content" class="relative pt-[85px] flex place-content-center">
<section class="w-[800px] pt-4">
{#if selectedAction === AdminSideBarSelection.USER_MANAGEMENT}
<UserManagement {usersOnServer} on:createUser={() => (shouldShowCreateUserForm = true)} />
{/if}
</section>
</section>
</section>
</section>

View File

@@ -0,0 +1,12 @@
import type { RequestHandler } from '@sveltejs/kit';
import { getRequest } from '../../../../lib/api';
export const get: RequestHandler = async ({ request, locals }) => {
const allUsers = await getRequest('user?isAll=true', locals.user!.accessToken)
return {
status: 200,
body: { allUsers }
};
}

View File

@@ -0,0 +1,52 @@
import type { RequestHandler } from '@sveltejs/kit';
import { putRequest } from '$lib/api';
import * as cookie from 'cookie';
export const post: RequestHandler = async ({ request, locals }) => {
const { id, isAdmin } = await request.json()
const res = await putRequest('user', {
id,
isAdmin,
}, locals.user!.accessToken);
if (res.statusCode) {
return {
status: res.statusCode,
body: JSON.stringify(res)
}
}
if (res.id == locals.user!.id) {
return {
status: 200,
body: { userInfo: res },
headers: {
'Set-Cookie': cookie.serialize('session', JSON.stringify(
{
id: res.id,
accessToken: locals.user!.accessToken,
firstName: res.firstName,
lastName: res.lastName,
isAdmin: res.isAdmin,
email: res.email,
}), {
path: '/',
httpOnly: true,
sameSite: 'strict',
maxAge: 60 * 60 * 24 * 30,
})
}
}
} else {
return {
status: 200,
body: { userInfo: { ...locals.user! } },
}
}
}

View File

@@ -0,0 +1,49 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { fade } from 'svelte/transition';
import LoginForm from '$lib/components/forms/login-form.svelte';
import UpdateForm from '../../../lib/components/forms/update-form.svelte';
import SelectAdminForm from '../../../lib/components/forms/select-admin-form.svelte';
let shouldShowUpdateForm = false;
let shouldShowSelectAdminForm = false;
const onLoginSuccess = async () => {
goto('/photos');
};
const onNeedUpdate = () => {
shouldShowUpdateForm = true;
shouldShowSelectAdminForm = false;
};
const onNeedSelectAdmin = () => {
shouldShowUpdateForm = false;
shouldShowSelectAdminForm = true;
};
</script>
<svelte:head>
<title>Immich - Login</title>
</svelte:head>
<section class="h-screen w-screen flex place-items-center place-content-center">
{#if !shouldShowUpdateForm && !shouldShowSelectAdminForm}
<div in:fade={{ duration: 100 }} out:fade={{ duration: 100 }}>
<LoginForm on:success={onLoginSuccess} on:need-update={onNeedUpdate} on:need-select-admin={onNeedSelectAdmin} />
</div>
{/if}
{#if shouldShowUpdateForm}
<div in:fade={{ duration: 100 }} out:fade={{ duration: 100 }}>
<UpdateForm on:success={onLoginSuccess} />
</div>
{/if}
{#if shouldShowSelectAdminForm}
<div in:fade={{ duration: 100 }} out:fade={{ duration: 100 }}>
<SelectAdminForm on:success={onLoginSuccess} />
</div>
{/if}
</section>

View File

@@ -0,0 +1,229 @@
import type { RequestHandler } from '@sveltejs/kit';
import { serverEndpoint } from '$lib/constants';
import * as cookie from 'cookie'
import { getRequest, putRequest } from '$lib/api';
type LoggedInUser = {
accessToken: string;
userId: string;
userEmail: string;
firstName: string;
lastName: string;
isAdmin: boolean;
}
export const post: RequestHandler = async ({ request }) => {
const form = await request.formData();
const email = form.get('email')
const password = form.get('password')
const payload = {
email,
password,
}
const res = await fetch(`${serverEndpoint}/auth/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(payload),
})
if (res.status === 201) {
// Login success
const loggedInUser = await res.json() as LoggedInUser;
/**
* Support legacy users with two scenario
*
* Scenario 1 - If one user exists on the server - make the user admin and ask for name.
* Scenario 2 - After assigned as admin, scenario 1 user not complete update form with names
* Scenario 3 - If two users exists on the server and no admin - ask to choose which one will be made admin
*/
// check how many user on the server
const { userCount } = await getRequest('user/count', '');
const { userCount: adminUserCount } = await getRequest('user/count?isAdmin=true', '')
/**
* Scenario 1 handler
*/
if (userCount == 1 && !loggedInUser.isAdmin) {
const updatedUser = await putRequest('user', {
id: loggedInUser.userId,
isAdmin: true
}, loggedInUser.accessToken)
/**
* Scenario 2 handler for current admin user
*/
let bodyResponse = { success: true, needUpdate: false }
if (loggedInUser.firstName == "" || loggedInUser.lastName == "") {
bodyResponse = { success: false, needUpdate: true }
}
return {
status: 200,
body: {
...bodyResponse,
user: {
id: updatedUser.userId,
accessToken: loggedInUser.accessToken,
firstName: updatedUser.firstName,
lastName: updatedUser.lastName,
isAdmin: updatedUser.isAdmin,
email: updatedUser.email,
},
},
headers: {
'Set-Cookie': cookie.serialize('session', JSON.stringify(
{
id: updatedUser.userId,
accessToken: loggedInUser.accessToken,
firstName: updatedUser.firstName,
lastName: updatedUser.lastName,
isAdmin: updatedUser.isAdmin,
email: updatedUser.email,
}), {
path: '/',
httpOnly: true,
sameSite: 'strict',
maxAge: 60 * 60 * 24 * 30,
})
}
}
}
/**
* Scenario 3 handler
*/
if (userCount >= 2 && adminUserCount == 0) {
return {
status: 200,
body: {
needSelectAdmin: true,
user: {
id: loggedInUser.userId,
accessToken: loggedInUser.accessToken,
firstName: loggedInUser.firstName,
lastName: loggedInUser.lastName,
isAdmin: loggedInUser.isAdmin,
email: loggedInUser.userEmail
},
success: 'success'
},
headers: {
'Set-Cookie': cookie.serialize('session', JSON.stringify(
{
id: loggedInUser.userId,
accessToken: loggedInUser.accessToken,
firstName: loggedInUser.firstName,
lastName: loggedInUser.lastName,
isAdmin: loggedInUser.isAdmin,
email: loggedInUser.userEmail
}), {
path: '/',
httpOnly: true,
sameSite: 'strict',
maxAge: 60 * 60 * 24 * 30,
})
}
}
}
/**
* Scenario 2 handler
*/
if (loggedInUser.firstName == "" || loggedInUser.lastName == "") {
return {
status: 200,
body: {
needUpdate: true,
user: {
id: loggedInUser.userId,
accessToken: loggedInUser.accessToken,
firstName: loggedInUser.firstName,
lastName: loggedInUser.lastName,
isAdmin: loggedInUser.isAdmin,
email: loggedInUser.userEmail
},
},
headers: {
'Set-Cookie': cookie.serialize('session', JSON.stringify(
{
id: loggedInUser.userId,
accessToken: loggedInUser.accessToken,
firstName: loggedInUser.firstName,
lastName: loggedInUser.lastName,
isAdmin: loggedInUser.isAdmin,
email: loggedInUser.userEmail
}), {
path: '/',
httpOnly: true,
sameSite: 'strict',
maxAge: 60 * 60 * 24 * 30,
})
}
}
}
return {
status: 200,
body: {
user: {
id: loggedInUser.userId,
accessToken: loggedInUser.accessToken,
firstName: loggedInUser.firstName,
lastName: loggedInUser.lastName,
isAdmin: loggedInUser.isAdmin,
email: loggedInUser.userEmail
},
success: 'success'
},
headers: {
'Set-Cookie': cookie.serialize('session', JSON.stringify(
{
id: loggedInUser.userId,
accessToken: loggedInUser.accessToken,
firstName: loggedInUser.firstName,
lastName: loggedInUser.lastName,
isAdmin: loggedInUser.isAdmin,
email: loggedInUser.userEmail,
}), {
// send cookie for every page
path: '/',
// server side only cookie so you can't use `document.cookie`
httpOnly: true,
// only requests from same site can send cookies
// and serves to protect from CSRF
// https://developer.mozilla.org/en-US/docs/Glossary/CSRF
sameSite: 'strict',
// set cookie to expire after a month
maxAge: 60 * 60 * 24 * 30,
})
}
}
} else {
return {
status: 400,
body: {
error: 'Incorrect email or password'
}
}
}
}

View File

@@ -0,0 +1,63 @@
import type { RequestHandler } from '@sveltejs/kit';
import { putRequest } from '../../../lib/api';
import * as cookie from 'cookie'
export const post: RequestHandler = async ({ request, locals }) => {
const form = await request.formData();
const firstName = form.get('firstName')
const lastName = form.get('lastName')
if (locals.user) {
const updatedUser = await putRequest('user', {
id: locals.user.id,
firstName,
lastName
}, locals.user.accessToken)
return {
status: 200,
body: {
user: {
id: updatedUser.id,
accessToken: locals.user.accessToken,
firstName: updatedUser.firstName,
lastName: updatedUser.lastName,
isAdmin: updatedUser.isAdmin,
email: updatedUser.email,
},
success: 'Update user success'
},
headers: {
'Set-Cookie': cookie.serialize('session', JSON.stringify(
{
id: updatedUser.id,
accessToken: locals.user.accessToken,
firstName: updatedUser.firstName,
lastName: updatedUser.lastName,
isAdmin: updatedUser.isAdmin,
email: updatedUser.email,
}), {
path: '/',
httpOnly: true,
sameSite: 'strict',
maxAge: 60 * 60 * 24 * 30,
})
}
}
}
return {
status: 400,
body: {
error: 'Cannot get access token from cookies'
}
}
}

View File

@@ -0,0 +1,39 @@
<script context="module" lang="ts">
import type { Load } from '@sveltejs/kit';
import { serverEndpoint } from '$lib/constants';
export const load: Load = async ({ session, fetch }) => {
const res = await fetch(`${serverEndpoint}/user/count`);
const { userCount } = await res.json();
if (userCount != 0) {
// Admin has been registered, redirect to login
if (!session.user) {
return {
status: 302,
redirect: '/auth/login',
};
} else {
return {
status: 302,
redirect: '/dashboard',
};
}
}
return {};
};
</script>
<script lang="ts">
import AdminRegistrationForm from '$lib/components/forms/admin-registration-form.svelte';
</script>
<svelte:head>
<title>Immich - Admin Registration</title>
</svelte:head>
<section class="h-screen w-screen flex place-items-center place-content-center">
<AdminRegistrationForm />
</section>

View File

@@ -0,0 +1,43 @@
import type { RequestHandler } from '@sveltejs/kit';
import { serverEndpoint } from '$lib/constants';
export const post: RequestHandler = async ({ request }) => {
const form = await request.formData();
const email = form.get('email')
const password = form.get('password')
const firstName = form.get('firstName')
const lastName = form.get('lastName')
const payload = {
email,
password,
firstName,
lastName,
}
const res = await fetch(`${serverEndpoint}/auth/admin-sign-up`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(payload),
})
if (res.status === 201) {
return {
status: 201,
body: {
success: 'Succesfully create admin account'
}
}
} else {
return {
status: 400,
body: {
error: await res.json()
}
}
}
}

View File

@@ -0,0 +1,62 @@
<script context="module" lang="ts">
export const prerender = false;
import type { Load } from '@sveltejs/kit';
export const load: Load = async ({ session, fetch }) => {
const res = await fetch(`${serverEndpoint}/user/count`);
const { userCount } = await res.json();
if (!session.user) {
// Check if admin exist to wherether navigating to login or registration
if (userCount != 0) {
return {
status: 200,
props: {
isAdminUserExist: true,
},
};
} else {
return {
status: 200,
props: {
isAdminUserExist: false,
},
};
}
} else {
return {
status: 302,
redirect: '/photos',
};
}
};
</script>
<script lang="ts">
import { serverEndpoint } from '$lib/constants';
import { goto } from '$app/navigation';
export let isAdminUserExist: boolean;
async function onGettingStartedClicked() {
isAdminUserExist ? goto('/auth/login') : goto('/auth/register');
}
</script>
<svelte:head>
<title>Immich - Welcome 🎉</title>
<meta name="description" content="Immich Web Interface" />
</svelte:head>
<section class="h-screen w-screen flex place-items-center place-content-center">
<div class="flex flex-col place-items-center gap-8 text-center max-w-[350px]">
<div class="flex place-items-center place-content-center ">
<img class="text-center" src="immich-logo.svg" height="200" width="200" alt="immich-logo" />
</div>
<h1 class="text-4xl text-immich-primary font-bold font-immich-title">Welcome to Immich Web</h1>
<button
class="border px-4 py-2 rounded-md bg-immich-primary hover:bg-immich-primary/75 text-white font-bold w-[200px]"
on:click={onGettingStartedClicked}>Getting Started</button
>
</div>
</section>

View File

@@ -0,0 +1,75 @@
<script context="module" lang="ts">
import type { Load } from '@sveltejs/kit';
export const load: Load = ({ session }) => {
if (!session.user) {
return {
status: 302,
redirect: '/auth/login',
};
}
return {
status: 200,
props: {
user: session.user,
},
};
};
</script>
<script lang="ts">
import type { ImmichUser } from '$lib/models/immich-user';
import NavigationBar from '../../lib/components/shared/navigation-bar.svelte';
import SideBarButton from '$lib/components/shared/side-bar-button.svelte';
import Magnify from 'svelte-material-icons/Magnify.svelte';
import ImageOutline from 'svelte-material-icons/ImageOutline.svelte';
import { AppSideBarSelection } from '$lib/models/admin-sidebar-selection';
import { onMount } from 'svelte';
export let user: ImmichUser;
let selectedAction: AppSideBarSelection;
const onButtonClicked = (buttonType: CustomEvent) => {
selectedAction = buttonType.detail['actionType'] as AppSideBarSelection;
};
onMount(() => {
selectedAction = AppSideBarSelection.PHOTOS;
});
</script>
<svelte:head>
<title>Immich - Photos</title>
</svelte:head>
<section>
<NavigationBar {user} />
</section>
<section class="grid grid-cols-[250px_auto] relative pt-[72px] h-screen">
<section id="admin-sidebar" class="flex flex-col gap-4 pt-8 pr-6">
<SideBarButton
title="Photos"
logo={ImageOutline}
actionType={AppSideBarSelection.PHOTOS}
isSelected={selectedAction === AppSideBarSelection.PHOTOS}
on:selected={onButtonClicked}
/>
<SideBarButton
title="Explore"
logo={Magnify}
actionType={AppSideBarSelection.EXPLORE}
isSelected={selectedAction === AppSideBarSelection.EXPLORE}
on:selected={onButtonClicked}
/>
</section>
<section class="overflow-y-auto relative">
<section id="setting-content" class="relative pt-[85px]">
<section class="pt-4">Coming soon</section>
</section>
</section>
</section>