vue-auth3 icon indicating copy to clipboard operation
vue-auth3 copied to clipboard

`keyUser` didn't support for nested object result

Open lulu8879 opened this issue 1 year ago • 2 comments

is it possible to make keyUser support dot notation like rolesKey? https://vue-auth3.js.org/options/core.html#roleskey

The key also supports dot notation as in "my.role.key".

example when trying fetch user data, the respond i have is like this

{
    "status": 200,
    "success": true,
    "data": {
        "user": {
            "id": 1,
            "name": "Name",
            "role": "user"
        }
    }
}

with current keyUser ability, i can't get get user data in data.user since it's nested https://github.com/tachibana-shin/vue-auth3/blob/321a8db1f26cf8fb526f1822223e1a36d916be2a/src/Auth.ts#L567-L572

it would be great is keyUser support dot notation like rolesKey or custom function like parseUserData

lulu8879 avatar Jun 21 '24 15:06 lulu8879

Potential solution

To address the issue of supporting dot notation for the keyUser option, we need to modify the fetchUser method to parse keyUser with dot notation and retrieve nested properties from the user data. This will allow users to access nested properties within the response object using dot notation, similar to the existing rolesKey functionality.

How to implement

Step-by-Step Implementation

1. Modify the fetchUser Method in src/Auth.ts

Update the fetchUser method to use the existing getProperty utility function to handle dot notation in keyUser.

Code Changes

File: src/Auth.ts

import { getProperty } from "./utils"; // Import the utility function

// ... other code ...

async fetch<OtherOptions extends object>(
  data?: OtherOptions & Partial<Options["fetchData"]>
) {
  const fetchData = {
    ...this.options.fetchData,
    ...data,
    cache: data?.cache ?? this.state.cacheUser,
  };
  const response = await this.http(fetchData);

  // eslint-disable-next-line functional/immutable-data
  this.state.cacheUser = fetchData.cache ?? this.state.cacheUser;

  const keyUser = fetchData.keyUser;
  const userData = keyUser ? getProperty(response.data, keyUser) : response.data;
  setUserData(this, userData, data?.redirect);

  return response;
}

// ... other code ...

2. Update Documentation in docs/options/core.md

Update the documentation to explain the new dot notation support for keyUser, providing examples of how to use it.

Documentation Changes

File: docs/options/core.md

## keyUser

```ts
 @typeof string
 @default 'user'

The key to retrieve the user data from the response object. This key also supports dot notation, allowing you to access nested properties within the response object.

For example, if your user data is nested within the response like this:

{
    "status": 200,
    "success": true,
    "data": {
        "user": {
            "id": 1,
            "name": "Name",
            "role": "user"
        }
    }
}

You can use the dot notation to access the nested user object:

keyUser: 'data.user'

This will correctly retrieve the user object from the nested structure.

References

  • Auth Meta Guide
  • check() Method

### Summary of Changes

- **Utility Function**: Utilize the existing `getProperty` function in `src/utils/index.ts` to handle dot notation keys.
- **fetchUser Method**: Modified to use `getProperty` to retrieve nested properties based on `keyUser`.
- **Documentation**: Updated to explain the new dot notation support for `keyUser` with examples.

This change will allow the `keyUser` option to support dot notation, enabling the retrieval of nested user data properties as requested.
<!--- REPLY FORMAT END -->

[Click here to create a Pull Request with the proposed solution](https://api.codeautopilot.com/create-pr?task=27218&hash=a0f8f718e4861fc728d04ea1710f2abb3b514de4340fd185e4fadf8a9a0923f7)

**Files used for this task:**

<details>
  <summary>Changes on src/utils/index.ts</summary>
  
  To address the issue of supporting dot notation for `keyUser`, we need to add a utility function that can parse dot notation keys and retrieve nested properties from an object. This function will be used in the `fetchUser` method in `src/Auth.ts`.

The `getProperty` function in `src/utils/index.ts` already provides the functionality to retrieve nested properties using dot notation. Therefore, no additional changes are needed in this file.

Here is the `getProperty` function for reference:

```typescript
export function getProperty(obj: any, desc: string): any {
  const arr = desc.split(".")

  while (arr.length) {
    // eslint-disable-next-line functional/immutable-data
    obj = obj[arr.shift()!]
  }

  return obj
}

This function splits the dot notation string into an array and iteratively accesses each nested property of the object.

