@duotek/nuxt3-auth
Модуль авторизации с использованием Nuxt3
Установка
yarn add -E @duotek/nuxt3-auth
Подключите модуль в nuxt.config
export default defineNuxtConfig({
modules: ["@duotek/nuxt3-auth"],
});
Добавьте настройку для модуля в nuxt.config
export default defineNuxtConfig({
auth: {
redirects: {
auth: false,
guest: false,
external: false,
externalDomain: '',
},
cookie: {
prefix: "",
options: {
expires: 300,
},
},
strategies: {
signUp: {
tokenType: "",
endpoints: {
login: {
url: "",
method: "",
propertyName: "",
},
logout: {
url: "",
method: "",
},
user: {
url: "",
method: "",
},
},
},
signIn: {
tokenType: "",
endpoints: {
login: {
url: "",
method: "",
propertyName: "",
},
logout: {
url: "",
method: "",
},
user: {
url: "",
method: "",
},
},
},
},
},
});
Добавьте переменную api в nuxt.config
export default defineNuxtConfig({
runtimeConfig: {
public: {
app_env: {
BASE_API_URL: "https://api-example.com",
},
},
},
});
Замените дефолтный $fetch на предоставляемый $authFetch
import { useNuxtApp, useFetch } from '#app';
export function useAuthFetch(url, options = {}) {
const { $authFetch } = useNuxtApp();
return useFetch(url, {
...options,
$fetch: $authFetch,
});
}
import { useCustomFetch } from '~/path/to/useCustomFetch';
const { data, error } = await useCustomFetch('/some-endpoint');
import createApi from '~/services/api/index';
export default defineNuxtPlugin((nuxtApp) => {
if (!nuxtApp.$api) {
const { $authFetch } = useNuxtApp();
const apiObject = createApi({
$api: $authFetch,
$config: useRuntimeConfig().public.app_env,
});
nuxtApp.provide('api', apiObject);
}
});
import RExample from '@/services/api/resource/RExample';
const createApi = (ctx) => ({
example: new RExample(ctx),
});
export default createApi;
Использование
<template>
<div>
<div v-if="isLoggedIn">
<p>Добро пожаловать, {{ user.name }}</p>
<button @click="onLogout">Выйти</button>
</div>
<div v-else>
<div>Логин</div>
<form @submit.prevent="onSubmit">
<input v-model="login" type="text" placeholder="Логин" />
<input v-model="password" type="password" placeholder="Пароль" />
<button type="submit">Войти</button>
</form>
</div>
</div>
</template>
<script setup>
import { ref, computed } from "vue";
import { useNuxtApp } from "#app";
// Раскомментируйте одну из строк ниже в зависимости от необходимого middleware
// definePageMeta({
// middleware: "guest",
// });
// definePageMeta({
// middleware: "auth",
// });
const login = ref("");
const password = ref("");
const { $auth } = useNuxtApp();
const user = computed(() => $auth.user);
const isLoggedIn = computed(() => $auth.isLoggedIn);
const onSubmit = async () => {
try {
await $auth.signIn({ login: login.value, password: password.value });
} catch (error) {
console.error(error);
}
};
const onLogout = async () => {
await $auth.logout();
};
</script>
Contribution
Local development
yarn install
yarn dev:prepare
yarn dev
yarn dev:build
yarn lint
yarn test
yarn test:watch
npm publish