npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@duotek/nuxt3-auth

v1.0.6

Published

Duotek Nuxt3 Auth Module

Downloads

39

Readme

@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, // дает возможность редиректить пользователя по внешним ссылкам
		},
		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

# 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