generated from pascalmartineau/wp-skeleton
refactor: use onServerResponse for auth instead of server api
This commit is contained in:
@@ -22,11 +22,12 @@ export function useAuth() {
|
|||||||
required: true,
|
required: true,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
async function onLoginSubmit({ data }: FormSubmitEvent<LoginOutput>) {
|
async function onLoginSubmit({ data: args }: FormSubmitEvent<LoginOutput>) {
|
||||||
try {
|
try {
|
||||||
const result = await $fetch<{ success: boolean; message?: string }>("/api/login", { method: "POST", body: data });
|
const { data, errors } = await useGraphqlMutation("login", args);
|
||||||
if (!result.success) {
|
if (errors.length || !data.login) {
|
||||||
throw new Error(result.message || "Une erreur est survenue.");
|
console.error(errors);
|
||||||
|
throw new Error("Une erreur est survenue.");
|
||||||
}
|
}
|
||||||
await router.push(redirect);
|
await router.push(redirect);
|
||||||
await refreshUserSession();
|
await refreshUserSession();
|
||||||
|
|||||||
@@ -7,40 +7,29 @@ export function useUserSwitching() {
|
|||||||
|
|
||||||
async function userSwitchTo(userId: string | number) {
|
async function userSwitchTo(userId: string | number) {
|
||||||
try {
|
try {
|
||||||
const result = await $fetch<{ success: boolean; message?: string }>("/api/switch-to", {
|
const { data, errors } = await useGraphqlMutation("userSwitchTo", { userId });
|
||||||
method: "POST",
|
if (errors.length || !data.userSwitchTo) {
|
||||||
body: { userId },
|
throw new Error("Une erreur est survenue");
|
||||||
});
|
|
||||||
|
|
||||||
if (!result.success) {
|
|
||||||
throw new Error(result.message || "Switch failed");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
await refreshUserSession();
|
await refreshUserSession();
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
catch (error) {
|
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" });
|
toast.add({ title: "Échec du changement d'utilisateur", description: message, color: "error" });
|
||||||
throw error;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function userSwitchBack() {
|
async function userSwitchBack() {
|
||||||
try {
|
try {
|
||||||
const result = await $fetch<{ success: boolean; message?: string }>("/api/switch-back", {
|
const result = await $fetch("/api/switch-back", { method: "POST" });
|
||||||
method: "POST",
|
|
||||||
});
|
|
||||||
if (!result.success) {
|
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();
|
await refreshUserSession();
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
catch (error) {
|
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" });
|
toast.add({ title: "Échec du changement d'utilisateur", description: message, color: "error" });
|
||||||
throw error;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -78,26 +78,3 @@ function ccat_graphql_switch_to_mutation( $input ) {
|
|||||||
'user' => \WPGraphQL::get_app_context()->get_loader( 'user' )->load_deferred( $target_user->ID ),
|
'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 );
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -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<string, string> = {
|
|
||||||
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 };
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -2,15 +2,12 @@ import { defineEventHandler } from "h3";
|
|||||||
|
|
||||||
export default defineEventHandler(async (event) => {
|
export default defineEventHandler(async (event) => {
|
||||||
try {
|
try {
|
||||||
const response = await useGraphqlMutation("userSwitchBack");
|
// TODO: Switch back to the previous user.
|
||||||
if (response.errors?.length) {
|
|
||||||
throw new Error(response.errors[0]?.message);
|
|
||||||
}
|
|
||||||
await clearUserSession(event);
|
await clearUserSession(event);
|
||||||
return { success: true };
|
return { success: true };
|
||||||
}
|
}
|
||||||
catch (error) {
|
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 };
|
return { success: false, message };
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -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 };
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
mutation userSwitchBack {
|
|
||||||
userSwitchBack(input: {}) {
|
|
||||||
success
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,5 +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";
|
||||||
|
|
||||||
interface DecodedToken {
|
interface DecodedToken {
|
||||||
exp: number;
|
exp: number;
|
||||||
@@ -24,9 +25,51 @@ export default defineGraphqlServerOptions({
|
|||||||
const newToken = await refreshAuthToken(session.secure.refreshToken);
|
const newToken = await refreshAuthToken(session.secure.refreshToken);
|
||||||
if (newToken) {
|
if (newToken) {
|
||||||
session.secure.authToken = newToken;
|
session.secure.authToken = newToken;
|
||||||
|
await setUserSession(event, session);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return { headers: { ...headers, Authorization: `Bearer ${session.secure.authToken}` } };
|
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!;
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -17583,12 +17583,6 @@ type RootMutation {
|
|||||||
input: UpdateUserInput!
|
input: UpdateUserInput!
|
||||||
): UpdateUserPayload
|
): UpdateUserPayload
|
||||||
|
|
||||||
"""The userSwitchBack mutation"""
|
|
||||||
userSwitchBack(
|
|
||||||
"""Input for the userSwitchBack mutation"""
|
|
||||||
input: UserSwitchBackInput!
|
|
||||||
): UserSwitchBackPayload
|
|
||||||
|
|
||||||
"""The userSwitchTo mutation"""
|
"""The userSwitchTo mutation"""
|
||||||
userSwitchTo(
|
userSwitchTo(
|
||||||
"""Input for the userSwitchTo mutation"""
|
"""Input for the userSwitchTo mutation"""
|
||||||
@@ -24953,25 +24947,6 @@ enum UserRoleEnum {
|
|||||||
TRANSLATOR
|
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 for the userSwitchTo mutation."""
|
||||||
input UserSwitchToInput {
|
input UserSwitchToInput {
|
||||||
"""
|
"""
|
||||||
|
|||||||
Reference in New Issue
Block a user