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 0fc6d69824
feat(server): user preferences (#9736)
* refactor(server): user endpoints

* feat(server): user preferences

* mobile: user preference

* wording

---------

Co-authored-by: Alex <alex.tran1502@gmail.com>
2024-05-28 09:16:53 +07:00

66 lines
1.5 KiB
TypeScript

import { browser } from '$app/environment';
import { serverInfo } from '$lib/stores/server-info.store';
import { preferences as preferences$, user as user$ } from '$lib/stores/user.store';
import { getMyPreferences, getMyUser, getStorage } 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 user = get(user$);
let preferences = get(preferences$);
if ((!user || !preferences) && hasAuthCookie()) {
[user, preferences] = await Promise.all([getMyUser(), getMyPreferences()]);
user$.set(user);
preferences$.set(preferences);
}
return user;
} 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 getStorage();
serverInfo.set(data);
}
};