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-02-13 02:47:26 +01:00
|
|
|
import { user } from '$lib/stores/user.store';
|
2024-02-13 23:07:37 +01:00
|
|
|
import { getMyUserInfo, getServerInfo } from '@immich/sdk';
|
|
|
|
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-02-13 02:47:26 +01:00
|
|
|
let loaded = get(user);
|
|
|
|
if (!loaded && hasAuthCookie()) {
|
2024-02-13 23:07:37 +01:00
|
|
|
loaded = await getMyUserInfo();
|
2024-02-13 02:47:26 +01:00
|
|
|
user.set(loaded);
|
|
|
|
}
|
|
|
|
return loaded;
|
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-02-13 02:47:26 +01:00
|
|
|
if (get(user)) {
|
2024-02-13 23:07:37 +01:00
|
|
|
const data = await getServerInfo();
|
2024-01-30 18:21:45 +01:00
|
|
|
serverInfo.set(data);
|
|
|
|
}
|
|
|
|
};
|