|
| 1 | +import { defineNuxtModule, addServerHandler, createResolver } from '@nuxt/kit' |
| 2 | +import { defu } from 'defu' |
| 3 | + |
| 4 | +export interface ModuleOptions { |
| 5 | + username?: string |
| 6 | + password?: string |
| 7 | + realm: string |
| 8 | + whitelistedRoutes: string[] |
| 9 | + enabled: boolean |
| 10 | +} |
| 11 | + |
| 12 | +export default defineNuxtModule<ModuleOptions>({ |
| 13 | + meta: { |
| 14 | + name: 'nuxt-basic-auth', |
| 15 | + configKey: 'basicAuth' |
| 16 | + }, |
| 17 | + defaults: { |
| 18 | + username: process.env.BASIC_AUTH_USERNAME, |
| 19 | + password: process.env.BASIC_AUTH_PASSWORD, |
| 20 | + realm: process.env.BASIC_AUTH_REALM || 'default', |
| 21 | + whitelistedRoutes: [], |
| 22 | + enabled: true |
| 23 | + }, |
| 24 | + setup (options, nuxt) { |
| 25 | + // Check if enabled |
| 26 | + if (!options.enabled) { |
| 27 | + return |
| 28 | + } |
| 29 | + // Check if config is present |
| 30 | + if (!options.username) { |
| 31 | + throw new Error('BasicAuth username not set. Either use runtimeConfig or \'.env\' with BASIC_AUTH_USERNAME') |
| 32 | + } |
| 33 | + if (!options.password) { |
| 34 | + throw new Error('BasicAuth password not set. Either use runtimeConfig or \'.env\' with BASIC_AUTH_PASSWORD') |
| 35 | + } |
| 36 | + |
| 37 | + // Copy module config in server runtimeConfig |
| 38 | + nuxt.options.runtimeConfig.basicAuth = defu(nuxt.options.runtimeConfig.basicAuth, options) |
| 39 | + |
| 40 | + // Transpile runtime |
| 41 | + const { resolve } = createResolver(import.meta.url) |
| 42 | + const runtimeDir = resolve('./runtime') |
| 43 | + nuxt.options.build.transpile.push(runtimeDir) |
| 44 | + |
| 45 | + addServerHandler({ |
| 46 | + middleware: true, |
| 47 | + handler: resolve(runtimeDir, 'server/middleware/serverHandler') |
| 48 | + }) |
| 49 | + } |
| 50 | +}) |
| 51 | + |
| 52 | +declare module '@nuxt/schema' { |
| 53 | + interface RuntimeConfig |
| 54 | + { |
| 55 | + basicAuth: ModuleOptions |
| 56 | + } |
| 57 | +} |
0 commit comments