@xsprtd/nuxt-api
Version:
Nuxt API Authentication and Http Client
86 lines (85 loc) • 2.48 kB
JavaScript
import { computed } from "vue";
import { useHttp } from "../composables/useHttp.js";
import { useApiOptions } from "../composables/useApiOptions.js";
import { useCurrentUser } from "../composables/useCurrentUser.js";
import { getAuthUser } from "../services/getAuthUser.js";
import extractNestedValue from "../helpers/extractNestedValue.js";
import { useTokenStorage } from "./useTokenStorage.js";
import { navigateTo, useRoute } from "#app";
export const useAuth = () => {
const options = useApiOptions();
const { post, processing, errorBag } = useHttp();
const user = useCurrentUser();
const isLoggedIn = computed(() => {
return user.value !== null;
});
const refreshUser = async () => {
try {
user.value = await getAuthUser();
} catch (error) {
user.value = null;
console.debug(error);
}
};
const login = async (credentials, clientOptions = {}, callback) => {
const { redirect, authMode, endpoints } = options;
const currentRoute = useRoute();
if (isLoggedIn.value) {
if (!redirect.postLogin || redirect.postLogin === currentRoute.path) {
return;
}
return navigateTo(redirect.postLogin);
}
const response = await post(
endpoints.login,
credentials,
clientOptions
);
if (authMode === "token") {
const { token } = options;
const tokenValue = extractNestedValue(
response,
token.responseKey
);
await useTokenStorage().set(tokenValue);
}
await refreshUser();
if (callback) {
return callback(response, user.value);
}
if (redirect.intendedEnabled) {
const requestedRoute = currentRoute.query.redirect;
if (requestedRoute && requestedRoute !== currentRoute.path) {
return navigateTo(requestedRoute);
}
}
if (!redirect.postLogin || currentRoute.path === redirect.postLogin) {
return;
}
return navigateTo(redirect.postLogin);
};
const logout = async (callback) => {
if (!isLoggedIn.value) {
return;
}
await post(options.endpoints.logout);
user.value = null;
if (callback) {
return callback();
}
const currentPath = useRoute().path;
if (!options.redirect.postLogout || currentPath === options.redirect.postLogout) {
return;
}
await navigateTo(options.redirect.postLogout);
};
return {
user,
isLoggedIn,
refreshUser,
login,
logout,
processing,
errorBag
};
};