feat: Initial login / logout API endpoints
This commit is contained in:
49
wp-content/themes/headless/server/utils/auth.ts
Normal file
49
wp-content/themes/headless/server/utils/auth.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import type { AuthPayloadFragment, AuthUserFragment } from "#graphql/types";
|
||||
import type { H3Event } from "h3";
|
||||
|
||||
/**
|
||||
* Handle user login by setting the session data with the provided authentication information.
|
||||
*
|
||||
* @param event The H3 event object.
|
||||
* @param payload The authentication payload containing user and token information.
|
||||
* @return A promise that resolves to true if the login was successful, or false if there was an error.
|
||||
*/
|
||||
export async function handleLogin(
|
||||
event: H3Event,
|
||||
{ user, authToken, refreshToken }: AuthPayloadFragment,
|
||||
) {
|
||||
if (!user || !authToken || !refreshToken) {
|
||||
return false;
|
||||
}
|
||||
|
||||
await setUserSession(event, {
|
||||
user: getAuthUser(user),
|
||||
secure: { authToken, refreshToken },
|
||||
loggedInAt: new Date().toISOString(),
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle user logout by clearing the session data.
|
||||
*
|
||||
* @param event The H3 event object.
|
||||
* @returns A promise that resolves when the session has been cleared.
|
||||
*/
|
||||
export async function handleLogout(event: H3Event) {
|
||||
await clearUserSession(event);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert the AuthUserFragment to a User object expected by nuxt-auth-utils
|
||||
*
|
||||
* @param user The AuthUserFragment containing user data from the GraphQL response
|
||||
* @returns A User object with the expected structure for nuxt-auth-utils, including an array of role names
|
||||
*/
|
||||
function getAuthUser(user: AuthUserFragment) {
|
||||
return {
|
||||
...user,
|
||||
roles: user.roles.nodes.map(({ name }) => name) || [],
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user