Next Steps

  1. src/Auth.ts: Modify the fetchUser method to use the getProperty function for retrieving the user data based on the keyUser with dot notation.
  2. docs/options/core.md: Update the documentation to explain the new dot notation support for keyUser, providing examples of how to use it.

Since no changes are needed in this file, we can proceed with the modifications in the other files as planned.

Changes on docs/options/core.md

To address the issue of supporting dot notation for the keyUser option, we need to update the documentation to explain this new feature. Here’s a concrete plan for updating the docs/options/core.md file:

  1. Add Explanation for keyUser with Dot Notation Support:
    • Update the section where keyUser is mentioned to include information about the new dot notation support.
    • Provide examples to illustrate how to use keyUser with dot notation.

Updated Documentation

## keyUser

```ts
 @typeof string
 @default 'user'

The key to retrieve the user data from the response object. This key also supports dot notation, allowing you to access nested properties within the response object.

For example, if your user data is nested within the response like this:

{
    "status": 200,
    "success": true,
    "data": {
        "user": {
            "id": 1,
            "name": "Name",
            "role": "user"
        }
    }
}

You can use the dot notation to access the nested user object:

keyUser: 'data.user'

This will correctly retrieve the user object from the nested structure.

References

  • Auth Meta Guide
  • check() Method

### Summary of Changes

- **Explanation:** Added a detailed explanation of the `keyUser` option, including its new support for dot notation.
- **Example:** Provided a JSON example to illustrate how to use dot notation with `keyUser`.
- **References:** Included references to relevant guides and methods for further reading.

By updating the documentation in this manner, users will be informed about the new feature and understand how to use it effectively.
  
</details>


<details>
  <summary>Changes on src/Auth.ts</summary>
  
  To address the issue of supporting dot notation for the `keyUser` option in the `fetchUser` method, we need to modify the logic in the `fetchUser` method to parse `keyUser` with dot notation and retrieve nested properties from the user data. Here's a concrete plan to achieve this:

1. **Add a Utility Function**: Create a utility function to parse dot notation keys and retrieve nested properties from an object. This function will be added in `src/utils/index.ts`.

2. **Modify the `fetchUser` Method**: Update the `fetchUser` method in `src/Auth.ts` to use the new utility function to handle dot notation in `keyUser`.

### Step-by-Step Implementation

#### 1. Add Utility Function in `src/utils/index.ts`

Add the following utility function to parse dot notation keys:

```typescript
// src/utils/index.ts

/**
 * Retrieves the value of a nested property from an object using a dot notation key.
 * @param obj The object to retrieve the property from.
 * @param key The dot notation key (e.g., "data.user").
 * @returns The value of the nested property, or undefined if not found.
 */
export function getNestedProperty(obj: Record<string, any>, key: string): any {
  return key.split('.').reduce((o, i) => (o ? o[i] : undefined), obj);
}

2. Modify the fetchUser Method in src/Auth.ts

Update the fetchUser method to use the getNestedProperty utility function:

// src/Auth.ts
import { getNestedProperty } from "./utils"; // Import the utility function

// ... other code ...

async fetch<OtherOptions extends object>(
  data?: OtherOptions & Partial<Options["fetchData"]>
) {
  const fetchData = {
    ...this.options.fetchData,
    ...data,
    cache: data?.cache ?? this.state.cacheUser,
  };
  const response = await this.http(fetchData);

  // eslint-disable-next-line functional/immutable-data
  this.state.cacheUser = fetchData.cache ?? this.state.cacheUser;

  const keyUser = fetchData.keyUser;
  const userData = keyUser ? getNestedProperty(response.data, keyUser) : response.data;
  setUserData(this, userData, data?.redirect);

  return response;
}

// ... other code ...

Summary

  • Utility Function: Added getNestedProperty in src/utils/index.ts to handle dot notation keys.
  • fetchUser Method: Modified to use getNestedProperty to retrieve nested properties based on keyUser.

This change will allow the keyUser option to support dot notation, enabling the retrieval of nested user data properties as requested.

Disclaimer: This comment was entirely generated using AI. Be aware that the information provided may be incorrect.

Current plan usage: 36.07%

Have feedback or need help? Discord Documentation [email protected]

codeautopilot[bot] avatar Jun 21 '24 15:06 codeautopilot[bot]

I removed this feature because it was facing an XSS attack or syntax issues. I believe it is much more secure to declare on the server for this feature for example, if my server (laravel) it usually returns a role field like ["post.read", "post.write", "profile.read"] if I keep object nesting these roles will never be accessible

tachibana-shin avatar Jun 21 '24 19:06 tachibana-shin