2024-02-13 02:47:26 +01:00
|
|
|
import { browser } from '$app/environment';
|
2024-02-13 23:07:37 +01:00
|
|
|
import { serverInfo } from '$lib/stores/server-info.store';
|
2024-05-28 04:16:53 +02:00
|
|
|
import { preferences as preferences$, user as user$ } from '$lib/stores/user.store';
|
|
|
|
import { getMyPreferences, getMyUser, getStorage } from '@immich/sdk';
|
2024-02-13 23:07:37 +01:00
|
|
|
import { redirect } from '@sveltejs/kit';
|
|
|
|
import { get } from 'svelte/store';
|
|
|
|
import { AppRoute } from '../constants';
|
2023-11-18 05:13:36 +01:00
|
|
|
|
|
|
|
export interface AuthOptions {
|
|
|
|
admin?: true;
|
2024-02-13 02:47:26 +01:00
|
|
|
public?: true;
|
2023-11-18 05:13:36 +01:00
|
|
|
}
|
|
|
|
|
2024-02-13 02:47:26 +01:00
|
|
|
export const loadUser = async () => {
|
2023-11-18 05:13:36 +01:00
|
|
|
try {
|
2024-05-28 04:16:53 +02:00
|
|
|
let user = get(user$);
|
|
|
|
let preferences = get(preferences$);
|
|
|
|
if ((!user || !preferences) && hasAuthCookie()) {
|
|
|
|
[user, preferences] = await Promise.all([getMyUser(), getMyPreferences()]);
|
|
|
|
user$.set(user);
|
|
|
|
preferences$.set(preferences);
|
2024-02-13 02:47:26 +01:00
|
|
|
}
|
2024-05-28 04:16:53 +02:00
|
|
|
return user;
|
2023-11-18 05:13:36 +01:00
|
|
|
} catch {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2024-02-13 02:47:26 +01:00
|
|
|
const hasAuthCookie = (): boolean => {
|
|
|
|
if (!browser) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
for (const cookie of document.cookie.split('; ')) {
|
|
|
|
const [name] = cookie.split('=');
|
|
|
|
if (name === 'immich_is_authenticated') {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
};
|
|
|
|
|
2023-11-18 05:13:36 +01:00
|
|
|
export const authenticate = async (options?: AuthOptions) => {
|
2024-02-13 02:47:26 +01:00
|
|
|
const { public: publicRoute, admin: adminRoute } = options || {};
|
|
|
|
const user = await loadUser();
|
2023-11-18 05:13:36 +01:00
|
|
|
|
2024-02-13 02:47:26 +01:00
|
|
|
if (publicRoute) {
|
|
|
|
return;
|
|
|
|
}
|
2023-12-12 03:35:57 +01:00
|
|
|
|
2023-11-18 05:13:36 +01:00
|
|
|
if (!user) {
|
2024-01-20 19:47:41 +01:00
|
|
|
redirect(302, AppRoute.AUTH_LOGIN);
|
2023-11-18 05:13:36 +01:00
|
|
|
}
|
|
|
|
|
2024-02-13 02:47:26 +01:00
|
|
|
if (adminRoute && !user.isAdmin) {
|
2024-01-20 19:47:41 +01:00
|
|
|
redirect(302, AppRoute.PHOTOS);
|
2023-11-18 05:13:36 +01:00
|
|
|
}
|
2023-12-12 17:35:28 +01:00
|
|
|
};
|
2023-12-12 03:35:57 +01:00
|
|
|
|
2024-01-30 18:21:45 +01:00
|
|
|
export const requestServerInfo = async () => {
|
2024-05-28 04:16:53 +02:00
|
|
|
if (get(user$)) {
|
2024-05-22 11:25:55 +02:00
|
|
|
const data = await getStorage();
|
2024-01-30 18:21:45 +01:00
|
|
|
serverInfo.set(data);
|
|
|
|
}
|
|
|
|
};
|