Some checks failed
ci / ci (22, ubuntu-latest) (push) Failing after 6m46s
57 lines
1.8 KiB
TypeScript
57 lines
1.8 KiB
TypeScript
import type { AuthProviderInfo, AuthModel } from 'pocketbase';
|
|
import { usePocketbase } from './usePocketbase';
|
|
|
|
export const useAuth = () => {
|
|
const pb = usePocketbase();
|
|
const router = useRouter();
|
|
|
|
const userCollection = 'users';
|
|
|
|
const user = ref<AuthModel | null>(null);
|
|
const isAuthenticated = computed<boolean>(() => pb.authStore.isValid && !!user.value);
|
|
const loading = ref<boolean>(false);
|
|
const error = ref<Error | null>(null);
|
|
|
|
const initAuth = async () => {
|
|
user.value = pb.authStore.record;
|
|
pb.authStore.onChange((_token, model) => (user.value = model));
|
|
};
|
|
|
|
const authProviders = async (): Promise<AuthProviderInfo[]> => {
|
|
const authMethods = await pb.collection(userCollection).listAuthMethods();
|
|
return authMethods.oauth2.enabled ? authMethods.oauth2.providers : [];
|
|
};
|
|
|
|
const login = async (provider: string) => {
|
|
loading.value = true;
|
|
error.value = null;
|
|
try {
|
|
const providers = await authProviders();
|
|
const providerData = providers.find((p) => p.name === provider);
|
|
if (!providerData) {
|
|
throw new Error(`${provider} OAuth is not configured`);
|
|
}
|
|
await pb.collection(userCollection).authWithOAuth2({ provider });
|
|
} catch (pbError) {
|
|
error.value = pbError as Error;
|
|
} finally {
|
|
loading.value = false;
|
|
}
|
|
};
|
|
|
|
const refreshAuth = async () => await pb.collection(userCollection).authRefresh();
|
|
|
|
const handleOAuthCallback = async () => {
|
|
user.value = pb.authStore.record;
|
|
if (isAuthenticated.value) {
|
|
await router.push('/dashboard');
|
|
} else {
|
|
await router.push('/');
|
|
}
|
|
};
|
|
|
|
const logout = () => pb.authStore.clear();
|
|
|
|
return { user, loading, error, isAuthenticated, login, logout, initAuth, refreshAuth, handleOAuthCallback };
|
|
};
|