winx-auth
TypeScript icon, indicating that this package has built-in type declarations

2.1.18 • Public • Published

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

Dependencies (5)

Dev Dependencies (14)

Package Sidebar

Install

npm i winx-auth

Weekly Downloads

9

Version

2.1.18

License

MIT

Unpacked Size

50.5 kB

Total Files

52

Last publish

Collaborators

  • tiwinx
  • alissonra