2023-11-17 23:13:36 -05:00
|
|
|
import { api } from '@api';
|
|
|
|
import { redirect } from '@sveltejs/kit';
|
|
|
|
import { AppRoute } from '../constants';
|
2023-12-12 03:35:57 +01:00
|
|
|
import { getSavedUser, setUser } from '$lib/stores/user.store';
|
2023-11-17 23:13:36 -05:00
|
|
|
|
|
|
|
export interface AuthOptions {
|
|
|
|
admin?: true;
|
|
|
|
}
|
|
|
|
|
|
|
|
export const getAuthUser = async () => {
|
|
|
|
try {
|
|
|
|
const { data: user } = await api.userApi.getMyUserInfo();
|
|
|
|
return user;
|
|
|
|
} catch {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
// TODO: re-use already loaded user (once) instead of fetching on each page navigation
|
|
|
|
export const authenticate = async (options?: AuthOptions) => {
|
|
|
|
options = options || {};
|
|
|
|
|
2023-12-12 03:35:57 +01:00
|
|
|
const savedUser = getSavedUser();
|
|
|
|
const user = savedUser || (await getAuthUser());
|
|
|
|
|
2023-11-17 23:13:36 -05:00
|
|
|
if (!user) {
|
|
|
|
throw redirect(302, AppRoute.AUTH_LOGIN);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (options.admin && !user.isAdmin) {
|
|
|
|
throw redirect(302, AppRoute.PHOTOS);
|
|
|
|
}
|
|
|
|
|
2023-12-12 03:35:57 +01:00
|
|
|
if (!savedUser) {
|
|
|
|
setUser(user);
|
|
|
|
}
|
|
|
|
|
2023-11-17 23:13:36 -05:00
|
|
|
return user;
|
|
|
|
};
|
|
|
|
|
|
|
|
export const isLoggedIn = async () => getAuthUser().then((user) => !!user);
|