opnform-host-nginx/client/composables/useOpnApi.js

89 lines
2.5 KiB
JavaScript
Raw Normal View History

import { getDomain, getHost, customDomainUsed } from "~/lib/utils.js"
2023-12-16 19:21:03 +01:00
function addAuthHeader(request, options) {
const authStore = useAuthStore()
if (authStore.token) {
options.headers = {
Authorization: `Bearer ${authStore.token}`,
...options.headers,
}
2023-12-16 19:21:03 +01:00
}
}
function addPasswordToFormRequest(request, options) {
if (!request || !request.startsWith("/forms/")) return
2024-01-16 13:27:54 +01:00
const slug = request.split("/")[2]
2023-12-16 19:21:03 +01:00
const passwordCookie = useCookie("password-" + slug, {
maxAge: 60 * 60 * 24 * 30,
}) // 30 days
if (slug !== undefined && slug !== "" && passwordCookie.value !== undefined) {
options.headers["form-password"] = passwordCookie.value
2023-12-16 19:21:03 +01:00
}
}
2024-01-12 15:43:28 +01:00
/**
* Add custom domain header if custom domain is used
*/
function addCustomDomainHeader(request, options) {
if (!customDomainUsed()) return
options.headers["x-custom-domain"] = getDomain(getHost())
2024-01-12 15:43:28 +01:00
}
2023-12-16 19:21:03 +01:00
export function getOpnRequestsOptions(request, opts) {
const config = useRuntimeConfig()
2024-01-13 18:17:24 +01:00
if (opts.body && opts.body instanceof FormData) {
opts.headers = {
charset: "utf-8",
2024-01-13 18:17:24 +01:00
...opts.headers,
}
}
opts.headers = { accept: "application/json", ...opts.headers }
2023-12-16 19:21:03 +01:00
// Authenticate requests coming from the server
if (import.meta.server && config.apiSecret) {
opts.headers["x-api-secret"] = config.apiSecret
}
2023-12-16 19:21:03 +01:00
addAuthHeader(request, opts)
addPasswordToFormRequest(request, opts)
2024-01-12 15:43:28 +01:00
addCustomDomainHeader(request, opts)
2023-12-16 19:21:03 +01:00
if (!opts.baseURL) opts.baseURL = config.privateApiBase || config.public.apiBase
2024-01-13 19:57:39 +01:00
2023-12-16 19:21:03 +01:00
return {
async onResponseError({ response }) {
2023-12-16 19:21:03 +01:00
const authStore = useAuthStore()
const { status } = response
2024-01-12 15:43:28 +01:00
if (status === 401) {
if (authStore.check) {
console.log("Logging out due to 401")
authStore.logout()
Re-login modal (#717) * Implement quick login/register flow with global event handling - Add QuickRegister component with improved modal management - Integrate quick login/register with app store state - Implement custom event handling for login/registration flow - Update OAuth callback to support quick login in popup windows - Refactor authentication-related components to use global events * Refactor authentication flow with centralized useAuth composable - Create new useAuth composable to centralize login, registration, and social login logic - Simplify authentication methods in LoginForm and RegisterForm - Add event-based login/registration flow with quick login support - Remove redundant API calls and consolidate authentication processes - Improve error handling and analytics tracking for authentication events * Enhance QuickRegister and RegisterForm components with unauthorized error handling - Add closeable functionality to modals based on unauthorized error state - Implement logout button in QuickRegister for unauthorized users - Reset unauthorized error state on component unmount - Update styling for "OR" text in RegisterForm for consistency - Set unauthorized error flag in app store upon 401 response in API calls * Refactor Authentication Flow and Remove Unused Callback Views - Deleted unused callback views for Notion and OAuth to streamline the codebase. - Updated QuickRegister and LoginForm components to remove the after-login event emission, replacing it with a window message system for better communication between components. - Enhanced the RegisterForm and other components to utilize the new window message system for handling login completion, improving reliability and maintainability. - Added a verifyAuthentication method in the useAuth composable to ensure user data is loaded correctly after social logins, including retry logic for fetching user data. These changes aim to simplify the authentication process and improve the overall user experience by ensuring a more robust handling of login events. * Add eslint-disable comment to useWindowMessage composable for linting control * Refactor QuickRegister.vue for improved template structure and clarity - Adjusted the rendering of horizontal dividers and the "or" text for better semantic HTML. - Added a compact-header prop to the modal for enhanced layout control. These changes aim to enhance the readability and maintainability of the QuickRegister component. --------- Co-authored-by: Julien Nahum <julien@nahum.net>
2025-03-25 10:41:11 +01:00
useAppStore().isUnauthorizedError = true
useAppStore().quickLoginModal = true
2024-01-12 15:43:28 +01:00
}
} else if (status === 420) {
// If invalid domain, redirect to main domain
console.warn("Invalid response from back-end - redirecting to main domain")
window.location.href =
config.public.appUrl + "?utm_source=failed_custom_domain_redirect"
} else if (status >= 500) {
console.error("Request error", status)
2023-12-16 19:21:03 +01:00
}
},
...opts,
2023-12-16 19:21:03 +01:00
}
}
export const opnFetch = (request, opts = {}) => {
return $fetch(request, getOpnRequestsOptions(request, opts))
}
2023-12-16 19:21:03 +01:00
export const useOpnApi = (request, opts = {}) => {
return useFetch(request, getOpnRequestsOptions(request, opts))
}