refactor: rename userSwitchTo
All checks were successful
Deploy WordPress and Nuxt / deploy (push) Successful in 1m6s

This commit is contained in:
2025-09-18 11:50:02 -04:00
parent 3cc4b570d5
commit 4e9ad82d96
9 changed files with 72 additions and 66 deletions

View File

@@ -7,8 +7,8 @@ export function useUserSwitching() {
async function userSwitchTo(userId: string | number) { async function userSwitchTo(userId: string | number) {
try { try {
const { data, errors } = await useGraphqlMutation("userSwitchTo", { userId }); const { data, errors } = await useGraphqlMutation("switchTo", { userId });
if (errors.length || !data.userSwitchTo) { if (errors.length || !data.switchTo) {
throw new Error("Une erreur est survenue"); throw new Error("Une erreur est survenue");
} }
await refreshUserSession(); await refreshUserSession();

View File

@@ -0,0 +1,10 @@
mutation switchTo($userId: ID!) {
switchTo(input: { userId: $userId }) {
authToken
refreshToken
user {
id
email
}
}
}

View File

@@ -1,10 +0,0 @@
mutation userSwitchTo($userId: ID!) {
userSwitchTo(input: { userId: $userId }) {
authToken
refreshToken
user {
id
email
}
}
}

View File

@@ -23,9 +23,9 @@ require_once __DIR__ . '/includes/taxonomies/resource-category.php';
// Forms // Forms
// WPGraphQL // WPGraphQL
require_once __DIR__ . '/includes/graphql/auth.php';
require_once __DIR__ . '/includes/graphql/address.php'; require_once __DIR__ . '/includes/graphql/address.php';
require_once __DIR__ . '/includes/graphql/breadcrumbs.php'; require_once __DIR__ . '/includes/graphql/breadcrumbs.php';
require_once __DIR__ . '/includes/graphql/user-switching.php';
// Roles // Roles

View File

@@ -1,29 +1,29 @@
<?php <?php
// Register userSwitchTo mutation // Register switchTo mutation
add_action( 'graphql_register_types', 'ccat_graphql_register_user_switch_to' ); add_action( 'graphql_register_types', 'ccat_graphql_register_switch_to' );
function ccat_graphql_register_user_switch_to() { function ccat_graphql_register_switch_to() {
register_graphql_mutation( register_graphql_mutation(
'userSwitchTo', 'switchTo',
array( array(
'inputFields' => array( 'inputFields' => array(
'userId' => array( 'userId' => array(
'type' => 'ID', 'type' => 'ID',
'description' => esc_html__( 'The ID of the user to switch to', 'ccat' ), 'description' => 'The ID of the user to switch to',
), ),
), ),
'outputFields' => array( 'outputFields' => array(
'authToken' => array( 'authToken' => array(
'type' => 'String', 'type' => 'String',
'description' => esc_html__( 'JWT Token for the target user', 'ccat' ), 'description' => 'JWT Token for the target user',
), ),
'refreshToken' => array( 'refreshToken' => array(
'type' => 'String', 'type' => 'String',
'description' => esc_html__( 'JWT Refresh Token for the target user', 'ccat' ), 'description' => 'JWT Refresh Token for the target user',
), ),
'user' => array( 'user' => array(
'type' => 'User', 'type' => 'User',
'description' => esc_html__( 'The target user object', 'ccat' ), 'description' => 'The target user object',
), ),
), ),
'mutateAndGetPayload' => 'ccat_graphql_switch_to_mutation', 'mutateAndGetPayload' => 'ccat_graphql_switch_to_mutation',
@@ -31,19 +31,19 @@ function ccat_graphql_register_user_switch_to() {
); );
} }
// Callback for userSwitchTo mutation // Handle switchTo mutation
function ccat_graphql_switch_to_mutation( $input ) { function ccat_graphql_switch_to_mutation( $input ) {
if ( ! is_user_logged_in() || ! current_user_can( 'manage_options' ) ) { if ( ! is_user_logged_in() || ! current_user_can( 'manage_options' ) ) {
throw new \GraphQL\Error\UserError( esc_html__( 'Insufficient permissions', 'ccat' ) ); throw new \GraphQL\Error\UserError( "Permissions insuffisantes pour se connecter en tant qu'un autre utilisateur." );
} }
$user_id = absint( $input['userId'] ); $user_id = absint( $input['userId'] );
$current_user_id = get_current_user_id(); $current_user_id = get_current_user_id();
if ( $user_id === $current_user_id ) { if ( $user_id === $current_user_id ) {
throw new \GraphQL\Error\UserError( esc_html__( 'Cannot switch to yourself', 'ccat' ) ); throw new \GraphQL\Error\UserError( 'Impossible de se connecter en tant que son propre utilisateur.' );
} }
$target_user = get_user_by( 'ID', $user_id ); $target_user = get_user_by( 'ID', $user_id );
if ( ! $target_user ) { if ( ! $target_user ) {
throw new \GraphQL\Error\UserError( esc_html__( 'User not found', 'ccat' ) ); throw new \GraphQL\Error\UserError( 'Utilisateur introuvable.' );
} }
$secret_key = defined( 'GRAPHQL_JWT_AUTH_SECRET_KEY' ) ? GRAPHQL_JWT_AUTH_SECRET_KEY : wp_salt(); $secret_key = defined( 'GRAPHQL_JWT_AUTH_SECRET_KEY' ) ? GRAPHQL_JWT_AUTH_SECRET_KEY : wp_salt();
$issued_at = time(); $issued_at = time();

View File

@@ -1,6 +1,12 @@
import { defineEventHandler } from "h3"; import { defineEventHandler } from "h3";
export default defineEventHandler(async (event) => { export default defineEventHandler(async (event) => {
await clearUserSession(event); try {
return { success: true }; await handleLogout(event);
return { success: true, message: "Déconnexion réussie" };
}
catch (error) {
const message = error instanceof Error ? error.message : "Une erreur est survenue.";
return { success: false, message };
}
}); });

View File

@@ -1,6 +1,6 @@
import { defineGraphqlServerOptions } from "nuxt-graphql-middleware/server-options"; import { defineGraphqlServerOptions } from "nuxt-graphql-middleware/server-options";
import { jwtDecode } from "jwt-decode"; import { jwtDecode } from "jwt-decode";
import type { LoginRootMutation, UserSwitchToRootMutation } from "#graphql-operations"; import type { LoginRootMutation, SwitchToRootMutation } from "#graphql-operations";
interface DecodedToken { interface DecodedToken {
exp: number; exp: number;
@@ -37,8 +37,8 @@ export default defineGraphqlServerOptions({
case "login": case "login":
await handleLogin(event, response._data!.data as LoginRootMutation); await handleLogin(event, response._data!.data as LoginRootMutation);
break; break;
case "userSwitchTo": case "switchTo":
await handleSwitchTo(event, response._data!.data as UserSwitchToRootMutation); await handleSwitchTo(event, response._data!.data as SwitchToRootMutation);
break; break;
} }
return response._data!; return response._data!;

View File

@@ -17463,6 +17463,12 @@ type RootMutation {
input: SendPasswordResetEmailInput! input: SendPasswordResetEmailInput!
): SendPasswordResetEmailPayload ): SendPasswordResetEmailPayload
"""The switchTo mutation"""
switchTo(
"""Input for the switchTo mutation"""
input: SwitchToInput!
): SwitchToPayload
"""The updateCategory mutation""" """The updateCategory mutation"""
updateCategory( updateCategory(
"""Input for the updateCategory mutation""" """Input for the updateCategory mutation"""
@@ -17582,12 +17588,6 @@ type RootMutation {
"""Input for the updateUser mutation""" """Input for the updateUser mutation"""
input: UpdateUserInput! input: UpdateUserInput!
): UpdateUserPayload ): UpdateUserPayload
"""The userSwitchTo mutation"""
userSwitchTo(
"""Input for the userSwitchTo mutation"""
input: UserSwitchToInput!
): UserSwitchToPayload
} }
"""The root entry point into the Graph""" """The root entry point into the Graph"""
@@ -21777,6 +21777,34 @@ type SiteOptions implements AcfOptionsPage & Node & WithAcfGroupCcat {
parentId: String parentId: String
} }
"""Input for the switchTo mutation."""
input SwitchToInput {
"""
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 ID of the user to switch to"""
userId: ID
}
"""The payload for the switchTo mutation."""
type SwitchToPayload {
"""JWT Token for the target user"""
authToken: String
"""
If a &#039;clientMutationId&#039; 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
"""JWT Refresh Token for the target user"""
refreshToken: String
"""The target user object"""
user: User
}
""" """
A taxonomy term used to organize and classify content. Tags do not have a hierarchy and are generally used for more specific classifications. A taxonomy term used to organize and classify content. Tags do not have a hierarchy and are generally used for more specific classifications.
""" """
@@ -24947,34 +24975,6 @@ enum UserRoleEnum {
TRANSLATOR TRANSLATOR
} }
"""Input for the userSwitchTo mutation."""
input UserSwitchToInput {
"""
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 ID of the user to switch to"""
userId: ID
}
"""The payload for the userSwitchTo mutation."""
type UserSwitchToPayload {
"""JWT Token for the target user"""
authToken: String
"""
If a &#039;clientMutationId&#039; 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
"""JWT Refresh Token for the target user"""
refreshToken: String
"""The target user object"""
user: User
}
"""Connection between the User type and the Comment type""" """Connection between the User type and the Comment type"""
type UserToCommentConnection implements CommentConnection & Connection { type UserToCommentConnection implements CommentConnection & Connection {
"""Edges for the UserToCommentConnection connection""" """Edges for the UserToCommentConnection connection"""

View File

@@ -1,4 +1,4 @@
import type { LoginRootMutation, UserSwitchToRootMutation } from "#graphql-operations"; import type { LoginRootMutation, SwitchToRootMutation } from "#graphql-operations";
import type { H3Event } from "h3"; import type { H3Event } from "h3";
import { pick } from "es-toolkit/compat"; import { pick } from "es-toolkit/compat";
@@ -25,7 +25,7 @@ export async function handleLogout(event: H3Event) {
await clearUserSession(event); await clearUserSession(event);
} }
export async function handleSwitchTo(event: H3Event, data?: UserSwitchToRootMutation) { export async function handleSwitchTo(event: H3Event, data?: SwitchToRootMutation) {
if (!data?.userSwitchTo?.user) { if (!data?.userSwitchTo?.user) {
return; return;
} }