1
0
Fork 0
mirror of https://github.com/immich-app/immich.git synced 2025-01-10 13:56:47 +01:00
immich/web/src/lib/utils/auth.ts
Jason Rasmussen 8fd94211c0
refactor(web): use new open api client (#7097)
* refactor(web): use new open api client

* refactor: remove activity api

* refactor: trash, oauth, and partner apis

* refactor: job api

* refactor: face, library, system config

* refactor: user api

* refactor: album api
2024-02-13 17:07:37 -05:00

64 lines
1.4 KiB
TypeScript

import { browser } from '$app/environment';
import { serverInfo } from '$lib/stores/server-info.store';
import { user } from '$lib/stores/user.store';
import { getMyUserInfo, getServerInfo } from '@immich/sdk';
import { redirect } from '@sveltejs/kit';
import { get } from 'svelte/store';
import { AppRoute } from '../constants';
export interface AuthOptions {
admin?: true;
public?: true;
}
export const loadUser = async () => {
try {
let loaded = get(user);
if (!loaded && hasAuthCookie()) {
loaded = await getMyUserInfo();
user.set(loaded);
}
return loaded;
} catch {
return null;
}
};
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;
};
export const authenticate = async (options?: AuthOptions) => {
const { public: publicRoute, admin: adminRoute } = options || {};
const user = await loadUser();
if (publicRoute) {
return;
}
if (!user) {
redirect(302, AppRoute.AUTH_LOGIN);
}
if (adminRoute && !user.isAdmin) {
redirect(302, AppRoute.PHOTOS);
}
};
export const requestServerInfo = async () => {
if (get(user)) {
const data = await getServerInfo();
serverInfo.set(data);
}
};