Skip to content

Commit

Permalink
fix: Fix error is not defined
Browse files Browse the repository at this point in the history
  • Loading branch information
trandaison committed Mar 29, 2024
1 parent 7d13fa1 commit 6fc7dcd
Show file tree
Hide file tree
Showing 14 changed files with 122 additions and 11 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ A simple authentication module for Nuxt 3
## Features

<!-- Highlight some of the features your module provide here -->
- &nbsp;Foo
- 🚠 &nbsp;Bar
- 🌲 &nbsp;Baz
- 🤝 &nbsp;Compatible with pinia, nuxtjs/i18n, ofetch.
- 🚀 &nbsp;Built in pages and compositions.
- ⚙️ &nbsp;Support refresh tokens

## Quick Setup

Expand Down
2 changes: 2 additions & 0 deletions docs/.vitepress/config/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ export const en = defineConfig({
{ text: "Login", link: "/guide/login" },
{ text: "Logout", link: "/guide/logout" },
{ text: "Middleware", link: "/guide/middleware" },
{ text: "HTTP Request", link: "/guide/http-request" },
{ text: "Typescript", link: "/guide/typescript" },
{ text: "FAQ", link: "/guide/faq" },
],
},
{
Expand Down
1 change: 1 addition & 0 deletions docs/.vitepress/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export default defineConfig({
{ text: "Logout", link: "/guide/logout" },
{ text: "Middleware", link: "/guide/middleware" },
{ text: "Typescript", link: "/guide/typescript" },
{ text: "FAQ", link: "/guide/faq" },
],
},
{
Expand Down
2 changes: 2 additions & 0 deletions docs/.vitepress/config/vi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ export const vi = defineConfig({
{ text: "Login", link: "/vi/guide/login" },
{ text: "Logout", link: "/vi/guide/logout" },
{ text: "Middleware", link: "/vi/guide/middleware" },
{ text: "HTTP Request", link: "/vi/guide/http-request" },
{ text: "Typescript", link: "/vi/guide/typescript" },
{ text: "Câu hỏi thường gặp", link: "/vi/guide/faq" },
],
},
{
Expand Down
16 changes: 16 additions & 0 deletions docs/guide/faq.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# frequently asked questions

## Why `$fetch` does not automatically refresh the access token when it expires or has a refresh access token but does not retry the request even though all settings are correct?

First of all, if you are using the global `$fetch` function, make sure you have set the `auth.useGlobalFetch: true` option in `nuxt.config.js`.

If you are using `$fetch` through `$auth`, make sure you are using the `auth: true` option when calling `$fetch`.

```ts
const auth = useAuth();
awit auth.$fetch('/api/me', { auth: true });
```

::: tip
See more about [auth.fetch](/api/$auth#fetch) and [auth.useGlobalFetch](/api/options#useglobalfetch).
:::
33 changes: 33 additions & 0 deletions docs/guide/http-request.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# HTTP Request

This module provides a simple way to make HTTP requests. It is based on the [`ofetch`](https://github.com/unjs/ofetch) library.

To make a request, you can use the `$fetch` method provided by the `$auth`.

```ts
const auth = useAuth();
await auth.$fetch('/api/books');
```

`$auth.$fetch` use the [nuxt $fetch](https://nuxt.com/docs/api/utils/dollarfetch) under the hood, so you can use all the options provided by the nuxt fetch method. Plus, it adds one more option `auth` to make authenticated requests.

```ts
const auth = useAuth();
await auth.$fetch('/api/me', {
auth: true
});
```

`auth` option allow theses values:

| Value | Description | Attach Access Token | Refresh access token | Retry request |
| --- | --- | --- | --- | --- |
| **`'auto'`** |||| Make authenticated request if possible but doesn't refresh access token when token expires |
| `true` |||| Make authenticated request and refresh token then retry if the response status is `401` |
| `false` |||| Make normal request |

:::tip
By default, the [useGlobalFetch](/api/options.html#useglobalfetch) option is set to `true`, so the global `$fetch` is overridden by `$auth.$fetch`.

In case you want to use the default Nuxt `$fetch`, set `useGlobalFetch: false` in the [options](/options).
:::
2 changes: 1 addition & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ hero:
actions:
- theme: brand
text: Get Started
link: /getting-started
link: /installation
- theme: alt
text: API Reference
link: /api/options
Expand Down
16 changes: 16 additions & 0 deletions docs/vi/guide/faq.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Các câu hỏi thường gặp

## `$fetch` không tự động refresh access token khi hết hạn mặc hoặc có refresh access token nhưng không retry lại request dù mọi cài đặt đều đúng?

Trước hết, nếu bạn sử dụng hàm global `$fetch`, hãy chắc chắn rằng bạn đã set cài đặt `auth.useGlobalFetch: true` trong `nuxt.config.js`.

Nếu bạn sử dụng `$fetch` thông qua `$auth`, hãy chắc chắn rằng bạn có sử dụng option `auth: true` khi gọi `$fetch`.

```ts
const auth = useAuth();
awit auth.$fetch('/api/me', { auth: true });
```

::: tip
Xem thêm về [$auth.$fetch](/vi/api/$auth#fetch)[auth.useGlobalFetch](/vi/api/options#useglobalfetch).
:::
33 changes: 33 additions & 0 deletions docs/vi/guide/http-request.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# HTTP request

Module này cung cấp một cách đơn giản để thực hiện các HTTP request sử dụng thư viện [`ofetch`](https://github.com/unjs/ofetch).

Để thực hiện một request, bạn có thể sử dụng phương thức `$fetch` được cung cấp bởi `$auth`.

```ts
const auth = useAuth();
await auth.$fetch('/api/books');
```

`$auth.$fetch` sử dụng [nuxt $fetch](https://nuxt.com/docs/api/utils/dollarfetch) bên dưới, vì vậy bạn có thể sử dụng tất cả các tùy chọn được cung cấp bởi phương thức fetch của nuxt. Ngoài ra, có thêm một tùy chọn nữa là `auth` để thực hiện các request được xác thực.

```ts
const auth = useAuth();
await auth.$fetch('/api/me', {
auth: true
});
```

Tùy chọn `auth` cho phép các giá trị sau:

| Giá trị | Mô tả | Đính kèm Access Token | Làm mới access token | Thử lại request |
| --- | --- | --- | --- | --- |
| **`'auto'`** |||| Thực hiện request xác thực nếu có thể nhưng không làm mới access token khi token hết hạn |
| `true` |||| Thực hiện request xác thực và làm mới token sau đó thử lại nếu trạng thái phản hồi là `401` |
| `false` |||| Thực hiện request bình thường |

::: tip
Mặc định, option [useGlobalFetch](/vi/api/options.html#useglobalfetch) được thiết lập là `true`, do đó global `$fetch` được override bởi `$auth.$fetch`.

Trong trường hợp bạn muốn sử dụng `$fetch` mặc định của Nuxt, hãy thiết lập `useGlobalFetch: false` trong [options](/options).
:::
2 changes: 1 addition & 1 deletion docs/vi/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ hero:
actions:
- theme: brand
text: Bắt đầu
link: /vi/getting-started
link: /vi/installation
- theme: alt
text: API Reference
link: /vi/api/options
Expand Down
1 change: 1 addition & 0 deletions src/runtime/composables/useLogout.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { RawLocation } from '@intlify/vue-router-bridge';
import { ref } from 'vue';
import { navigateTo, useNuxtApp, useRuntimeConfig } from "#imports";
import { useLocalizeRoute } from "#build/useLocalizeRoute.mjs";

export const useLogout = (redirectPath: RawLocation = "/") => {
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/middleware/auth.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable consistent-return */
import type { RouteLocationNormalized } from 'vue-router';
import { navigateTo, useNuxtApp } from "#imports";
import { navigateTo, useNuxtApp, useRuntimeConfig } from "#imports";
import { useLocalizeRoute } from "#build/useLocalizeRoute.mjs";
import { AuthStatus } from "../utils";

Expand Down
6 changes: 5 additions & 1 deletion src/runtime/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { addRouteMiddleware, defineNuxtPlugin } from "#imports";
import {
addRouteMiddleware,
defineNuxtPlugin,
useRuntimeConfig,
} from "#imports";
import { Auth } from "./services/Auth";
import authMiddleware from "./middleware/auth";

Expand Down
11 changes: 7 additions & 4 deletions src/runtime/services/HttpService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,14 @@ export default class HttpService {
}

try {
await this.$auth.refreshTokens();
options.headers = (options.headers || {}) as Record<string, string>;
options.headers[headerName] = `${type} ${this.$auth.accessToken}`;
const { token } = await this.$auth.refreshTokens();
// Stringify and parse to remove the callback functions (e.g. onResponse, onRequest, etc.)
const opts = JSON.parse(JSON.stringify(options));
opts.headers = opts.headers || {};
opts.headers[headerName] = `${type} ${token}`;
await this.$fetch(request, {
onRequest: this.onRequest.bind(this),
...opts,
auth: false,
onResponse(ctx) {
Object.assign(context, ctx);
},
Expand Down

0 comments on commit 6fc7dcd

Please sign in to comment.