Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test: LDP-2492: Add mocked backend for Drupal login form #252

Draft
wants to merge 8 commits into
base: 2.x
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
"dist",
"playground/components",
"playground/pages",
"playground/app.vue"
"playground/app.vue",
"playground/middleware"
],
"scripts": {
"prepack": "nuxt-module-build",
Expand Down
14 changes: 14 additions & 0 deletions playground/components/global/DrupalForm.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<template>
<form :formId="formId" :method="method" v-bind="attributes" :action="useRoute().fullPath" class="drupal-form">
<slot><div v-html="content" /></slot>
</form>
</template>

<script setup lang="ts">
const props = defineProps<{
formId: String,
attributes: Object,
method: String,
content?: String,
}>()
</script>
16 changes: 0 additions & 16 deletions playground/middleware/redirect.global.ts

This file was deleted.

7 changes: 7 additions & 0 deletions playground/server/api/[...].ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export default defineEventHandler((event) => {
event.node.res.statusCode = 404
return {
status: 'error',
message: 'Not Found'
}
})
20 changes: 20 additions & 0 deletions playground/server/api/user/login.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
export default defineEventHandler(async (event) => {
if (event.node.req.method === 'POST') {
const formData = await readFormData(event)
const username = formData.get('name')
const password = formData.get('pass')

if (username === 'admin' || password === 'drupal123') {
setHeader(event, 'Set-Cookie', 'SSESSf9f2dc90f4drupal=k8WpMQCcQ-test; Expires=Fri, 13-Sep-2024 18:47:37 GMT; Max-Age=2000000; Path=/; Domain=localhost; Secure; HttpOnly; SameSite=Lax');

return {"redirect":{"external":false,"url":"/node/1","statusCode":301},"messages":[]}
} else if (username !== 'admin' || password !== 'drupal123') {
return {
"title":"Log in","messages":{"error":["Unrecognized username or password. \u003Ca href=\u0022\/user\/password\u0022\u003EForgot your password?\u003C\/a\u003E"]},"breadcrumbs":[{"frontpage":true,"url":"\/","label":"Home"}],"metatags":{"meta":[],"link":[]},"content_format":"json","content":{"element":"drupal-form","formId":"user_login_form","attributes":{"class":["user-login-form"],"dataDrupalSelector":"user-login-form"},"method":"post","content":"\u003Cdiv class=\u0022js-form-item form-item js-form-type-textfield form-item-name js-form-item-name\u0022\u003E\n \u003Clabel for=\u0022edit-name\u0022 class=\u0022form-item__label js-form-required form-required\u0022\u003EUsername\u003C\/label\u003E\n \u003Cinput autocorrect=\u0022none\u0022 autocapitalize=\u0022none\u0022 spellcheck=\u0022false\u0022 autofocus=\u0022autofocus\u0022 autocomplete=\u0022username\u0022 data-drupal-selector=\u0022edit-name\u0022 type=\u0022text\u0022 id=\u0022edit-name\u0022 name=\u0022name\u0022 value=\u0022admin123\u0022 size=\u002260\u0022 maxlength=\u002260\u0022 class=\u0022form-text required error form-element form-element--type-text form-element--api-textfield\u0022 required=\u0022required\u0022 aria-required=\u0022true\u0022 aria-invalid=\u0022true\u0022 \/\u003E\n\n \u003C\/div\u003E\n\u003Cdiv class=\u0022js-form-item form-item js-form-type-password form-item-pass js-form-item-pass\u0022\u003E\n \u003Clabel for=\u0022edit-pass\u0022 class=\u0022form-item__label js-form-required form-required\u0022\u003EPassword\u003C\/label\u003E\n \u003Cinput autocomplete=\u0022current-password\u0022 data-drupal-selector=\u0022edit-pass\u0022 type=\u0022password\u0022 id=\u0022edit-pass\u0022 name=\u0022pass\u0022 size=\u002260\u0022 maxlength=\u0022128\u0022 class=\u0022form-text required form-element form-element--type-password form-element--api-password\u0022 required=\u0022required\u0022 aria-required=\u0022true\u0022 \/\u003E\n\n \u003C\/div\u003E\n\u003Cinput data-drupal-selector=\u0022form-y0dcq5st-2releayznqf-qaeu2krrwig77u-4x69m1u\u0022 type=\u0022hidden\u0022 name=\u0022form_build_id\u0022 value=\u0022form-y0DCq5St-2rElEaYZnqF-QAeU2KrrWiG77u-4x69M1U\u0022 \/\u003E\n\u003Cinput data-drupal-selector=\u0022edit-user-login-form\u0022 type=\u0022hidden\u0022 name=\u0022form_id\u0022 value=\u0022user_login_form\u0022 \/\u003E\n\u003Cdiv data-drupal-selector=\u0022edit-actions\u0022 class=\u0022form-actions js-form-wrapper form-wrapper\u0022 id=\u0022edit-actions\u0022\u003E\u003Cinput class=\u0022button--primary button js-form-submit form-submit\u0022 data-drupal-selector=\u0022edit-submit\u0022 type=\u0022submit\u0022 id=\u0022edit-submit\u0022 name=\u0022op\u0022 value=\u0022Log in\u0022 \/\u003E\n\u003C\/div\u003E\n"},"page_layout":"default","local_tasks":[]
}
}
}
return {
"title":"Log in","messages":[],"breadcrumbs":[{"frontpage":true,"url":"\/","label":"Home"}],"metatags":{"meta":[],"link":[]},"content_format":"json","content":{"element":"drupal-form","formId":"user_login_form","attributes":{"class":["user-login-form"],"dataDrupalSelector":"user-login-form"},"method":"post","content":"\u003Cdiv class=\u0022js-form-item form-item js-form-type-textfield form-item-name js-form-item-name\u0022\u003E\n \u003Clabel for=\u0022edit-name\u0022 class=\u0022form-item__label js-form-required form-required\u0022\u003EUsername\u003C\/label\u003E\n \u003Cinput autocorrect=\u0022none\u0022 autocapitalize=\u0022none\u0022 spellcheck=\u0022false\u0022 autofocus=\u0022autofocus\u0022 autocomplete=\u0022username\u0022 data-drupal-selector=\u0022edit-name\u0022 type=\u0022text\u0022 id=\u0022edit-name\u0022 name=\u0022name\u0022 value=\u0022\u0022 size=\u002260\u0022 maxlength=\u002260\u0022 class=\u0022form-text required form-element form-element--type-text form-element--api-textfield\u0022 required=\u0022required\u0022 aria-required=\u0022true\u0022 \/\u003E\n\n \u003C\/div\u003E\n\u003Cdiv class=\u0022js-form-item form-item js-form-type-password form-item-pass js-form-item-pass\u0022\u003E\n \u003Clabel for=\u0022edit-pass\u0022 class=\u0022form-item__label js-form-required form-required\u0022\u003EPassword\u003C\/label\u003E\n \u003Cinput autocomplete=\u0022current-password\u0022 data-drupal-selector=\u0022edit-pass\u0022 type=\u0022password\u0022 id=\u0022edit-pass\u0022 name=\u0022pass\u0022 size=\u002260\u0022 maxlength=\u0022128\u0022 class=\u0022form-text required form-element form-element--type-password form-element--api-password\u0022 required=\u0022required\u0022 aria-required=\u0022true\u0022 \/\u003E\n\n \u003C\/div\u003E\n\u003Cinput data-drupal-selector=\u0022form-6ngyrvfrmgfogyhp4piezpfq5nj09qszrlhrch4nvzi\u0022 type=\u0022hidden\u0022 name=\u0022form_build_id\u0022 value=\u0022form-6NGYrVfrmgfoGYHP4piEzpFq5Nj09QszRLhRCH4NvZI\u0022 \/\u003E\n\u003Cinput data-drupal-selector=\u0022edit-user-login-form\u0022 type=\u0022hidden\u0022 name=\u0022form_id\u0022 value=\u0022user_login_form\u0022 \/\u003E\n\u003Cdiv data-drupal-selector=\u0022edit-actions\u0022 class=\u0022form-actions js-form-wrapper form-wrapper\u0022 id=\u0022edit-actions\u0022\u003E\u003Cinput class=\u0022button--primary button js-form-submit form-submit\u0022 data-drupal-selector=\u0022edit-submit\u0022 type=\u0022submit\u0022 id=\u0022edit-submit\u0022 name=\u0022op\u0022 value=\u0022Log in\u0022 \/\u003E\n\u003C\/div\u003E\n"},"page_layout":"default","local_tasks":[]
}
})
39 changes: 39 additions & 0 deletions playground/server/middleware/drupalFormHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
export default defineEventHandler(async (event) => {
const runtimeConfig = useRuntimeConfig()
const { ceApiEndpoint, drupalBaseUrl, serverDrupalBaseUrl } = runtimeConfig.public.drupalCe
const fetchUrl = serverDrupalBaseUrl ? serverDrupalBaseUrl : drupalBaseUrl

if (event.node.req.method === 'POST') {
const formData = await readFormData(event)

if (formData) {
const targetUrl = event.node.req.url
const response = await $fetch.raw(fetchUrl + ceApiEndpoint + targetUrl, {
method: 'POST',
body: formData,
}).catch((error) => {
event.context.drupalCeCustomPageResponse = {
error: {
data: error,
statusCode: error.statusCode || 400,
message: error.message || 'Fetch error. See drupalFormHandler.',
}
}
})

if (response) {
event.context.drupalCeCustomPageResponse = {
_data: response._data,
headers: Object.fromEntries(response.headers.entries()),
}
return
}
} else {
throw createError({
statusCode: 400,
statusMessage: 'Bad Request',
message: 'No or invalid form data given. See drupalFormHandler.',
})
}
}
})
3 changes: 1 addition & 2 deletions src/module.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { fileURLToPath } from 'url'
import { defineNuxtModule, addPlugin, addServerPlugin, createResolver, addImportsDir, addServerHandler } from '@nuxt/kit'
import { defineNuxtModule, addServerPlugin, createResolver, addImportsDir, addServerHandler } from '@nuxt/kit'
import { defu } from 'defu'
import type { NuxtOptionsWithDrupalCe } from './types'

Expand Down Expand Up @@ -59,7 +59,6 @@ export default defineNuxtModule<ModuleOptions>({
const { resolve } = createResolver(import.meta.url)
const runtimeDir = fileURLToPath(new URL('./runtime', import.meta.url))
nuxt.options.build.transpile.push(runtimeDir)
addPlugin(resolve(runtimeDir, 'plugin'))
if (options.serverLogLevel) {
addServerPlugin(resolve(runtimeDir, 'server/plugins/errorLogger'))
}
Expand Down
39 changes: 32 additions & 7 deletions src/runtime/composables/useDrupalCe/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { appendResponseHeader } from 'h3'
import type { UseFetchOptions } from '#app'
import type { $Fetch, NitroFetchRequest } from 'nitropack'
import { getDrupalBaseUrl, getMenuBaseUrl } from './server'
import { useRuntimeConfig, useState, useFetch, navigateTo, createError, h, resolveComponent, setResponseStatus, useNuxtApp, useRequestHeaders, ref, watch } from '#imports'
import { useRuntimeConfig, useState, useFetch, navigateTo, createError, h, resolveComponent, setResponseStatus, useNuxtApp, useRequestHeaders, ref, watch, useRequestEvent } from '#imports'

export const useDrupalCe = () => {
const config = useRuntimeConfig().public.drupalCe
Expand Down Expand Up @@ -116,9 +116,36 @@ export const useDrupalCe = () => {
page_layout: 'default',
title: '',
}))
const serverResponse = useState('server-response', () => null)
useFetchOptions.key = `page-${path}`
const page = ref(null)
const pageError = ref(null)

const { data: page, error } = await useCeApi(path, useFetchOptions, true)
if (import.meta.server) {
serverResponse.value = useRequestEvent(nuxtApp).context.drupalCeCustomPageResponse
}

// Check if the page data is already provided, e.g. by a form response.
if (serverResponse.value) {
if (serverResponse.value._data) {
page.value = serverResponse.value._data
passThroughHeaders(nuxtApp, serverResponse.value.headers)
} else if (serverResponse.value.error) {
pageError.value = serverResponse.value.error
}
// Clear the server response state after it was sent to the client.
if (import.meta.client) {
serverResponse.value = null
}
} else {
const { data, error } = await useCeApi(path, useFetchOptions, true)
page.value = data.value
pageError.value = error.value
}

if (page.value?.messages) {
pushMessagesToState(page.value.messages)
}

if (page?.value?.redirect) {
await callWithNuxt(nuxtApp, navigateTo, [
Expand All @@ -128,13 +155,11 @@ export const useDrupalCe = () => {
return pageState
}

if (error.value) {
overrideErrorHandler ? overrideErrorHandler(error) : pageErrorHandler(error, { config, nuxtApp })
page.value = error.value?.data
if (pageError.value) {
overrideErrorHandler ? overrideErrorHandler(pageError) : pageErrorHandler(pageError, { config, nuxtApp })
page.value = pageError.value?.data
}

page.value?.messages && pushMessagesToState(page.value.messages)

pageState.value = page
return page
}
Expand Down
4 changes: 0 additions & 4 deletions src/runtime/plugin.ts

This file was deleted.