diff --git a/wp-content/themes/ccat/app/composables/useAuth.ts b/wp-content/themes/ccat/app/composables/useAuth.ts index 8ee0159..fceaab6 100644 --- a/wp-content/themes/ccat/app/composables/useAuth.ts +++ b/wp-content/themes/ccat/app/composables/useAuth.ts @@ -22,11 +22,12 @@ export function useAuth() { required: true, }, ]; - async function onLoginSubmit({ data }: FormSubmitEvent) { + async function onLoginSubmit({ data: args }: FormSubmitEvent) { try { - const result = await $fetch<{ success: boolean; message?: string }>("/api/login", { method: "POST", body: data }); - if (!result.success) { - throw new Error(result.message || "Une erreur est survenue."); + const { data, errors } = await useGraphqlMutation("login", args); + if (errors.length || !data.login) { + console.error(errors); + throw new Error("Une erreur est survenue."); } await router.push(redirect); await refreshUserSession(); diff --git a/wp-content/themes/ccat/app/composables/useUserSwitching.ts b/wp-content/themes/ccat/app/composables/useUserSwitching.ts index be5ef1c..739e8b1 100644 --- a/wp-content/themes/ccat/app/composables/useUserSwitching.ts +++ b/wp-content/themes/ccat/app/composables/useUserSwitching.ts @@ -7,40 +7,29 @@ export function useUserSwitching() { async function userSwitchTo(userId: string | number) { try { - const result = await $fetch<{ success: boolean; message?: string }>("/api/switch-to", { - method: "POST", - body: { userId }, - }); - - if (!result.success) { - throw new Error(result.message || "Switch failed"); + const { data, errors } = await useGraphqlMutation("userSwitchTo", { userId }); + if (errors.length || !data.userSwitchTo) { + throw new Error("Une erreur est survenue"); } - await refreshUserSession(); - return result; } catch (error) { - const message = error instanceof Error ? error.message : "Switch failed"; + const message = error instanceof Error ? error.message : "Une erreur est survenue"; toast.add({ title: "Échec du changement d'utilisateur", description: message, color: "error" }); - throw error; } } async function userSwitchBack() { try { - const result = await $fetch<{ success: boolean; message?: string }>("/api/switch-back", { - method: "POST", - }); + const result = await $fetch("/api/switch-back", { method: "POST" }); if (!result.success) { - throw new Error(result.message || "Échec du retour à l'utilisateur précédent"); + throw new Error("Une erreur est survenue."); } await refreshUserSession(); - return result; } catch (error) { - const message = error instanceof Error ? error.message : "Échec du retour à l'utilisateur précédent"; + const message = error instanceof Error ? error.message : "Une erreur est survenue"; toast.add({ title: "Échec du changement d'utilisateur", description: message, color: "error" }); - throw error; } } diff --git a/wp-content/themes/ccat/server/graphql/login.gql b/wp-content/themes/ccat/app/graphql/login.gql similarity index 100% rename from wp-content/themes/ccat/server/graphql/login.gql rename to wp-content/themes/ccat/app/graphql/login.gql diff --git a/wp-content/themes/ccat/server/graphql/userSwitchTo.gql b/wp-content/themes/ccat/app/graphql/userSwitchTo.gql similarity index 100% rename from wp-content/themes/ccat/server/graphql/userSwitchTo.gql rename to wp-content/themes/ccat/app/graphql/userSwitchTo.gql diff --git a/wp-content/themes/ccat/includes/graphql/user-switching.php b/wp-content/themes/ccat/includes/graphql/user-switching.php index 0376416..298ac86 100644 --- a/wp-content/themes/ccat/includes/graphql/user-switching.php +++ b/wp-content/themes/ccat/includes/graphql/user-switching.php @@ -78,26 +78,3 @@ function ccat_graphql_switch_to_mutation( $input ) { 'user' => \WPGraphQL::get_app_context()->get_loader( 'user' )->load_deferred( $target_user->ID ), ); } - -// Register userSwitchBack mutation -add_action( 'graphql_register_types', 'ccat_graphql_register_user_switch_back' ); -function ccat_graphql_register_user_switch_back() { - register_graphql_mutation( - 'userSwitchBack', - array( - 'inputFields' => array(), - 'outputFields' => array( - 'success' => array( - 'type' => 'Boolean', - 'description' => esc_html__( 'Whether switching back was successful', 'ccat' ), - ), - ), - 'mutateAndGetPayload' => 'ccat_graphql_switch_back_mutation', - ) - ); -} - -// Callback for userSwitchBack mutation -function ccat_graphql_switch_back_mutation() { - return array( 'success' => true ); -} diff --git a/wp-content/themes/ccat/server/api/login.post.ts b/wp-content/themes/ccat/server/api/login.post.ts deleted file mode 100644 index 97ae0e0..0000000 --- a/wp-content/themes/ccat/server/api/login.post.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { defineEventHandler, readBody } from "h3"; - -export default defineEventHandler(async (event) => { - const { email, password } = await readBody(event); - try { - const response = await useGraphqlMutation("login", { email, password }); - if (response.errors.length) { - throw new Error(response.errors[0]?.message); - } - if (!response.data.login) { - throw new Error("Login failed: Invalid credentials"); - } - const { authToken, refreshToken, user } = response.data.login; - await setUserSession(event, { - user, - secure: { authToken, refreshToken }, - loggedInAt: new Date().toISOString(), - }); - return { success: true }; - } - catch (error) { - const messages: Record = { - invalid_email: "Courriel et/ou mot de passe invalide(s).", - incorrect_password: "Courriel et/ou mot de passe invalide(s).", - }; - const message = error instanceof Error && messages[error.message] ? messages[error.message] : "Une erreur est survenue."; - return { success: false, message }; - } -}); diff --git a/wp-content/themes/ccat/server/api/switch-back.post.ts b/wp-content/themes/ccat/server/api/switch-back.post.ts index 0ce8f08..e88e221 100644 --- a/wp-content/themes/ccat/server/api/switch-back.post.ts +++ b/wp-content/themes/ccat/server/api/switch-back.post.ts @@ -2,15 +2,12 @@ import { defineEventHandler } from "h3"; export default defineEventHandler(async (event) => { try { - const response = await useGraphqlMutation("userSwitchBack"); - if (response.errors?.length) { - throw new Error(response.errors[0]?.message); - } + // TODO: Switch back to the previous user. await clearUserSession(event); return { success: true }; } catch (error) { - const message = error instanceof Error ? error.message : "Échec du retour à l'utilisateur précédent"; + const message = error instanceof Error ? error.message : "Une erreur est survenue."; return { success: false, message }; } }); diff --git a/wp-content/themes/ccat/server/api/switch-to.post.ts b/wp-content/themes/ccat/server/api/switch-to.post.ts deleted file mode 100644 index 50d13ae..0000000 --- a/wp-content/themes/ccat/server/api/switch-to.post.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { defineEventHandler, readBody } from "h3"; - -export default defineEventHandler(async (event) => { - const { userId } = await readBody(event); - try { - const currentSession = await getUserSession(event); - if (!currentSession?.user) { - throw new Error("Authentication requise"); - } - const response = await useGraphqlMutation("userSwitchTo", { userId }); - if (response.errors?.length) { - throw new Error(response.errors[0]?.message); - } - if (!response.data.userSwitchTo) { - throw new Error("Le changement d'utilisateur a échoué"); - } - const { authToken, refreshToken, user } = response.data.userSwitchTo; - await setUserSession(event, { - user, - secure: { authToken, refreshToken }, - loggedInAt: new Date().toISOString(), - switchedBy: currentSession.user.id, - }); - return { success: true }; - } - catch (error) { - const message = error instanceof Error ? error.message : "Le changement d'utilisateur a échoué"; - return { success: false, message }; - } -}); diff --git a/wp-content/themes/ccat/server/graphql/userSwitchBack.gql b/wp-content/themes/ccat/server/graphql/userSwitchBack.gql deleted file mode 100644 index b5c4e58..0000000 --- a/wp-content/themes/ccat/server/graphql/userSwitchBack.gql +++ /dev/null @@ -1,5 +0,0 @@ -mutation userSwitchBack { - userSwitchBack(input: {}) { - success - } -} \ No newline at end of file diff --git a/wp-content/themes/ccat/server/graphqlMiddleware.serverOptions.ts b/wp-content/themes/ccat/server/graphqlMiddleware.serverOptions.ts index 300cd3e..c753f4d 100644 --- a/wp-content/themes/ccat/server/graphqlMiddleware.serverOptions.ts +++ b/wp-content/themes/ccat/server/graphqlMiddleware.serverOptions.ts @@ -1,5 +1,6 @@ import { defineGraphqlServerOptions } from "nuxt-graphql-middleware/server-options"; import { jwtDecode } from "jwt-decode"; +import type { LoginRootMutation, UserSwitchToRootMutation } from "#graphql-operations"; interface DecodedToken { exp: number; @@ -24,9 +25,51 @@ export default defineGraphqlServerOptions({ const newToken = await refreshAuthToken(session.secure.refreshToken); if (newToken) { session.secure.authToken = newToken; + await setUserSession(event, session); } } return { headers: { ...headers, Authorization: `Bearer ${session.secure.authToken}` } }; }, + + onServerResponse(event, response, _operation, operationName) { + // Handle login mutation + if (operationName === "login") { + const loginData = response._data as LoginRootMutation; + if (loginData?.login) { + const { authToken, refreshToken, user } = loginData.login; + setUserSession(event, { + user: { + id: user?.id, + email: user?.email, + }, + secure: { + authToken, + refreshToken, + }, + }); + } + } + + // Handle user switch mutations + if (operationName === "userSwitchTo") { + const switchData = response._data as UserSwitchToRootMutation; + if (switchData?.userSwitchTo?.authToken) { + const { authToken, refreshToken, user } = switchData.userSwitchTo; + setUserSession(event, { + user: { + id: user?.id, + email: user?.email, + }, + secure: { + authToken, + refreshToken, + }, + }); + } + } + + // Return the original response data + return response._data!; + }, }); diff --git a/wp-content/themes/ccat/server/schema.graphql b/wp-content/themes/ccat/server/schema.graphql index 6fc398b..cc4f2a2 100644 --- a/wp-content/themes/ccat/server/schema.graphql +++ b/wp-content/themes/ccat/server/schema.graphql @@ -17583,12 +17583,6 @@ type RootMutation { input: UpdateUserInput! ): UpdateUserPayload - """The userSwitchBack mutation""" - userSwitchBack( - """Input for the userSwitchBack mutation""" - input: UserSwitchBackInput! - ): UserSwitchBackPayload - """The userSwitchTo mutation""" userSwitchTo( """Input for the userSwitchTo mutation""" @@ -24953,25 +24947,6 @@ enum UserRoleEnum { TRANSLATOR } -"""Input for the userSwitchBack mutation.""" -input UserSwitchBackInput { - """ - This is an ID that can be passed to a mutation by the client to track the progress of mutations and catch possible duplicate mutation submissions. - """ - clientMutationId: String -} - -"""The payload for the userSwitchBack mutation.""" -type UserSwitchBackPayload { - """ - If a 'clientMutationId' input is provided to the mutation, it will be returned as output on the mutation. This ID can be used by the client to track the progress of mutations and catch possible duplicate mutation submissions. - """ - clientMutationId: String - - """Whether switching back was successful""" - success: Boolean -} - """Input for the userSwitchTo mutation.""" input UserSwitchToInput { """