New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@duotek/nuxt3-auth

Package Overview
Dependencies
Maintainers
0
Versions
26
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@duotek/nuxt3-auth

Duotek Nuxt3 Auth Module

  • 2.4.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
12
decreased by-77.78%
Maintainers
0
Weekly downloads
 
Created
Source

@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: { // опциональный параметр для работы middleware
			auth: false, // передается строка страницы для редиректа авторизованного пользователя или false для пропуска
			guest: false, // передается строка страницы для редиректа неавторизованного пользователя или 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');

// Или расширьте $fetch своими эндпоинтами

// файл services/index.js
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);
	}
});

// файл services/api/index.js
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
# Install dependencies
yarn install

# Generate type stubs
yarn dev:prepare

# Develop with the playground
yarn dev

# Build the playground
yarn dev:build

# Run ESLint
yarn lint

# Run Vitest
yarn test
yarn test:watch

# Release new version
npm publish

Keywords

FAQs

Package last updated on 21 Jan 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc