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

winx-auth

v2.1.15

Published

Auth Nuxt module

Downloads

450

Readme

Winx Auth

npm version npm downloads License Nuxt

Quick Setup

  1. Add auth-module dependency to your project
# Using pnpm
pnpm add -D winx-auth

# Using yarn
yarn add --dev winx-auth

# Using npm
npm install --save-dev winx-auth
  1. Add winx-auth to the modules section of nuxt.config.ts
export default defineNuxtConfig({
  modules: [
    'winx-auth'
  ]
})

That's it! You can now use Winx Auth in your Nuxt app ✨

Development

# Install dependencies
npm install

# Generate type stubs
npm run dev:prepare

# Develop with the playground
npm run dev

# Build the playground
npm run dev:build

# Run ESLint
npm run lint

# Run Vitest
npm run test
npm run test:watch

# Release new version
npm run release

Module Options

To configure Winx Auth, you can pass the auth options.

// nuxt.config.ts
export default defineNuxtConfig({
  modules: [
    'winx-auth',
  ],
  auth: { // optional
    // Enable winx-auth (default: true)
    enabled: true,
    apiUrl: 'http://localhost:8080', // api url (default: env.API_URL)
    // Whether to add a global authentication middleware that protects all pages. (default: true)
    enableGlobalAppMiddleware: true, 
    globalMiddlewareOptions: {
      allow404WithoutAuth: true,
    },
    clientOptions: {
      retry: 1,
      baseURL: process.env.API_URL as string, // Api base url (default: env.API_URL)
    },
    token: {
      name: 'token.winx',
      cookieOptions: {
        path: '/',
        domain: '',
        // Only send cookie via HTTPs to mitigate man-in-the-middle attacks. (default: false in develop and true in production)
        secure: true,
        // Only send cookie via HTTP requests, do not allow access of cookie from JS to mitigate XSS attacks. (default: false in develop and true in production)
        httpOnly: true,
      },
    },
    csrf: {
      cookieKey: '',
      cookieOptions: {
        path: '/',
        // Only send cookie via HTTPs to mitigate man-in-the-middle attacks (default: false in develop and true in production)
        httpOnly: true,
        // Only send cookie via HTTP requests, do not allow access of cookie from JS to mitigate XSS attacks (default: false in develop and true in production)
        secure: true,
        sameSite: 'strict',
      },
      methodsToProtect: ['POST', 'PUT', 'PATCH'],
      excludedUrls: [],
      encryptSecret: randomBytes(22).toString('base64'),
      encryptAlgorithm: 'aes-256-cbc',
    }
  }
})

Composables

useAuth

<script setup lang="ts">
import { useAuth } from "#imports";

const { login, logout } = useAuth();

const code = ref('');

// Login
const singIn = async () => {
  await login({ code });
}

// logout
const SignOut = async () => {
  await logout();
}
</script>

<template>
  <input v-model="code" type="text" class="form-control">
  
  <button @click="singIn()">Login</button>
  <!-- or -->
  <button @click="$auth.login({ code })">Login</button>
  
  <button @click="SignOut()">Logout</button>
  <!-- or -->
  <button @click="$auth.logout()">Logout</button>
</template>

Options useAuth()

import { useAuth } from "#imports";

const {
  setUser, // Update user data locally.
  fetchUser, // Fetch user in API and update locally.
  startLogin, // It waits for the user document to be sent to the API, the email with the authentication code is sent as a response. In some cases, the API might send an authentication token if the login type doesn't require the code.
  login, // Expects a code and returns a token for authentication.
  logout, // Log off the system.
  isAuthenticated // Informs if it is authenticated or not.
} useAuth();

useApiClient

<script setup lang="ts">
import { useSupabaseClient } from "#imports";

const client = useSupabaseClient();

await client('/user');
</script>

useAuthUser

Logged in user data

<script setup lang="ts">
import { useAuthUser } from "#imports";

const user = useAuthUser();
</script>

<template>
  <pre>{{user}}</pre>
</template>

useCsrf

Use this composable if you need to access to the CSRF token value.

const { csrf } = useCsrf()
console.log(csrf) // something like: mo4+MrFaeXP7fhAie0o2qw==:tLUaqtHW6evx/coGQVAhtGAR+v6cxgFtrqmkOsuAMag8PHRnMwpbGGUO0TPJjL+4

const { data } = await useFetch('/api/login', { method: 'POST', body: {}, headers: { "csrf-token": csrf }})

// or

const { data } = await useFetch('/api/login', { method: 'POST', body: { ...body, _csrf: csrf } })

Server Services

serverClient

import { serverClient } from '#auth/server';
import type { ICompanyServerResponse } from '@/types';

export default defineEventHandler(async (event): Promise<ICompanyServerResponse> => {
  const client = serverClient(event);
  const body = await readBody(event);

  return await client('/company', {
    method: 'POST',
    body,
  });
});

serverAuthUser

This function is similar to the useAuthUser composable but is used in server routes.

import { assertMethod } from 'h3';
import { serverAuthUser } from '#auth/server';

export default defineEventHandler(async (event) => {
  assertMethod(event, 'GET');

  const user = await serverAuthUser(event);
});

Helpers

$auth

This helper provides the useAuth() functions.

const { $auth } = useNuxtApp()

$auth.login({ values... })

$csrf

This helper provides the crsf

const { $csrf } = useNuxtApp()

console.log($csrf()) //return csrf

Server Routes

The authentication module uses these server routes. They are for exclusive use.

  • /api/login
  • /api/logout
  • /api/me
  • /api/start